0

I have an embedded device that I am trying to communicate with via TCP over a wireless connection. Below is the structure of the data that the device is expecting:

char[] = { 0x55, 0x55, 0x55, 0x55 //header block
    //start data here
    0x01, 0x00, 0x00, 0x00 //example data
    //end data block
    0xAA, 0xAA, 0xAA, 0xAA //footer
    };

I am trying to use QTcpSocket to write this data. QTcpSocket will allow me to write char data, or QByteArray, but when I attempt to save this data in either of these formats, it fails. The only way I am successfully able to save the data is in an unsigned char array.

Example of what I mean:

char message[12] = {
    0x55, 0x55, 0x55, 0x55,
    0x01, 0x00, 0x00, 0x00,
    0xAA, 0xAA, 0xAA, 0xAA};

However, this message block gives me an error

C4309: 'initializing' : truncation of constant value.

And when printing this data, it comes out as:

U U U U
r

with the r being more like the edge of a square than the actual letter

This particular issue is fixed by changing the array from char to unsigned char

unsigned char message[12] = {
    0x55, 0x55, 0x55, 0x55,
    0x01, 0x00, 0x00, 0x00,
    0xAA, 0xAA, 0xAA, 0xAA};

which when printed then comes out with the data:

85 85 85 85
1 0 0 0
170 170 170 170

This matches the format that the device I am talking to is expecting. However, if I put the data in this format, QTcpSocket doesn't like that, and responds back with:

C2664: 'qint64 QIODevice::write(const QByteArray &)': cannot convert argument 1
from 'unsigned char[20]' to 'const char *'

Is there a way to send the data that I am wanting to with QTcpSocket, or do I need to figure out how to write this message using windows sockets?

Nejat
  • 31,784
  • 12
  • 106
  • 138
user3830784
  • 355
  • 3
  • 17

1 Answers1

1

You can simply cast to char * :

qint64 ret = socket.write((char *)message, 12);
Nejat
  • 31,784
  • 12
  • 106
  • 138
  • Is there a similar easy conversion for then reading the data in the same format from QTcpSocket? (example, I sent the message in the example, the device sends it back to "verify" that it recieved it correctly, how do I read it out to know that it is the same thing that I sent?) – user3830784 Jan 15 '15 at 20:07
  • 1
    In a similar way you can use `socket.read((char *)message, 12);` which could be done in a slot connected to the `readyRead` signal of `QTcpSocket`. See this for an example of using `QTcpSocket` asynchronously : http://stackoverflow.com/questions/27787130/qt-even-processing-while-waitforconnected-is-running/27793246#27793246 – Nejat Jan 15 '15 at 20:28