1

我正在使用 QtSerialPort 通过 COM 端口将串行消息发送到 INSTEON PowerLinc 2413U 调制解调器。我可以很好地硬编码和发送消息,但是我需要使用可变设备 ID 发送相同的消息。以下是我用来发送静态消息的结构:

QByteArray msg;
bool msgStatus;   

msg.resize(8);
msg[0] = 0x02;
msg[1] = 0x62;
msg[2] = 0x1B;
msg[3] = 0xE9;
msg[4] = 0x4B;
msg[5] = 0x11;
msg[6] = 0x05;
msg[7] = 0x00;
send(msg,&msgStatus);

索引位置 2、3 和 4 表示设备 ID。在这种情况下为“1BE94B”。我的函数接受应该通过 QString 执行操作的设备 ID。

如何转换 QString 以适应 3 个索引的所需结构。我使用以下方法成功获取了 3 字节地址的每个字节:

devID.mid(0,2)
devID.mid(2,2)
devID.mid(4,2)

我的目标实现是让 QByteArray 看起来像这样:

QByteArray msg;
bool msgStatus;   

msg.resize(8);
msg[0] = 0x02;
msg[1] = 0x62;
msg[2] = devID.mid(0,2)
msg[3] = devID.mid(2,2)
msg[4] = devID.mid(4,2)
msg[5] = 0x11;
msg[6] = 0x05;
msg[7] = 0x00;
send(msg,&msgStatus);

I have tried many different conversions schemes, but have been unable to resolve what I need. Ultimately my msg should be structured as:

    02621DE94B151300

The only way I have successfully seen the intended device action is by individually assigning each byte in the QByteArray, using msg.append() does not seem to work.

Thank you for your suggestions!

4

1 回答 1

1

Part of the problem here is that QString is unicode/short based and not char based. For me it works when I use toLocal8Bit

QByteArray id;
idd.resize(3);
id[0] = 0x1B;
id[1] = 0xE9;
id[2] = 0x4B;

QString devId( bytes );

QByteArray msg;
msg.resize(8);
msg[0] = 0x02;
msg[1] = 0x62;
msg.replace( 2, 3, devId.toLocal8Bit() );
msg[5] = 0x11;
msg[6] = 0x05;
msg[7] = 0x00;

If your id is text, and not bytes, then the fromHex must be added:

QString devId( "1BE94B" );
msg.replace( 2, 3, QByteArray::fromHex( devId.toLocal8Bit() ) );
于 2013-02-18T13:17:06.887 回答