Failing to send MQ-4 sensor data using Nodemcu to my node.js server

70 Views Asked by At

I am new to IoT so this question might sound a bit dumb but I am stuck and can't seem to figure out a solution. I am trying to send data from my mq-4 sensor to the node.js server. The code I have shows no error but I can't get any data to show on my front-end.

This is my Arduino IDE code:

#include <ESP8266WiFi.h>
#include <WebSocketsClient.h>

const char* ssid = "";
const char* password = "";
const char* webSocketServer = "IPAdress:8080";

WebSocketsClient webSocket;


void setup() {
  Serial.begin(9600);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  webSocket.begin(webSocketServer, 8080);
}

void loop() {
  int sensorValue = analogRead(A0);
  String sensorValueStr = String(sensorValue);
  webSocket.sendTXT(sensorValueStr);
  webSocket.loop();

  delay(1000);
}

I made sure that my server is connected to my front-end.

This is my server code:

const WebSocket = require('ws');
const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    const html = fs.readFileSync('index.html', 'utf8');
    res.end(html);
  } else {
    res.writeHead(404);
    res.end();
  }
});
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    // Broadcast the actual sensor data to all connected clients
    wss.clients.forEach((client) => {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });
});
server.listen(8080, () => {
  console.log('Server is running on port 8080');
});

1

There are 1 best solutions below

0
ChipChop Gizmo On

It looks like that you are specifying the port as a part of your server IP

webSocketServer = "IPAdress:8080"

but then you are specifying the port again in

webSocket.begin(webSocketServer, 8080);

I think that you just need to specify the IP address without the ":8080" part?

I've tried various web socket libraries and settled on the "WebSockets2_Generic.h" (needed some tweaking for ESP8266/32 for PlatformIO) and it works great, the code is a bit different but it has a similar logic, if you specify a port in the WebSocket.begin() then it will use that or if you don't then it will use just whatever you've specified as the server address. Check the docs for WebSocketsClient.h I would imagine it works in a similar way.

If you wan to try WebSockets2_Generic you can download my library chipchop.io arduino library, I've modified the WebSockets2_Generic purely for ESP8266/32 so it's just the web socket client and it's quite small. You also have a pretty robust fully implemented web socket communication in the "ChipChopManager.h & .cpp" files, just tweak it to what you need (the backend is Node.js and I know it works 100%)

At a really quick glance your Node.js part looks correct and if you want to test your server the easiest way is to make a simple HTML page and try a web socket connection with Javascript

let socket = new WebSocket("ws://ipaddress:8080"); // be careful with "ws://" or "wss://", if your node server is not using a secure connection you will have to use ws://

socket.onopen = function(e) {
  console.log("Connection opened");
  socket.send("Howdy");
};

socket.onmessage = function(event) {
  let message = event.data
  console.log(message);
};

socket.onclose = function(event) {
  if (event.wasClean) {
    console.log("Connection closed cleanly");
  } else {
    
    console.log('Connection died');
  }
};

socket.onerror = function(error) {
  console.log(error);
};

Hope this helps