Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Socket.io 2.0 Compatibility #40

Open
diruuu opened this issue May 31, 2017 · 10 comments
Open

Socket.io 2.0 Compatibility #40

diruuu opened this issue May 31, 2017 · 10 comments

Comments

@diruuu
Copy link

diruuu commented May 31, 2017

Hi,
Silly question, but I wonder if this work with socket.io v2.0. Or should I use socket.io v.1 only on the server?

@washo4evr
Copy link
Owner

Hi,
for sure it has only been tested on 1.x
I would recommend staying with the older version

I may try when time permits to check v2.x

@HudsonProdigy
Copy link

No it does not. At least not as is. I spent half day trying to get it to work, with no success. As soon as i read this post and realized i was running 2.0.1 socket io, i downgraded to 1.4.5 and everything worked great.

@washo4evr
Copy link
Owner

I ordered an ESP32 and will be adding support for this new CPU + socket.io 2.x when I receive it.

Thanks for your patience

@washo4evr
Copy link
Owner

Hi,
ESP32 + socket.IO v2.0.3 are now supported

@florian-guillemard
Copy link

Hi,

I tried with socket.IO v2.2.0, and now on v2.0.3.. I can't make it work :(
My server is on a MacOSX 10.14.2, Node v10.13.0..

2 days I'm on this and I can't figure it out..
I made an app with the subscribing functionnality "room", it's working great with the Web page but no hope on ESP32S.. So I tried your example with no success!

Thanks for your help,

On ESP32S

#define ESP32
#include <SocketIOClient.h>

SocketIOClient client;
const char* ssid     = "Florian";
const char* password = "0601773693";

char host[] = "192.168.1.95";
int port = 2390;
extern String RID;
extern String Rname;
extern String Rcontent;

unsigned long previousMillis = 0;
long interval = 5000;
unsigned long lastreply = 0;
unsigned long lastsend = 0;

void setup() {
  Serial.begin(115200);
  delay(10);

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  if (!client.connect(host, port)) {
    Serial.println("connection failed");
    return;
  }
if (client.connected())
  {
    client.send("connection", "message", "Connected !!!!");
  }
}

void loop() {
unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > interval)
  {
    previousMillis = currentMillis;
    //client.heartbeat(0);
    Serial.print("**************************************  ");
    Serial.println(lastsend);
    client.send("atime", "message", "Time please?");
    lastsend = millis();
    Serial.print("**************************************  ");
    Serial.println(lastsend);
  }
  if (client.monitor())
  {
    lastreply = millis();
    Serial.println(RID);
    if (RID == "atime" && Rname == "time")
    {
      Serial.print("Il est ");
      Serial.println(Rcontent);
    }
  }
}

On Node :

var app = require('http').createServer(handler);
var io = require('socket.io')(app);

// io.configure('production', function(){
//   io.set('transports', ['xhr-polling']);
// });

var fs = require('fs');
app.listen(2390);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}
function ParseJson(jsondata) {
    try {
        return JSON.parse(jsondata);
    } catch (error) {
        return null;
    }
}
function sendTime() {
    io.sockets.emit('atime', { time: new Date().toJSON() });
}
io.on('connection', function (socket) {
	console.log("Connected");
  socket.emit('welcome', { message: 'Connected !!!!' });
  socket.on('connection', function (data) {
    console.log(data);   });
  socket.on('atime', function (data) {
	  sendTime();
    console.log(data);
    });
socket.on('JSON', function (data) {
//	console.log(data);
	var jsonStr = JSON.stringify(data);
	    var parsed = ParseJson(jsonStr);
console.log(parsed);
	console.log(parsed.sensor);
  });
    socket.on('arduino', function (data) {
	  io.sockets.emit('arduino', { message: 'R0' });
    console.log(data);
  });
});

In 'index.html' :

<!doctype html>
<html>
    <head>
        <script src='//code.jquery.com/jquery-1.7.2.min.js'></script>
        <script src='//192.168.1.95:2390/socket.io/socket.io.js'></script>
        <script>
            var socket = io.connect('//192.168.1.95:2390');
$(document).ready(function(){
                $("#button").click(function() {
                    socket.emit('arduino' ,"Hello World!");
                })
            })
            socket.on('welcome', function(data) {
                $('#messages').append('<li>' + data.message + '</li>');
                socket.emit('atime', {data: 'foo!'});
            });
            socket.on('atime', function(data) {
                console.log(data);
                $('#messages').append('<li>' + data.time + '</li>');
            });
            socket.on('arduino', function(data) {
                console.log(data);
                $('#messages').append('<li>' + data + '</li>');
            });
		
            socket.on('error', function() { console.error(arguments) });
            socket.on('message', function() { console.log(arguments) });
        </script>
    </head>
    <body>
        <button type="button" id='button'>Send Message to Arduino</button> 
<ul id='messages'></ul>

    </body>
</html>``` 

@HRahikainen
Copy link

With the default example, I was experiencing timeout after 20-30 seconds. Then in the JS side (own custom nodejs), I changed the configuration of the server "pingInterval" and "pingTimeout" to one minute and set a timer to trigger a client.heartbeat(1) every 55 seconds. Now it works.

@florian-guillemard
Copy link

Thanks, I will try ASAP your solution ;)

@florian-guillemard
Copy link

I changed the 'pingTimeout' and 'pingInterval' at 60 000 but with no effect!
What did I do wrong ?

Connecting to Florian
..
WiFi connected
IP address: 
192.168.1.76
1216 <= millis() before connect()
19474 <= millis() before print('failed')
connection failed
**************************************  0
**************************************  19475
var app = require('http').createServer(handler);
var io = require('socket.io')(app, {
  pingInterval: 60000,
  pingTimeout: 60000
});

@HRahikainen
Copy link

Snippet of my server code (v.2.2.0, nodejs v.10.4.0):

const express = require("express");
const app = express();
const http = require("http").Server(app);

const io = require("socket.io")(http, {
  pingInterval: 60000,
  pingTimeout: 5000
});

...

io.on("connection", function(socket) {
  console.log("Client connected");

  socket.on("disconnect", function(reason) {
    console.log("Client disconnected: " + reason);
  });

// other handlers

...
// finally
http.listen(PORT, () => console.log(`Listening on ${PORT}`));

and for the ESP32S side:

#define ESP32
#include <SocketIOClient.h>

SocketIOClient client;
const unsigned char LED_BUILTIN = 2;
const char *ssid = "";
const char *password = "";

char host[] = "your host";
int port = your port;
int i = 0;

hw_timer_t *timer = NULL;
volatile SemaphoreHandle_t timerSemaphore;
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;
volatile uint32_t isrCounter = 0;
volatile uint32_t lastIsrAt = 0;
uint32_t isrCount = 0, isrTime = 0;

void IRAM_ATTR onTimer()
{
  // Increment the counter and set the time of ISR
  portENTER_CRITICAL_ISR(&timerMux);
  isrCounter++;
  lastIsrAt = millis();
  portEXIT_CRITICAL_ISR(&timerMux);
  // Give a semaphore that we can check in the loop
  xSemaphoreGiveFromISR(timerSemaphore, NULL);
  // It is safe to use digitalRead/Write here if you want to toggle an output
}

extern String RID;
extern String Rname;
extern String Rcontent;

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  Serial.begin(9600);
  delay(10);

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  if (!client.connect(host, port))
  {
    Serial.println("Connection failed");
    return;
  }
  if (client.connected())
  {
    Serial.println("Connected");
    // Create semaphore to inform us when the timer has fired
    timerSemaphore = xSemaphoreCreateBinary();
    timer = timerBegin(0, 80, true);             // Timer0, 80 prescaler, count up
    timerAttachInterrupt(timer, &onTimer, true); // timer, callback, edge
    timerAlarmWrite(timer, 1000000, true);       // timer, count to interrupt at, reload
    timerAlarmEnable(timer);
  }
}

void loop()
{

  // If Timer has fired
  if (xSemaphoreTake(timerSemaphore, 0) == pdTRUE)
  {
    // Read the interrupt count and time
    portENTER_CRITICAL(&timerMux);
    isrCount = isrCounter;
    isrTime = lastIsrAt;
    portEXIT_CRITICAL(&timerMux);
    // Print it
    Serial.print("onTimer no. ");
    Serial.print(isrCount);
    Serial.print(" at ");
    Serial.print(isrTime);
    Serial.println(" ms");
    if (isrCount % 55 == 0)
    {
      client.heartbeat(1);  // Keep connection alive by sending heartbeat every 55 seconds.
    }
  }

  if (i < 1)
  {
    Serial.println("**************************************  ");
    client.send("message", "message", "Some message sent once!");
    Serial.println("**************************************  ");
    i++;
  }

  if (client.monitor())
  {
    Serial.println(RID);
    if (RID == "message" && Rname == "message")
    {
      Serial.print("Contents:");
      Serial.println(Rcontent);
    }
    else if (RID == "message" && Rname == "things")
    {
      Serial.print("Some amount of things ");
      Serial.print(Rcontent); // Value of things
      Serial.println(" unit of things.");
      client.send("message", "message", "Response to things");
    }
  }
}

Hope this helps you, I don't have time for much else right now.

@florian-guillemard
Copy link

Thanks for your response, but I did not work with Socket.IO v2.2.0 and Node v10.4.0 with my ESP32S :(

ets Jun  8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0018,len:4
load:0x3fff001c,len:1324
load:0x40078000,len:7788
ho 0 tail 12 room 4
load:0x40080400,len:6460
entry 0x400806e8


Connecting to Florian
..
WiFi connected
IP address: 
192.168.1.76
Connection failed
/Users/ficeto/Desktop/ESP32/ESP32/esp-idf-public/components/freertos/queue.c:1441 (xQueueGenericReceive)- assert failed!
abort() was called at PC 0x4008caad on core 1

Backtrace: 0x4008fe64:0x3ffb1ee0 0x40090039:0x3ffb1f00 0x4008caad:0x3ffb1f20 0x400d1956:0x3ffb1f60 0x401213aa:0x3ffb1fb0 0x4008bead:0x3ffb1fd0

Rebooting...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants