在 node-red 中创建二进制负载

create binary payload in node-red

node-red 和 javascript 的新手。我需要使用 TCP 输入连接到继电器控制器以获得状态。我正在使用功能节点生成一个两字节的请求,该请求将流向 TCP 输入节点和控制器,但不知道如何在 java 中对其进行格式化。我可以设置

msg.payload = "hello";

要发送一个字符串,但我需要发送2个字节:0xEF 0xAA。在 C# 中,我只创建字符串

msg.payload = "\xEF\xAA";

之类的。如何在 java/node-red 中执行此操作?

二进制有效负载是 NodeJS buffer 对象,因此可以这样创建:

msg.payload = new Buffer([0xEF,0xAA]);

截至今天(nodered 0.17.5),这可以通过以下方式实现,参见documentation

msg.payload = Buffer.from("\xEF\xAA")

msg.payload  = Buffer.from('hello world', 'ascii');

如您所见,您还可以指定一个encoding参数:

The character encodings currently supported by Node.js include:

'ascii' - for 7-bit ASCII data only. This encoding is fast and will strip the high bit if set.

'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.

'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported.

'ucs2' - Alias of 'utf16le'.

'base64' - Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC4648, Section 5.

'latin1' - A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC1345, page 63, to be the Latin-1 supplement block and C0/C1 control codes).

'binary' - Alias for 'latin1'.

'hex' - Encode each byte as two hexadecimal characters.