first commit
This commit is contained in:
commit
a36c433e0a
|
@ -0,0 +1,176 @@
|
|||
# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore
|
||||
|
||||
# Logs
|
||||
|
||||
logs
|
||||
_.log
|
||||
npm-debug.log_
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# Caches
|
||||
|
||||
.cache
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
|
||||
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
||||
|
||||
# Runtime data
|
||||
|
||||
pids
|
||||
_.pid
|
||||
_.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Snowpack dependency directory (https://snowpack.dev/)
|
||||
|
||||
web_modules/
|
||||
|
||||
# TypeScript cache
|
||||
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
|
||||
.eslintcache
|
||||
|
||||
# Optional stylelint cache
|
||||
|
||||
.stylelintcache
|
||||
|
||||
# Microbundle cache
|
||||
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variable files
|
||||
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
|
||||
.parcel-cache
|
||||
|
||||
# Next.js build output
|
||||
|
||||
.next
|
||||
out
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
|
||||
.nuxt
|
||||
dist
|
||||
|
||||
# Gatsby files
|
||||
|
||||
# Comment in the public line in if your project uses Gatsby and not Next.js
|
||||
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
|
||||
.vuepress/dist
|
||||
|
||||
# vuepress v2.x temp and cache directory
|
||||
|
||||
.temp
|
||||
|
||||
# Docusaurus cache and generated files
|
||||
|
||||
.docusaurus
|
||||
|
||||
# Serverless directories
|
||||
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
|
||||
.dynamodb/
|
||||
|
||||
# TernJS port file
|
||||
|
||||
.tern-port
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
|
||||
.vscode-test
|
||||
|
||||
# yarn v2
|
||||
|
||||
.yarn/cache
|
||||
.yarn/unplugged
|
||||
.yarn/build-state.yml
|
||||
.yarn/install-state.gz
|
||||
.pnp.*
|
||||
|
||||
# IntelliJ based IDEs
|
||||
.idea
|
||||
|
||||
# Finder (MacOS) folder config
|
||||
.DS_Store
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
# tambak server
|
||||
|
||||
### this is a node express js server that receive data from esp-01 and send it ti flutter app using socket io
|
||||
|
||||
![alt text](image.png)
|
||||
![alt text](image-1.png)
|
|
@ -0,0 +1,22 @@
|
|||
const mysql = require('mysql');
|
||||
const dotenv = require('dotenv');
|
||||
|
||||
dotenv.config();
|
||||
|
||||
// Connect to the MySQL database
|
||||
const connection = mysql.createConnection({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
database: process.env.DB_NAME
|
||||
});
|
||||
|
||||
// connection.connect((err) => {
|
||||
// if (err) {
|
||||
// console.error('Error connecting to MySQL database: ' + err.stack);
|
||||
// return;
|
||||
// }
|
||||
// console.log('Connected to MySQL database as id ' + connection.threadId);
|
||||
// })
|
||||
|
||||
module.exports = {connection}
|
Binary file not shown.
After Width: | Height: | Size: 22 KiB |
|
@ -0,0 +1,145 @@
|
|||
const express = require('express');
|
||||
const http = require('http');
|
||||
const cors = require('cors');
|
||||
const dotenv = require('dotenv');
|
||||
const socket = require('./socket');
|
||||
const app = express();
|
||||
const server = http.createServer(app);
|
||||
const io = socket.init(server);
|
||||
const iosend = socket.getIO();
|
||||
const conn = require('./conn.js');
|
||||
const connection = conn.connection;
|
||||
|
||||
dotenv.config();
|
||||
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
// app.use(fileUpload());
|
||||
app.options('*', cors());
|
||||
app.use(cors());
|
||||
|
||||
|
||||
async function insert_data(water_height, status) {
|
||||
const query_insert = 'INSERT INTO tb_data (water_height, status) VALUES (?, ?)';
|
||||
const result_insert = await new Promise((resolve, reject) => {
|
||||
connection.query(query_insert, [water_height, status], (err, result) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
app.post('/', async (req, res) => {
|
||||
var data = req.body;
|
||||
try {
|
||||
const query_search = 'Select * from tb_data';
|
||||
const result_search = await new Promise((resolve, reject) => {
|
||||
connection.query(query_search, (err, result) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
})
|
||||
var now = new Date();
|
||||
|
||||
const status = data.danger_level == 1 ? 2 : data.warning_level == 1 ? 1 : 0;
|
||||
if (result_search.length > 0) {
|
||||
const last_data = result_search[result_search.length - 1];
|
||||
|
||||
var converted_time_last = new Date(last_data.created_at);
|
||||
now = now.getTime();
|
||||
converted_time_last = converted_time_last.getTime();
|
||||
var differenceInSeconds = (now - converted_time_last) / 1000;
|
||||
console.log(differenceInSeconds, "second");
|
||||
|
||||
|
||||
const thresholds = {
|
||||
2: 30,
|
||||
1: 60,
|
||||
default: 120
|
||||
};
|
||||
|
||||
const threshold = thresholds[status] || thresholds.default;
|
||||
|
||||
if (differenceInSeconds > threshold) {
|
||||
insert_data(data.water_height, status);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
} else {
|
||||
|
||||
insert_data(data.water_height, status);
|
||||
}
|
||||
|
||||
console.log(data);
|
||||
io.emit('data', data);
|
||||
res.status(200).json({ message: 'success', data: data });
|
||||
} catch (error) {
|
||||
console.log("ini error post", error);
|
||||
res.status(500).json({ message: 'Internal server error' });
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
|
||||
app.get('/', async (req, res) => {
|
||||
const date = req.query.date;
|
||||
console.log(date, "ini di get");
|
||||
|
||||
const query_search = date == null
|
||||
? 'SELECT * FROM tb_data ORDER BY created_at DESC LIMIT 20'
|
||||
: 'SELECT * FROM tb_data WHERE created_at LIKE "%' + date + '%" ORDER BY created_at DESC';
|
||||
|
||||
const result_search = await new Promise((resolve, reject) => {
|
||||
connection.query(query_search, (err, result) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
})
|
||||
res.status(200).json({ message: 'success', data: result_search });
|
||||
|
||||
})
|
||||
|
||||
// app error handler
|
||||
app.use((err, req, res, next) => {
|
||||
console.log(err);
|
||||
res.status(500).send('Something broke!');
|
||||
});
|
||||
|
||||
io.on('connection', (socket) => {
|
||||
let userID = socket.id;
|
||||
console.log('A user connected: ' + userID);
|
||||
|
||||
socket.on('scan_dia', (data) => {
|
||||
console.log('Received scan_dia event: ' + data);
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
console.log('User disconnected: ' + userID);
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
app,
|
||||
server,
|
||||
io
|
||||
};
|
||||
|
||||
const port = process.env.PORT || 3001;
|
||||
|
||||
// Start the server
|
||||
server.listen(port, () => {
|
||||
console.log(`Server is running on http://localhost:${port}`);
|
||||
});
|
|
@ -0,0 +1,254 @@
|
|||
const express = require('express');
|
||||
const http = require('http');
|
||||
const cors = require('cors');
|
||||
const dotenv = require('dotenv');
|
||||
const socket = require('./socket');
|
||||
const app = express();
|
||||
const server = http.createServer(app);
|
||||
const io = socket.init(server);
|
||||
const iosend = socket.getIO();
|
||||
const conn = require('./conn.js');
|
||||
const connection = conn.connection;
|
||||
|
||||
dotenv.config();
|
||||
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
// app.use(fileUpload());
|
||||
app.options('*', cors());
|
||||
app.use(cors());
|
||||
|
||||
// Helper function to format date
|
||||
const formatDate = (date) => {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
const hours = String(date.getHours()).padStart(2, '0');
|
||||
const minutes = String(date.getMinutes()).padStart(2, '0');
|
||||
const seconds = String(date.getSeconds()).padStart(2, '0');
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
|
||||
};
|
||||
|
||||
async function insert_data(data) {
|
||||
const parts = data.split(',');
|
||||
const query_insert = 'INSERT INTO tb_data (ultrasonic1, ultrasonic2,ph1,ph2,ph3,tds1, tds2,tds3)values(?, ?,?,?,?,?,?,?)';
|
||||
const result_insert = await new Promise((resolve, reject) => {
|
||||
connection.query(query_insert, [parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[6], parts[6]], (err, result) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
app.post('/', async (req, res) => {
|
||||
var { value } = req.body;
|
||||
|
||||
const query_search = 'Select * from tb_data';
|
||||
|
||||
try {
|
||||
const result_search = await new Promise((resolve, reject) => {
|
||||
connection.query(query_search, (err, result) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
var now = new Date();
|
||||
|
||||
if (result_search.length > 0) {
|
||||
const last_data = result_search[result_search.length - 1];
|
||||
|
||||
var converted_time_last = new Date(last_data.waktu);
|
||||
|
||||
now = now.getTime();
|
||||
converted_time_last = converted_time_last.getTime();
|
||||
var differenceInSeconds = (now - converted_time_last) / 1000;
|
||||
console.log(differenceInSeconds, "second");
|
||||
if (differenceInSeconds > 10) {
|
||||
insert_data(value);
|
||||
}
|
||||
} else {
|
||||
insert_data(value);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.log("error post", error);
|
||||
res.status(500).send(error);
|
||||
}
|
||||
const query_status = 'Select * from tb_gerbang';
|
||||
|
||||
const result_status = await new Promise((resolve, reject) => {
|
||||
connection.query(query_status, (err, result) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
const status = result_status[0].status;
|
||||
|
||||
io.emit('data', { value, status });
|
||||
|
||||
res.status(200).send(status);
|
||||
|
||||
// res.status(200).send('idle');
|
||||
})
|
||||
|
||||
app.get('/', async (req, res) => {
|
||||
const date = req.query.date;
|
||||
const query_search = 'Select * from tb_data order by waktu desc limit 10';
|
||||
|
||||
const result_search = await new Promise((resolve, reject) => {
|
||||
connection.query(query_search, (err, result) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
})
|
||||
res.status(200).send(result_search);
|
||||
})
|
||||
|
||||
app.post('/gerbang', async (req, res) => {
|
||||
const query = 'Select * from tb_gerbang';
|
||||
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
connection.query(query, (err, result) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
const status_gerbang = result[0].status;
|
||||
const status_update = status_gerbang == "buka" ? "tutup" : "buka";
|
||||
|
||||
const query_update = 'UPDATE tb_gerbang SET status = ?';
|
||||
|
||||
const result_update = await new Promise((resolve, reject) => {
|
||||
connection.query(query_update, [status_update], (err, result) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
res.status(200).send(result);
|
||||
|
||||
})
|
||||
|
||||
// Helper function to get random number in range
|
||||
const getRandomInRange = (min, max) => {
|
||||
return (Math.random() * (max - min) + min).toFixed(2);
|
||||
};
|
||||
|
||||
|
||||
app.post('/dummy_data', async (req, res) => {
|
||||
// Date range
|
||||
const startDate = new Date(2024, 5, 20); // July 15, 2024
|
||||
const endDate = new Date(2024, 6, 31); // July 31, 2024
|
||||
|
||||
// Value ranges
|
||||
const ultrasonicRange = [150, 200];
|
||||
const phRange = [6.26, 7.10];
|
||||
const tdsRange = [1370, 1410];
|
||||
|
||||
// Loop to generate and insert data
|
||||
let currentDate = startDate;
|
||||
while (currentDate <= endDate) {
|
||||
for (let hour = 0; hour < 24; hour++) {
|
||||
currentDate.setHours(hour);
|
||||
|
||||
// Generate random seconds
|
||||
const randomSeconds = Math.floor(Math.random() * 60);
|
||||
currentDate.setSeconds(randomSeconds);
|
||||
|
||||
const waktu = formatDate(currentDate);
|
||||
const ultrasonic1 = getRandomInRange(...ultrasonicRange);
|
||||
const ultrasonic2 = getRandomInRange(...ultrasonicRange);
|
||||
const ph1 = getRandomInRange(...phRange);
|
||||
const ph2 = getRandomInRange(...phRange);
|
||||
const ph3 = getRandomInRange(...phRange);
|
||||
const tds1 = getRandomInRange(...tdsRange);
|
||||
const tds2 = getRandomInRange(...tdsRange);
|
||||
const tds3 = getRandomInRange(...tdsRange);
|
||||
|
||||
const query = `INSERT INTO tb_data (waktu, ultrasonic1, ultrasonic2, ph1, ph2, ph3, tds1, tds2, tds3)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
|
||||
|
||||
connection.query(query, [waktu, ultrasonic1, ultrasonic2, ph1, ph2, ph3, tds1, tds2, tds3], (error) => {
|
||||
if (error) {
|
||||
console.error('Error inserting data:', error);
|
||||
return res.status(500).send('Error inserting data');
|
||||
}
|
||||
});
|
||||
}
|
||||
currentDate.setDate(currentDate.getDate() + 1);
|
||||
}
|
||||
|
||||
res.send('Dummy data inserted successfully');
|
||||
});
|
||||
// GET endpoint to fetch and format data
|
||||
app.get('/dummy_data', async (req, res) => {
|
||||
const query = 'SELECT * FROM tb_data';
|
||||
connection.query(query, (error, results) => {
|
||||
if (error) {
|
||||
console.error('Error fetching data:', error);
|
||||
return res.status(500).send('Error fetching data');
|
||||
}
|
||||
|
||||
// Format the 'waktu' field for each result
|
||||
const formattedResults = results.map(row => ({
|
||||
...row,
|
||||
waktu: formatDate(new Date(row.waktu))
|
||||
}));
|
||||
|
||||
res.send(formattedResults);
|
||||
});
|
||||
});
|
||||
|
||||
// app error handler
|
||||
app.use((err, req, res, next) => {
|
||||
console.log(err);
|
||||
res.status(500).send('Something broke!');
|
||||
});
|
||||
|
||||
io.on('connection', (socket) => {
|
||||
let userID = socket.id;
|
||||
console.log('A user connected: ' + userID);
|
||||
|
||||
socket.on('scan_dia', (data) => {
|
||||
console.log('Received scan_dia event: ' + data);
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
console.log('User disconnected: ' + userID);
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
app,
|
||||
server,
|
||||
io
|
||||
};
|
||||
|
||||
const port = process.env.PORT || 3001;
|
||||
|
||||
// Start the server
|
||||
server.listen(port, () => {
|
||||
console.log(`Server is running on http://localhost:${port}`);
|
||||
});
|
|
@ -0,0 +1,27 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
// Enable latest features
|
||||
"lib": ["ESNext", "DOM"],
|
||||
"target": "ESNext",
|
||||
"module": "ESNext",
|
||||
"moduleDetection": "force",
|
||||
"jsx": "react-jsx",
|
||||
"allowJs": true,
|
||||
|
||||
// Bundler mode
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"noEmit": true,
|
||||
|
||||
// Best practices
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
|
||||
// Some stricter flags (disabled by default)
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noPropertyAccessFromIndexSignature": false
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"name": "tambak",
|
||||
"version": "1.0.0",
|
||||
"description": "tambak backend",
|
||||
"main": "index.js",
|
||||
"author": "kicap",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"dotenv": "^16.4.5",
|
||||
"express": "^4.19.2",
|
||||
"express-form-data": "^2.0.23",
|
||||
"mysql": "^2.18.1",
|
||||
"socket.io": "^4.7.5"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
const socketio = require('socket.io');
|
||||
// const socketio_client = require('socket.io-client');
|
||||
const dotenv = require('dotenv');
|
||||
|
||||
dotenv.config();
|
||||
|
||||
// const socket_client = socketio_client("http://localhost:"+process.env.PORT);
|
||||
|
||||
let io;
|
||||
|
||||
function init(server) {
|
||||
io = socketio(server);
|
||||
return io;
|
||||
}
|
||||
|
||||
function getIO() {
|
||||
if (!io) {
|
||||
throw new Error('Socket.io not initialized');
|
||||
}
|
||||
return io;
|
||||
}
|
||||
|
||||
|
||||
|
||||
module.exports = {
|
||||
init,
|
||||
getIO,
|
||||
// socket_client
|
||||
};
|
Loading…
Reference in New Issue