我正在尝试将此简单的PHP脚本移植到node.js。
电视使用RS232,并且命令是PON开启; POF关闭。

此示例成功打开了电视:

<?php
$rs232_sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($rs232_sock, '10.0.1.155', '4999');
$rs232_in = pack("H*" ,'02'.bin2hex('PON').'03');
socket_write($rs232_sock, $rs232_in, strlen($rs232_in));
?>


我已经开始使用NodeJS:

var net = require('net');
var jspack = require('jspack/jspack.js').jspack;

client.connect('4999','10.0.1.155', function(){
    console.log('CONNECTED');
        // Send the RS232 command
        client.write(jspack.Pack("H",'02'+bin2hex(command)+'03'));
}).on('data', function(data) {
    // log the response
    console.log('DATA: ' + data);
    // Close the connection
    client.destroy();
});


这导致:

net.js:618
    throw new TypeError('invalid data');
    ^

TypeError: invalid data
    at Socket.write (net.js:618:11)
    at Socket.<anonymous> (/Users/paul/Sites/homebridge-globalcache-gc100/test.js:79:10)
    at Socket.g (events.js:261:16)
    at emitNone (events.js:73:20)
    at Socket.emit (events.js:167:7)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1051:10)

最佳答案

您不需要额外的库来发送二进制数据。像这样的东西就足够了:

var net = require('net');
var PON_MSG = new Buffer('\x02PON\x03', 'binary');
var POF_MSG = new Buffer('\x02POF\x03', 'binary');

client.connect('4999','10.0.1.155', function() {
  console.log('CONNECTED');
  // Replace `PON_MSG` with `POF_MSG` to do POF instead
  client.write(PON_MSG);
}).on('data', function(data) {
  console.log('DATA: %j', data);
});


另请注意,data事件可以触发多次,因此何时可以安全地终止连接(如果远程端没有自动终止连接)取决于协议(以确保已收到整个响应)。

08-18 14:00