使用WiFly与ws websockets

时间:2014-07-27 18:17:48

标签: node.js websocket arduino

我一直试图想出一种方法来连接来自Arduino的WiFly,以便将一些加速度计数据发送到我的node.js服务器。目前,我的方法是拥有三台服务器:

  1. Http>>这是出于客户目的
  2. 网络服务器>>这基本上是针对TCP请求的,这就是我的服务器从3. WS websockets>>接收信息的方式。这将从Net服务器获取数据并将其流式传输到客户端。
  3. 以下是代码:

    var http = require('http');
    var fs = require('fs');
    var path = require('path');
    var url = require('url');
    var net = require('net');
    var sensorData;
    var message = {
      "data": ''
    }
    var newValue,
      oldValue,
      diff;
    //Settings
    var HTTP_PORT = 9000;
    var NET_PORT = 9001;
    var WS_PORT = 9002;
    //Server
    var mimeTypes = {
      "html": "text/html",
      "jpeg": "image/jpeg",
      "jpg": "image/jpeg",
      "png": "image/png",
      "js": "text/javascript",
      "css": "text/css"
    };
    http.createServer(function (req, res) {
      var fileToLoad;
      if (req.url == '/') {
        fileToLoad = 'index.html';
      } else {
        fileToLoad = url.parse(req.url).pathname.substr(1);
      }
    
      console.log('[HTTP] :: Loading :: ' + 'frontend/' + fileToLoad);
      var fileBytes;
      var httpStatusCode = 200;
      fs.exists('frontend/' + fileToLoad, function (doesItExist) {
        if (!doesItExist) {
          console.log('[HTTP] :: Error loading :: ' + 'frontend/' + fileToLoad);
          httpStatusCode = 404;
        }
        var fileBytes = fs.readFileSync('frontend/' + fileToLoad);
        var mimeType = mimeTypes[path.extname(fileToLoad).split('.')[1]];
        res.writeHead(httpStatusCode, {
          'Content-type': mimeType
        });
        res.end(fileBytes);
      });
      // console.log("[INIT] Server running on HTTP Port");
    }).listen(HTTP_PORT);
    
    proxy.on("close", function(){
      console.log("Connection has closed");
    });
    
    proxy.on("end", function(){
      console.log("Connection has ended");
     });
    var socket;
    var clients = [];
    var socketObject;
    var server = net.createServer(function (socket) {
      socketObject = socket;
      socket.name = socket.remoteAddress + ":" + socket.remotePort;
      clients.push(socket);
      console.log(socket);
      socket.write("HTTP/1.1 101", function () {
        console.log('[CONN] New connection: ' + socket.name + ', total clients: ' + clients.length);
      });
      socket.setEncoding('utf8');
      socket.on('error', function (data) {
        console.log(data);
      });
      socket.on('end', function () {
        console.log('[END] Disconnection: ' + socket.name + ', total clients: ' + clients.length);
      });
      socket.on('data', function (data) {
        console.log('[RECV from ' + socket.remoteAddress + "] " + data);
        oldValue = newValue;
        newValue = data;
        diff = Math.abs(newValue) - Math.abs(oldValue);
        console.log(Math.abs(newValue) + '-' + Math.abs(oldValue));
        message.data = Math.abs(diff);
        console.log('[SAVED] ' + message.data);
      });
    });
    server.listen(NET_PORT, function () {
      console.log("[INIT] Server running on NET server port", NET_PORT);
    });
    var WebSocketServer = require('ws').Server,
      wss = new WebSocketServer({
        port: WS_PORT
      });
    wss.on('connection', function (ws) {
      // ws.send(JSON.stringify(message));
      setInterval(function () {
        updateXData(ws)
      }, 500);
    });
    
    
    function updateXData(ws) {
      var newMessage = {
        "data": ""
      }
      newMessage.data = message.data
      ws.send(JSON.stringify(newMessage));
    }
    

    所以问题是:是否有一种更简洁的方法,只需使用ws处理来自WiFly的数据,然后将其发送到客户端?

    提前致谢!

1 个答案:

答案 0 :(得分:0)

不确定这是否适合您,可能对您不熟悉,但您可以使用MQTT,有免费的经纪人非常好,并且使用配备WiFly Shield的Arduino相对容易设置和实施。< / p>

http://mqtt.org/

希望这有点帮助!