0

I am trying to build a system to send sensor data from esp32 to a node.js based application with Websocket, hosted on Glitch server.

When locally hosted (under the same router), esp32 can send data to the back-end, and the front-end also works with the IP address acquired from the router. But, when hosted on a live server(Glitch), esp32 can connect to the back-end with an IP address, but the front-end requires a secure connection and thus does not show real-time data.Thus does not connect to web socket server. Shows an error saying "wss protocol is needed to connect from https protocol"

My web socket server has been perfectly deployed in Glitch.com. I can connect my front-end (React.js app) hosted in firebase to my WebSocket server.

How do I solve this problem and send data to the live server?

ESP32 code

#include <ArduinoWebsockets.h>
#include <ArduinoJson.h>
#include <WiFi.h>

const char* ssid = "TP-Link_7EEF"; //Enter SSID
const char* password = "__________"; //Enter Password

const char* websockets_connection_string = "wss://sugar-fabulous-coat.glitch.me/"; //Enter server adress

const char echo_org_ssl_ca_cert[] PROGMEM = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIDhTCCAm0CFA+uuIM2KjxS8GAsr6QZaqHv1BYWMA0GCSqGSIb3DQEBCwUAMH8x\n" \
"CzAJBgNVBAYTAkJEMRMwEQYDVQQIDApTb21lLVN0YXRlMSIwIAYDVQQKDBlFeGNl\n" \
"bGxlbnQgVGVjaG5vbG9naWVzIEJEMTcwNQYJKoZIhvcNAQkBFihleGNlbGxlbnQu\n" \
"dGVjaG5vbG9naWVzLmxpbWl0ZWRAZ21haWwuY29tMB4XDTIyMTIwMzEwMjQ1NFoX\n" \
"DTIzMTIwMzEwMjQ1NFowfzELMAkGA1UEBhMCQkQxEzARBgNVBAgMClNvbWUtU3Rh\n" \
"dGUxIjAgBgNVBAoMGUV4Y2VsbGVudCBUZWNobm9sb2dpZXMgQkQxNzA1BgkqhkiG\n" \
"9w0BCQEWKGV4Y2VsbGVudC50ZWNobm9sb2dpZXMubGltaXRlZEBnbWFpbC5jb20w\n" \
"ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDTt943oNt1+++837JO621n\n" \
"SiMaRzrMt6SKjZNNLJKurdlsPkcibMoLoE7A3VfmYh/1dM9kWS2ANYxXMP8QBsD8\n" \
"I8m3i6pFFZVORX14iPNvpxkgzGoZkXsD0CYRC8pErv5O3GSgXfHjunvaqxrtCGsQ\n" \
"x/x/tqErp9Hn9cnWV0XiIZhkl2qI6O7f84tyYVc7rK3BII6AVLwp0KXjGk3SxE0+\n" \
"P37UPSfy4kgY2JJBJmdz+AJ79AgGpuSW3nQPjzG0ULjWCCAwwPVbeagilqqrsBhk\n" \
"fI+TVb6wN8qXnuHSdKHjpgFbpM0VrvtLcZXNW0HgTqqVQnM0ZlRWA6qH8bp3IxRx\n" \
"AgMBAAEwDQYJKoZIhvcNAQELBQADggEBAKJEQhswcQBE5zqavvcaEuUd3x6NeO75\n" \
"5xR5PplJm0IB7FC2S8LPEZQuM22qTdvrO6sp1Hl9ddGCPhdBJjRVRZxUz9mVbpZH\n" \
"hO0C26nfxwhSMP4XoJvVP0yBMRpulBC3YpOC6IDRjxlj3+dCHS42EJpeyVLChZA/\n" \
"URiwwAcS1myS3dR7Gnj/6hKRu654qS3UI9cFayxbaF2IBi7xk3qXhkvsJ/Z2TJ9i\n" \
"SxMrgEzrUVbTVt11bS7MvrOhwCFQBH97+0JrON3csRf4ZEGBSH3jSLVTCFGTi/wQ\n" \
"oMBYySQqFSrTd5zvxyklqHjAjlq815kYSXMAEmhL8T/7IVFAj/lUW2Q=\n" \
"-----END CERTIFICATE-----\n";

int value1=0;
int value2=0;
StaticJsonDocument<100> doc;

using namespace websockets;

void onMessageCallback(WebsocketsMessage message) {
    Serial.print("Got Message: ");
    Serial.println(message.data());
}

void onEventsCallback(WebsocketsEvent event, String data) {
    if(event == WebsocketsEvent::ConnectionOpened) {
        Serial.println("Connnection Opened");
    } else if(event == WebsocketsEvent::ConnectionClosed) {
        Serial.println("Connnection Closed");
    } else if(event == WebsocketsEvent::GotPing) {
        Serial.println("Got a Ping!");
    } else if(event == WebsocketsEvent::GotPong) {
        Serial.println("Got a Pong!");
    }
}

WebsocketsClient client;
void setup() {
    Serial.begin(115200);
    // Connect to wifi
    WiFi.begin(ssid, password);

    // Wait some time to connect to wifi
    for(int i = 0; i < 10 && WiFi.status() != WL_CONNECTED; i++) {
        Serial.print("wifi connecting....");
        delay(1000);
    }
    Serial.print("");
    Serial.print("wifi connected.");

  // Before connecting, set the ssl fingerprint of the server
    client.setCACert(echo_org_ssl_ca_cert);

    // Connect to server
    client.connect(websockets_connection_string);
    
    // run callback when messages are received
    client.onMessage(onMessageCallback);
    
    // run callback when events are occuring
    client.onEvent(onEventsCallback);

    // Send a message
    serializeJson(doc,Serial);
    // Send a mess 

Server code

var bodyParser = require("body-parser");
const express = require("express"); //express framework to have a higher level of methods
const app = express(); //assign app variable the express class/method
var http = require("http");
var path = require("path");
const port = process.env.PORT || 5000;
const fs = require("fs");

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const server = http.createServer({
        ssl: true,
        port: 3000,
        ssl_key: fs.readFileSync(path.join(__dirname, "cert", "key.pem")),
        ssl_cert: fs.readFileSync(path.join(__dirname, "cert", "cert.pem")),
    },app); //create a server
//******this snippet gets the local ip of the node.js server. copy this ip to the client side code and add ':3000' **
//*****exmpl. 192.168.56.1---> var sock =new WebSocket("ws://192.168.56.1:3000");************
// require("dns").lookup(require("os").hostname(), function(err, add, fam) {
//     console.log("addr: " + add);
// });
/*******websocket setup*****************************/
//var expressWs = require('express-ws')(app,server);
const WebSocket = require("ws");
const s = new WebSocket.Server({ server });
//when browser sends get request, send html file to browser
// viewed at http://localhost:30000

// app.get("/", function(req, res) {
//     res.sendFile(path.join(__dirname + "/index.html"));
// });

app.get("/", (req, res) => {
    // res.send("Websocket is online. on ");
    res.send({ response: `Server is up and running. PORT: ${port} ` });
});

//*****************************************
//**********ws chat server***************************
//app.ws('/echo', function(ws, req) {
s.on("connection", function(ws, req) {
    // console.log("clients: ", s.clients);
    /*** when server receives messsage from client trigger function with argument message ***/
    ws.on("message", function(message) {
        console.log("Receivedd: ", message.toString(), " Port: ", port);
        s.clients.forEach(function(client) {
            //broadcast incoming message to all clients (s.clients)
            if (client != ws && client.readyState) {
                //except to the same client (ws) that sent this message
                // console.log("message: ", message.toString());
                let xx = message.toString();
                client.send(xx);
            }
        });
        // ws.send("From Server only to sender: "+ message); //send to client where message is from
    });
    ws.on("close", function() {
        console.log("lost one client");
    });
    //ws.send("new client connected");
    console.log("new client connected. Total Clients: >> ", s.clients.size);
});
server.listen(port, () => {
    console.log("Web socket server is running on port: ", port);
});

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.