MKR101 fails to connect to Websockets Server

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>
...

I remember some time ago having websocket problems. I don't know if this solves your case but I could not get websockets running with Javascript without implementing ws.onClose function. Here is a working HTML:

<html>
  <body>

    Example 10 - using WebSockets<br><br>

    <script type='text/javascript'>

      if ("WebSocket" in window) {
        var ws = new WebSocket ("ws://" + self.location.host + "/example10_WebSockets"); // open webSocket connection
				
        ws.onopen = function () {

          // ----- send text data -----

          ws.send ("Hello webSocket server, after this text I'm sending 32 16 bit binary integers."); 

          // ----- send binary data -----

          const fibonacciSequence = new Uint16Array (32);
          fibonacciSequence [0] = -21;
          fibonacciSequence [1] = 13;
          for (var i = 2; i < 32; i ++) fibonacciSequence [i] = fibonacciSequence [i - 1] + fibonacciSequence [i - 2]; 
          ws.send (fibonacciSequence);
        };

        ws.onmessage = function (evt) { 
          if (typeof(evt.data) === 'string' || evt.data instanceof String) { // UTF-8 formatted string data

            // ----- receive text data -----

            alert ("[example 10] got text from server over webSocket: " + evt.data);
	  }
          if (evt.data instanceof Blob) { // binary data

            // ----- receive binary data as blob and then convert it into array buffer -----

            var myFloat32Array = null;
            var myArrayBuffer = null;
            var myFileReader = new FileReader ();
            myFileReader.onload = function (event) {
              myArrayBuffer = event.target.result;
              myFloat32Array = new Float32Array (myArrayBuffer); // <= our data is now here, in the array of 32 bit floating point numbers

              var myMessage = "[example 10] got " + myArrayBuffer.byteLength + " bytes of binary data from server over webSocket\n[example 10]";
              for (var i = 0; i < myFloat32Array.length; i++) myMessage += " " + myFloat32Array [i];
                alert (myMessage);
                // note that we don't really know anything about format of binary data we have got, we'll just assume here it is array of 32 bit floating point numbers
                // (I know they are 32 bit floating point numbers because I have written server C++ example myself but this information can not be obtained from webSocket)

                alert ("[example 10] if the sequence is 1 0.5 0.25 0.125 0.0625 0.03125 0.015625 0.0078125\n" + 
                       "             it means that 32 bit floating point format is compatible with ESP32 C++ server.\n");

                ws.close (); // this is where webSocket connection ends - in our simple "protocol" browser closes the connection but it could be the server as well

            };
            myFileReader.readAsArrayBuffer (evt.data);

          }
        };
				
        ws.onclose = function () { 
          alert ("WebSocket connection is closed."); 
        };

      } else {
        alert ("WebSockets are not supported by your browser.");
      }

    </script>
  </body>
</html>

The working solution is available on GIthub in case you need it. Websockets are supposed to be easy to implement.

I have resolved this problem, well understand the causes. The sketch etc is valid and does work. The issues are with my MacBook(s). For some reason connections are 'refused'. Clearing cache and a reboot fixes the problem. So from an MKR1010 and web sockets there are no issues. What my Macbook issue are, that's another problem to solve.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.