commit 6f49cca0c194ecae53efffcad83bfdcce00e2e76 Author: kicap1992 Date: Sat Aug 3 12:44:43 2024 +0800 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9b1ee42 --- /dev/null +++ b/.gitignore @@ -0,0 +1,175 @@ +# 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 diff --git a/README.md b/README.md new file mode 100644 index 0000000..5d151d8 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# Traffic Light Disfunctio Monitoring (Node.js) + +### traffic light disfunction monitoring, this is the backend/ where it receive data from esp8266 and sen it to app using websocket + +![alt text](image.png) diff --git a/bun.lockb b/bun.lockb new file mode 100755 index 0000000..185b306 Binary files /dev/null and b/bun.lockb differ diff --git a/image.png b/image.png new file mode 100644 index 0000000..9857974 Binary files /dev/null and b/image.png differ diff --git a/index.js b/index.js new file mode 100644 index 0000000..0826bb8 --- /dev/null +++ b/index.js @@ -0,0 +1,111 @@ +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(); + + +dotenv.config(); + +app.use(express.json()); +app.use(express.urlencoded({ extended: true })); +// app.use(fileUpload()); +app.options('*', cors()); +app.use(cors()); + +function isValidDate(dateString) { + // Check if the string matches the format YYYY-MM-DD using a regular expression + const regex = /^\d{4}-\d{2}-\d{2}$/; + if (!regex.test(dateString)) { + return false; + } + + // Parse the string to a Date object + const date = new Date(dateString); + + // Check if the date is valid by comparing it with the components of the original string + const timestamp = date.getTime(); + if (isNaN(timestamp)) { + return false; + } + + // Further check to ensure that the date components match the input string + const [year, month, day] = dateString.split('-').map(Number); + if (date.getUTCFullYear() !== year || date.getUTCMonth() + 1 !== month || date.getUTCDate() !== day) { + return false; + } + + return true; +} + +function timeStringToDate(timeStr) { + const [hours, minutes, seconds] = timeStr.split(':').map(Number); + const date = new Date(); + date.setHours(hours, minutes, seconds, 0); + return date; +} + +// Handle POST requests to '/post' +app.post('/', async (req, res) => { + // Access the POST data sent in the request body + try { + var postData = req.body; + // console.log(postData); + const {no ,light ,value2 ,pln } = postData; + console.log(no ,light ,value2 ,pln); + // rms = value2 + iosend.emit('datanya', { + no : no, + light : light, + pln : pln, + rms : value2}); + + return res.status(200).send({ message: 'OK data' }); + + } catch (error) { + console.error(error); + return res.status(500).send({ message: 'Internal server error' }); + } + +}); + +app.get('/', async (req, res) => { + return res.status(200).send({ message: 'This is a GET request' }); + +}) + +// 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 || 3004; + +// Start the server +server.listen(port, () => { + console.log(`Server is running on http://localhost:${port}`); +}); diff --git a/jsconfig.json b/jsconfig.json new file mode 100644 index 0000000..238655f --- /dev/null +++ b/jsconfig.json @@ -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 + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..526b556 --- /dev/null +++ b/package.json @@ -0,0 +1,18 @@ +{ + "name": "traffic-light", + "version": "1.0.0", + "description": "Traffic light backend", + "main": "index.js", + "devDependencies": { + "@types/bun": "latest" + }, + "peerDependencies": { + "typescript": "^5.0.0" + }, + "dependencies": { + "dotenv": "^16.4.5", + "express": "^4.19.2", + "express-form-data": "^2.0.23", + "socket.io": "^4.7.5" + } +} \ No newline at end of file diff --git a/socket.js b/socket.js new file mode 100755 index 0000000..c0d73f3 --- /dev/null +++ b/socket.js @@ -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 +}; \ No newline at end of file