SocketIO server not sending data to Arduino

2019-09-07 17:06发布

问题:

I have an Arduino TCP connection that sends data to my server using socketIO. Everything works great. I'm trying to send data to tigger some events. I got char c = client.read() function on my Arduino sketch to listen for incoming data but unfortunately I don't receive anything.

I'm running all my connections on one port. HTTP/TCP i.e my Arduino forwards data on port 3000 and my webpage also uses this port. Could this be a problem?

server.js

var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(3000);

io.sockets.on('connection', function(socket){

socket.on('ON', function (data) {
    _.each(clients, function(client) {
        client.emit('ON', data);
        console.log(data + "  ON");
    });


});
socket.on('OFF', function (data) {
    console.log(data);
    _.each(clients, function(client) {
        client.emit('OFF', data);
        console.log(data + "  OFF")
    });

   });
});

Arduino.ino

#include <dht.h>
#include <SPI.h>
#include <Ethernet.h>

dht DHT;
#define DHT11_PIN A5


void sendData(int temperature, int humidity) ;
// Ethernet related
EthernetClient client;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(192,168,0,11);
IPAddress server(192,168,0,10);


void setup(){
  Serial.begin(9600);
    Ethernet.begin(mac, ip);
    delay(3000);

  }

void loop()
{ 
  int chk = DHT.read11(DHT11_PIN);
  int t = DHT.temperature;
  int h = DHT.humidity;

          // send data to the server
        sendData(t, h); 

  Serial.print("Temperature = ");
  Serial.print(t);
  Serial.print( "," );
  Serial.print("Humidity = ");
  Serial.print(h);
  Serial.print("\n");
   delay(6000);

}



void sendData(int temperature, int humidity) 
{
  if(!client.connected())
  {
    if (client.connect(server, 3000)) {
      char c = client.read();
   Serial.print(c);      

Serial.println("Sending data...");
      // send the HTTP PUT request:
      client.print("GET /weatherserver/");
      client.print(temperature);
      client.print("/");      
      client.print(humidity); 
      client.println(" HTTP/1.1");
      client.println("Host: localhost");
      client.println("User-Agent: arduino-barom");
      client.println("Connection: close");
      client.println();
      client.stop();
    } else {
       Serial.println("Could not connect.");
       client.stop();
    }
  }
  delay(6000);
}