-1

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

  • 1
    You're first copying `append` into `combind` and then overwritting it with `sCmd`. I'm not sure if that's what you wanna do. – Paweł Stawarz Mar 07 '14 at 00:23
  • That would make sense, I thought it was concatenating the contents. Ideally I would like the results of combind to be a concatenation of append + and sCmd. Also append should be a 4 byte 32-bit big-Endian number. Similar to this [size][size][size][size][string CMD (size bytes long)] – user3390444 Mar 07 '14 at 09:07
  • If I were you, I would use a `std::string`. Then you could simply use `combind=append+sCmd`. But since you're using char arrays, then you have to use strcat (http://www.cplusplus.com/reference/cstring/strcat/) – Paweł Stawarz Mar 07 '14 at 15:52

1 Answers1

0

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
}