Domanda

I am using QtSerialPort to send serial messages across a COM port to an INSTEON PowerLinc 2413U Modem. I can hardcode and send messages just fine, however I need to send the same message using variable device IDs. The following is the structure I used to send static messages:

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);

Index positions 2,3,and 4 represent the device ID. "1BE94B" in this instance. My function accepts the device ID that the action should be executed for via QString.

How can I convert the QString to fit the needed structure of 3 indices. I successfully get each byte of the 3 byte address using the following:

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

My Target implementation is for the QByteArray to look like this:

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!

È stato utile?

Soluzione

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() ) );
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top