NodeJS server
•
Ditulis oleh Tim Pasti Oke
REGISTER
sendTelegram('-4554349110', `${message}`)
send_curl(data.urlcurl,data)
PONG
if (recipientSocket && recipientSocket.readyState === WebSocket.OPEN) {
recipientSocket.send('{"action":"ping","data":'+JSON.stringify(data)+'}')
}else{
//senderSocket.send('{"action":"data", "message":{"from":"bootani-b136771","to":"android-y4wJsO94M","pwdcontrol":"4R1WAOiMJ","cmd":"offline","saklar1":"00000000","saklar2":"00000000","saklar3":"00000000"}}')
senderSocket.send('{"action":"pong","data":'+JSON.stringify(data)+'}')
}
MESSAGE
recipientSocket.send(JSON.stringify({from: data.from,message: data.message}))
DATA
if (recipientSocket && recipientSocket.readyState === WebSocket.OPEN) {
// ================= versi lama ==========================
// recipientSocket.send(JSON.stringify({
// from: data.from,
// message: data
// }))
recipientSocket.send('{"action":"data","data":'+JSON.stringify(data)+'}')
}
PUBLISH
clients.forEach((clientSocket, clientId) => {
if (clientId.includes(data.to) && clientSocket.readyState === WebSocket.OPEN) {
clientSocket.send('{"action":"publish","data":'+JSON.stringify(data)+'}')
}
})
UPDATE
clients.forEach((clientSocket, clientId) => {
if (clientId.includes(data.to) && clientSocket.readyState === WebSocket.OPEN) {
clientSocket.send('{"action":"update","data":'+JSON.stringify(data)+'}')
}
})
send_curl(data.urlapi,data)
FULL CODE
const https = require('https')
function sendTelegram(chatId,pesan){
const data = JSON.stringify({
chat_id: chatId,
text: pesan
})
const options = {
hostname: 'api.telegram.org',
port: 443,
path: '/bot1624331807:AAEzRpaQqOcujBgonr9UlFt_TWP9FjijzKA/sendMessage',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
const req = https.request(options, res => {
res.on('data', d => {
process.stdout.write(d)
})
})
req.on('error', error => {
console.error(error)
})
req.write(data)
req.end()
}
function send_curl(s_host,postData){
const data = JSON.stringify(postData)
const url = new URL(s_host) // Gunakan URL object
const options = {
hostname: url.hostname, // Ambil hostname dari URL
path: url.pathname + url.search, // Gabungkan path + query (kalau ada)
port: 443,
method: 'POST',
/*
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
*/
}
const req = https.request(options, res => {
res.on('data', d => {
process.stdout.write(d)
})
})
req.on('error', error => {
console.error(error)
})
req.write(data)
req.end()
}
//|================================ =================================
//| membuat websocket server untuk menerima dan mengirim pesan
//| juga mensend curl ketika action = update
//| juga mensend telegram ketika action = register
//|================================ =================================
const WebSocket = require('ws')
const server = new WebSocket.Server({ port: 8080 })
const clients = new Map() // Use a Map to associate IDs with sockets
const fs = require('fs')
server.on('connection', (socket) => {
socket.on('message', (message) => {
const clientLog = clients.get("socketlog")
//if(clientLog)clientLog.send(JSON.stringify({from: "server",message: `${message}`}))
if(clientLog)clientLog.send(`${message}`)
// Extract the date and time components
// Get the current date and time
fs.appendFile('ws.log', '\n\r' + `${message}`, (err) => {
if (err) throw err
console.log('Data was appended to file!')
})
try {
//sendTelegram('aaa', `${message}`)
const { action, data } = JSON.parse(message)
if (action === 'register') {
// Register the client with an ID
clients.set(data.id, socket)
if(data.id.includes('android')){
console.log(`Client registered: ${data.id}`)
}else{
sendTelegram('-4554349110', `${message}`)
send_curl(data.urlapi,data)
console.log(`Client registered: ${data.id}`)
}
} else if (action === 'ping') {
// dikirim dari webclient ke ESP untuk memancing ping balik dari arduino
// mendapat ping dari arduino jika onLine
// mendapat pong dari server jika offline
const recipientSocket = clients.get(data.to)
const senderSocket = clients.get(data.from)
if (recipientSocket && recipientSocket.readyState === WebSocket.OPEN) {
recipientSocket.send('{"action":"ping","data":'+JSON.stringify(data)+'}')
}else{
//senderSocket.send('{"action":"data", "message":{"from":"bootani-b136771","to":"android-y4wJsO94M","pwdcontrol":"4R1WAOiMJ","cmd":"offline","saklar1":"00000000","saklar2":"00000000","saklar3":"00000000"}}')
senderSocket.send('{"action":"pong","data":'+JSON.stringify(data)+'}')
}
} else if (action === 'message') {
// dikirim dari webclient ke ESP
// untuk mengontrol ESP
const recipientSocket = clients.get(data.to)
if (recipientSocket && recipientSocket.readyState === WebSocket.OPEN) {
recipientSocket.send(JSON.stringify({
from: data.from,
message: data.message
}))
}
} else if (action === 'data') {
// dikirim dari webclient ke ESP
// untuk mengontrol ESP
const recipientSocket = clients.get(data.to)
if (recipientSocket && recipientSocket.readyState === WebSocket.OPEN) {
// ================= versi lama ==========================
// recipientSocket.send(JSON.stringify({
// from: data.from,
// message: data
// }))
recipientSocket.send('{"action":"data","data":'+JSON.stringify(data)+'}')
}
} else if (action === 'publish') {
// dikirim dari ESP ke webclient
// untuk memberitahukan kepada webclient untuk reload
// tidak perlu curl karena mysql sudah sinkron
// contoh pesannya {"action":"publish", "data":{"from":"esp-control","to":"android","cmd":"reload"}
// const recipientSocket = clients.get(data.to)
clients.forEach((clientSocket, clientId) => {
if (clientId.includes(data.to) && clientSocket.readyState === WebSocket.OPEN) {
clientSocket.send('{"action":"publish","data":'+JSON.stringify(data)+'}')
}
})
} else if (action === 'update') {
// dikirim dari ESP ke webclient
// untuk memberitahukan kepada webclient untuk reload
// juga mengupdate mysql melalui curl
// contoh pesannya {"action":"data","data":{"from":"esp-sensor","to":"android","cmd":"reload","urlapi":"' + S_urlPOST + '","message":{"action":"update","saklar1":"010011101","saklar2":"101010","saklar3":"gugugaga"}}}
//const recipientSocket = clients.get(data.to)
clients.forEach((clientSocket, clientId) => {
if (clientId.includes(data.to) && clientSocket.readyState === WebSocket.OPEN) {
clientSocket.send('{"action":"update","data":'+JSON.stringify(data)+'}')
}
})
send_curl(data.urlapi,data)
}
} catch (error) {
// Handle JSON parsing errors
sendTelegram('-4554349110','Error' + error + `${message}`)
}
})
socket.on('error', (error) => {
if (error.code === 'WS_ERR_INVALID_UTF8') {
console.error('Invalid UTF-8 sequence ignored:', error)
// Optionally, log the error or perform any other action
} else {
console.error('WebSocket error:', error)
}
})
socket.on('close', () => {
// Remove the client from the Map
for (const [id, client] of clients.entries()) {
if (client === socket) {
clients.delete(id)
console.log(`Client disconnected: ${id}`)
break
}
}
})
})
console.log('WebSocket server is running on ws://localhost:8080')
//|================================ =================================
//| membuat websocket client untuk mengirim pesan
//| ketika menerima curl via webserver
//|================================ =================================
// WebSocket client setup (connecting to WebSocket server at ws://localhost:8080)
const wsClient = new WebSocket('ws://ws.robot.protindo.com:8080')
// Event listener for when WebSocket connection is opened
wsClient.on('open', () => {
console.log('Connected to WebSocket server')
wsClient.send('{"action":"register","data":{"id":"jssocket","message":{"singer":"mltr http server","song":"on_connected"}}}')
fs.appendFile('wsclient.log', '\n\r datawsclient on connect :' , (err) => {
if (err) throw err
console.log('Data was appended to file!')
})
})
// Event listener for errors in the WebSocket client
wsClient.on('error', (error) => {
console.error('WebSocket error:', error)
})
// WebSocket message event (optional, can be used to listen to messages from WebSocket server)
wsClient.on('message', (data) => {
console.log('Received message from WebSocket server:', data)
wsClient.send('{"action":"register","data":{"id":"jssocket","message":{"singer":"mltr http server","song":"on_message"}}}')
fs.appendFile('wsclient.log', '\n\r datawsclient on MESSAGE :' + `${data}`, (err) => {
if (err) throw err
console.log('Data was appended to file!')
})
})
//|================================ =================================
//| Create an HTTP server to handle POST requests
//| kemudian mengirimkan pesan via websocket
//|================================ =================================
const http = require('http')
const webserver = http.createServer((req, res) => {
if (req.method === 'POST') {
let body = ''
// Collect the incoming data
req.on('data', chunk => {
body += chunk.toString()
})
// When the data is fully received
req.on('end', () => {
try {
fs.appendFile('wsclient-http.log', '\n\r Data POST Received:' + `${body}`, (err) => {
if (err) throw err
console.log('Data was appended to file!')
})
const data = JSON.parse(body) // Parse the POST data
console.log('Received POST data:', data)
// Check if WebSocket client is ready and send data
if (wsClient.readyState === WebSocket.OPEN) {
// Send the data to the WebSocket server
wsClient.send(JSON.stringify(data), (err) => {
if (err) {
console.error('Error sending data over WebSocket:', err)
} else {
console.log('Sent data to WebSocket server:', data)
}
})
// Respond to the HTTP client with success
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ message: 'Data sent to WebSocket server', status: 'success',data:data }))
} else {
// If WebSocket is not connected
res.writeHead(500, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'WebSocket is not connected' }))
}
} catch (error) {
// Handle JSON parsing errors
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Invalid JSON in POST request' }))
}
})
} else {
// Handle other request methods
res.writeHead(405, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Only POST method is allowed' }))
}
})
// Start the HTTP server
const PORT = 3000
if (!webserver.listening) {
webserver.listen(PORT, () => console.log('Server running on port 3000'))
}
/*
webserver.listen(PORT, () => {
console.log('HTTP server running on http://localhost:${PORT}')
})
*/
Butuh solusi instan siap pakai?
Dapatkan modul & script server production-ready langsung di web store kami.
Komentar
Belum ada komentar. Jadilah yang pertama memberikan komentar!