Hello,
I'm building a project to monitor sensor data in the field. Sensors connect to MKR1310 and broadcast details through LoRa. Receiving board (MKR1310) logs data and uses Serial1 to communicate with a MKR1010. Probably a bit clunky but gets me from outdoors to my WiFI network.
On my Macbook I've a Node JS Websocket Server running as per code provided. Function is to write data to a file and later on a database. This code works. Have tested this with a HTML page.
The sketch below is a cut down version to get the protocols between the MKR1010 and the WebSocket server working.
The only WebSockets event I ever get is 01 - Disconnected. No doubt (hopefully) a simple error in the sketch. There are a number of post on the forum and GitHub related to this but these have not helped me. I've tried numerous permutations of the WebSocket.begin function to no avail. The HTML page specifies localhost:8080.
I'd appreciate some help here as I'm thrashing about with this. Very frustrating for a retired ex Tech Enterprise Architect who should know better!!! To my mind this should be straight forward and hopefully provide a simple working mode for others. I have always looked to having simple and elegant code as we do seem to over engineer so much these days.
Frustrating - but beats crafting management and board papers!
Cheers
Nick
(PS am also, in parallel, using The Things Network and Arduino Cloud. Some interesting learning here and potential issue for later discussion)
The sketch ----------------------------------------
#include <Arduino.h>
#include <SPI.h>
#include <WiFiNINA.h>
#include <WebSocketsClient.h>
#define WIFI_SSID ""
int status = WL_IDLE_STATUS;
WiFiClient client;
WebSocketsClient webSocket;
void webSocketEvent(WStype_t type, uint8_t *payload, size_t length) {
switch (type) {
case WStype_DISCONNECTED:
Serial.println("Disconnected!");
break;
case WStype_CONNECTED:
Serial.println("Connected!");
webSocket.sendTXT("Connected");
break;
case WStype_TEXT:
Serial.print("get text:");
Serial.println((char *)payload);
break;
default:
Serial.print("Message type is ");
Serial.println(type);
break;
}
}
void setup() {
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!");
while (true);
}
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(WIFI_SSID);
status = WiFi.begin(WIFI_SSID, WIFI_PASS);
delay(10000);
}
Serial.println("Connected to WiFi");
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
webSocket.begin("//localhost8080", 8080);
webSocket.onEvent(webSocketEvent);
webSocket.setReconnectInterval(5000);
}
void loop() {
webSocket.loop();
webSocket.sendTXT("what will this be");
}
...
The NODE JS Websocket Server ---------------------------
...
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (message) => {
console.log(`Received message: ${message}`);
// Write message to a file
const fs = require('fs');
fs.appendFile('received_data.txt', `${message}\n`, (err) => {
if (err) throw err;
console.log('Message written to file');
});
// Send acknowledgment to client (optional)
ws.send(`Message received: ${message}`);
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
console.log('WebSocket server started on port 8080');
...
The test HTML page -------------------------------------------------------------------
...
<html>
<head>
</head>
<body>
<form id="input-form">
<label for="message">Enter Message:</label>
<input type="text" id="message" name="message"><br><br>
<input type="submit" value="Send">
</form>
<div id="messages"></div>
<script>
const webSocket = new WebSocket('ws://localhost:8080/');
webSocket.onmessage = (event) => {
console.log(event)
document.getElementById('messages').innerHTML +=
'Message from server: ' + event.data + "<br>";
};
webSocket.addEventListener("open", () => {
console.log("We are connected");
});
function sendMessage(event) {
var inputMessage = document.getElementById('message')
webSocket.send(inputMessage.value)
inputMessage.value = ""
event.preventDefault();
}
document.getElementById('input-form').addEventListener('submit', sendMessage);
</script>
</body>
</html>
...