Colin Stearns / Mbed 2 deprecated qcControl

Dependencies:   mbed

Fork of dgps by Colin Stearns

packet.h

Committer:
dylanembed123
Date:
2014-04-07
Revision:
13:a6d3cf2b018e
Parent:
12:e42985e3ea64
Child:
14:6be57da62283

File content as of revision 13:a6d3cf2b018e:

#define PACKETSIZE 256

// Example
// Packet 1. (SuperPackid=5,type=PT_IMAGE,size=0)
// Packet 2. (SuperPackid=5,type=PT_DEFAULT,size=1024)
// Packet 3. (SuperPackid=5,type=PT_DEFAULT,size=1000)
// Packet 4. (SuperPackid=5,type=PT_END,size=0)
#define XBEEON
enum PACKET_TYPE{
    PT_DEFAULT=0,
    PT_END,
    PT_IMAGE,
    PT_SIZE
};
typedef struct PacketStruct{
    unsigned int type;
    unsigned int size;// Number of valid bits
    char data[PACKETSIZE];
    unsigned int superPackID;// 
}PacketStruct;

class PacketSender{
    private:
    unsigned int superID;
    public:
    unsigned int getSuperID(){return superID++;}
    PacketSender():superID(0),outputDevice(
        #ifdef XBEEON
        XBEE::getSerial()
        #else
        USB::getSerial()
        #endif
    ){}
    Serial& outputDevice;
    void sendPacket(PacketStruct& output){
        for(int a=0;a<sizeof(PacketStruct);a++){
            outputDevice.putc(((char*)(&output))[a]);
            //USB::getSerial().putc(((char*)(&output))[a]);
        }
    }
    unsigned int min(unsigned int a,unsigned int b){
        return a<b ? a : b;
    }
    void sendPacket(unsigned int superPackID,char* data,unsigned int size,PACKET_TYPE type = PT_END){
        if(data!=NULL && size>0){
            for(int i=0;i<=(size-1)/PACKETSIZE;i++){
                PacketStruct output;
                output.type=PT_DEFAULT;
                output.superPackID=superPackID;
                output.size=min(PACKETSIZE,size-i*PACKETSIZE);
                for(int a=0;a<output.size;a++){
                    //USB::getSerial().printf(">>%d/%d - %d\n",a,size,output.size);
                    output.data[a]=data[a-i*PACKETSIZE];
                }
                for(int a=output.size;a<PACKETSIZE;a++){output.data[a]='\0';}
                //memcpy(output.data,&(data[i*PACKETSIZE]),min(PACKETSIZE,size-i*PACKETSIZE));
                sendPacket(output);
            }
            
        }else{
            PacketStruct output;
            output.type=type;
            output.size=0;
            output.superPackID=superPackID;
            for(int a=0;a<PACKETSIZE;a++){output.data[a]=a;}
            sendPacket(output);
        }
    }
    PacketStruct* getNextPacket(){
        int avail = outputDevice.readable();
        if(avail <= 0)return NULL;
        PacketStruct* output=new PacketStruct();
        for(int i=0;i<sizeof(PacketStruct);i++){
            // Wait for byte
            while(outputDevice.readable()<=0){}
            ((char*)output)[i] = outputDevice.getc();
        }
        return output;
    }
    
};
static PacketSender* ps=NULL;
static PacketSender& getPS(){
    if(ps==NULL)ps=new PacketSender();
    return *ps;
}