Remote Sensors Protocol with C++
Question: I am working on a project with the raspberry Pi and Scratch. I need to use the
Remote Sensors Protocol with C++. I have tried porting the Python code across
but i cannot get C++ to return the null values.

The original Python code looks like this:

    
    
    import socket
    from array import array
    
    HOST = '192.168.1.101'
    PORT = 42001
    
    scratchSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    scratchSock.connect((HOST, PORT))
    
    def sendCMD(cmd):
        n = len(cmd)
        a = array('c')
        a.append(chr((n >> 24) & 0xFF))
        a.append(chr((n >> 16) & 0xFF))
        a.append(chr((n >>  8) & 0xFF))
        a.append(chr(n & 0xFF))
        scratchSock.send(a.tostring() + cmd)
    
    sendCMD('sensor-update "dave" 201')
    

My Attempt in C++ looks like this:

    
    
    char* scratchencode(string cmd)
    {
        int cmdlength;
    
        cmdlength = cmd.length();
        char* combind = new char[20];
        const char * sCmd = cmd.c_str();
        char append[]={(cmdlength >> 24) & 0xFF, (cmdlength >> 16) & 0xFF, (cmdlength >> 8) & 0xFF, (cmdlength & 0xFF)};
        strcpy(combind,append);
        strcpy(combind,sCmd);
        return combind;
    }
    

Needles to say it doesn't work, Can anyone help with the porting the code, i
have tried to miminc the python code and the orgial doument at
<http://wiki.scratch.mit.edu/wiki/Remote_Sensors_Protocol> but have had no
success.

Chris


Answer: I have solved the problem, Thank you Paweł Stawarz. Your advice was just what
i needed, i converted the entire function to work with strings and it worked
first time.

The code is as follows:

    
    
    string scratchencode(string cmd)
    {
        int cmdlength; // holds the length of cmd
        string combind; // used to store the concatenated Packet
        string mgsSize; // used to store Message size
    
        cmdlength = cmd.length(); // length of CMD
    
        //convert intiger to a  4 byte 32-bit big-Endian number, using bit shifting.
        mgsSize = (cmdlength >> 24);
        mgsSize += (cmdlength >> 16);
        mgsSize += (cmdlength >> 8);
        mgsSize += cmdlength;
    
        combind = mgsSize + cmd; // concatenate mgsSize and cmd producing a structure of  [size][size][size][size][string CMD (size bytes long)]
        return combind; // return the string
    }
    

