2013-01-22 4 views
1

node.js.를 사용하여 응용 프로그램에 문제가 있습니다. 웹 페이지와 PLC 사이의 통신을 허용하는 작은 응용 프로그램을 작성했습니다. 웹 페이지와의 통신은 socket.io를 기반으로하며, PLC와의 통신은 net.createConnection을 기반으로합니다.Node.js : 동일한 메시지가 여러 번 복사 됨

내 응용 프로그램이 웹 페이지에서 명령을 받으면 표준 가져 오기/쓰기 프로토콜로 메시지를 만들어 해당 메시지를 PLC에 보냅니다. PLC 응답은 F/W 프로토콜을 기반으로합니다. 응용 프로그램에서 응답 메시지를 수신하면이를 해독하여 웹 페이지에 정보를 거의 보내지 않아야합니다.

모든 프로세스가 작동하지만 PLC에서 메시지를 다시 한 번 복제 할 때마다 모든 작업 (가져 오기 또는 쓰기가 중요하지 않은 경우) 후에 표시됩니다. 예를 들어 : 이것은 PLC의 문제가 있지만 메시지가 정확하고 하나의 경우 내가 확인 Wireshark를 사용했습니다

Fetch operation -> Response: Data 
Fetch operation -> Response: Data Data 
Fetch operation -> Response: Data Data Data 
... 

. node.js 버퍼에 문제가 있다고 생각합니다.

의견이 있으십니까?

여기에 코드입니다 :

/*** 
    Fetch-Write protocol in Node.js 
    Massimo Milluzzo - [email protected] 
***/ 


// Packages needed 
var httpd = require('http').createServer(handler); 
var io = require('socket.io').listen(httpd); 
var fs = require('fs'); 
var net = require('net'); 

// Connection variables 
var host = "192.168.0.220";  // Ip of PLC 
var port = 2002;    // Port for the comunication with PLC 
httpd.listen(4000);    // Listening the browser on port 4000 
var conn = null;    // Manage the connection 
var message = null;    // Message 

// Manage HTML request 
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); 
     } 
    ); 
} 

// When is created the connection of the socket 
io.sockets.on('connection', function (socket) { 
    console.log('connected'); 

    // Test function 
    socket.on('message', function(content) { 
     console.log(content); 
     socket.emit('serverMessage', 'I\'m here'); 
    }); 

    // Need to write -> set the message 
    socket.on('write', function(content){ 
     // See fetch-write protocol documentation 
     message = new Uint8Array([83,53,16,1,3,3,3,8,0x01,content[0],0,content[1],0,content[2],255,2,0,content[3]]); 
     connect(content); 
    }); 

    socket.on('fetch', function(content) { 
     // See fetch-write protocol documentation 
     message = new Uint8Array([83,53,16,1,3,5,3,8,0x01,content[0],0,content[1],0,content[2],255,2]); 
     connect(content); 
    }); 

    // Main function for the communication with PLC 
    function connect(content){ 
     // Console writing 
     console.log(content); 
     socket.emit('serverMessage', 'Message received...try to comunicate with PLC'); 

     // If there isn't a connection create one 
     if(conn == null) 
      conn = net.createConnection(port,host); 


     // If gets an error print it 
     conn.on('error', function(err) { 
      console.log('Error in connection:', err); 
      socket.emit('error',""+err); 
     }); 

     // On connection close write it 
     conn.on('close', function() { 
      console.log('connection got closed'); 
      socket.emit('serverMessage','connection got closed'); 
     }); 

     // When data is received decode the message 
     conn.on('data', function(data) { 
      console.log('some data has arrived:', ""+data); 

      // See fetch-write protocol documentation 
      if((data[0] == 0x53) && 
       (data[1] == 0x35) && 
       (data[2] == 0x10) && 
       (data[3] == 0x01) && 
       (data[4] == 0x03) && 
       ((data[5] == 0x06) || (data[5] == 0x04)) && // 06: fetch | 04: write 
       (data[6] == 0x0F) && 
       (data[7] == 0x03) && 
       ((data[8] == 0x00) || (data[8] == 0x02) || (data[8] == 0x03) || (data[8] == 0x06)) && // Error code, see fetch-write protocol documentation 
       (data[9] == 0xFF) && 
       (data[10] == 0x07)) 
      { 
       switch(data[8]){ 
        // No error 
        case 0x00: 
         // Fetch 
         if(data[5] == 0x06){ 
          // Get the response of PLC 
          var i; 
          var mex = ""; 
          for(i = 16; i<data.length; i=i+2){ 
           mex = mex + "[" + data[i].toString(16) + " " + data[i+1].toString(16) + "]"; 
          } 
          // Write it 
          socket.emit('serverMessage','Value read: ' + mex); 
          mex = ""; 
         } 
         // Write 
         else if(data[5] == 0x06){ 
          socket.emit('serverMessage','PLC updated'); 
         } 
        break; 
        // Error 02: Requested block does not exist 
        case 0x02: 
         socket.emit('error','Requested block does not exist'); 
        break; 
        // Error 03: Requested block is to small 
        case 0x03: 
         socket.emit('error','Requested block is to small'); 
        break; 
        // Error 06: No valid ORG ID 
        case 0x06: 
         socket.emit('error','No valid ORG ID'); 
        break; 
        // Any other code, warning because not exist in the protocol 
        default: 
         var temp = ""+data[8]; 
         socket.emit('error','Unknown error ID ['+temp+']'); 
        break; 
       } 
      } 
      // The message doesn't correspond to the Fetch/Write protocol 
      else{ 
       socket.emit('error','Error while talking with PLC'); 
      } 
      data = ""; 
     }); 

     // Write the client message on the socket 
     conn.write(new Buffer(message,'ascii'), function() { 
      console.log('data was written out'); 
      socket.emit('serverMessage','data was written out'); 
     }); 
    } 
}); 

! 업데이트 !!!

내가 다른 테스트를했습니다

, 결과는 메시지의 실제 대기열이되지 않는 것입니다, 시험의 결과는 다음과 같습니다

Data 
Data1 Data1 
Data  Data  Data 
Data2 Data2 Data2 Data2 
Data3 Data3 Data3 Data3 Data3 
Data1 Data1 Data1 Data1 Data1 Data1 

답변

0

마지막으로

를 해결, 나는 해결책을 발견하고는 매우 간단하다 : 문제가 새로운 "데이터"리스너의 추가 작업, 모든 시간이이었다이었다 .

conn.on('data', function(data) { 
    ... 
} 

에 :

conn.once('data', function(data) { 
    ... 
} 

이를 방지하기 위해, 나는의 코드를 변경했다

관련 문제