void PackageFile::ReadPackage()
{
    std::fstream packageStream = std::fstream(TargetPackage, std::ios::in | std::ios::binary);

    char buf[512];
    char* fileContents = NULL;

    ReadBytes(buf, PACK_FILE_SIG_LENGTH, &packageStream);

    if (strncmp(buf, "PACK", PACK_FILE_SIG_LENGTH) != 0)
        return;

    ReadBytes(buf, sizeof(int), &packageStream);
    int dirOffset = BytesToInt(buf);

    ReadBytes(buf, sizeof(int), &packageStream);
    int directorySize = BytesToInt(buf);

    Header *packHeader = new Header();
    strncpy(packHeader->sig, "PACK", 4);
    packHeader->dirOffset = dirOffset;
    packHeader->dirLength = directorySize;

    if (packageHeader)
        delete(packageHeader);

    packageHeader = packHeader;

    bool hasNextFile = true;
    packageStream.seekg(dirOffset);

    entries->Release();

    int bytesRead = 0;
    while (hasNextFile)
    {
        ReadBytes(buf, DIRECTORY_ENTRY_SIZE, &packageStream);
        bytesRead += DIRECTORY_ENTRY_SIZE;

        if (bytesRead > directorySize)
        {
            hasNextFile = false;
            break;
        }

        DirectoryEntry* newEntry = new DirectoryEntry();

        strncpy(newEntry->fileName, buf, strlen(buf));

        int targetFilePos = BytesToInt(&buf[FILENAME_MAX_LENGTH]);
        int targetFileLength = BytesToInt(&buf[FILENAME_MAX_LENGTH + sizeof(int)]);

        newEntry->filePosition = targetFilePos;
        newEntry->fileLength = targetFileLength;

        entries->Add(newEntry);
    }

    packageRead = true;
}
const char* PackageFile::GetFile(std::string filename, int& fileSize)
{
    std::fstream packageStream = std::fstream(TargetPackage, std::ios::in | std::ios::binary);

    char buf[512];
    char* fileContents = NULL;

    ReadBytes(buf, PACK_FILE_SIG_LENGTH, &packageStream);

    // Step 1. Check it the file is the correct format
    if (strncmp(buf, "PACK", PACK_FILE_SIG_LENGTH) != 0)
        return NULL;

    ReadBytes(buf, sizeof(int), &packageStream);

    int dirOffset = BytesToInt(buf);

    bool hasNextFile = true;
    bool fileFound = false;
    packageStream.seekg(dirOffset);

    int filesIndex = 0;
    while (hasNextFile && !fileFound)
    {
        ReadBytes(buf, DIRECTORY_ENTRY_SIZE, &packageStream);
        if (strncmp(filename.c_str(), buf, FILENAME_MAX_LENGTH) == 0)
        {
            int targetFilePos = BytesToInt(&buf[FILENAME_MAX_LENGTH]);
            int targetFileLength = BytesToInt(&buf[FILENAME_MAX_LENGTH + sizeof(int)]);

            int absoluteFileOffset = dirOffset + (DIRECTORY_ENTRY_SIZE * this->entries->Count());
            packageStream.seekg(targetFilePos + absoluteFileOffset); // Offset the file pos by the directory offset and the entry offset
            
            fileContents = new char[targetFileLength];
            ReadBytes(fileContents, targetFileLength, &packageStream);

            fileSize = targetFileLength;
            fileFound = true;
        }

        if (strcmp(buf, "") == 0)
        {
            hasNextFile = false;
        }

        filesIndex++;
    }

    return fileContents;
}
Example #3
0
/*
==================
Channel::OnWindowAdjust
==================
*/
void Channel::OnWindowAdjust(const ubyte *data, uint32 len) {
	uint32 increment;
	BytesToInt(increment, data+10);

	winSizeOut += increment;
	printf("Window adjust recvd: %i\n", increment);
}
Example #4
0
/*
==================
Channel::IsPacketForMe
==================
*/
bool Channel::IsPacketForMe(const ubyte *data, uint32 len) {
	if (len > 10) {
		uint32 recp;
		BytesToInt(recp, data+6);

		return (recp == senChan);
	} 

	return false;
}
Example #5
0
//-------------------------------------------------------------------------
// Returns the user's current balance as an int
//
// 'user'      - Structure for holding user token information.
//
// Return: Current value of the user's balance.
//
int GetBalance(SHAUser* user)
{
   int balance = -1;

   if(user->devAN[0]==0x18)
      balance = BytesToInt(((DebitFile*)user->accountFile)->balanceBytes, 3);
   else if((user->devAN[0]&0x7F)==0x33)
   {
      DebitFile33* acctFile = (DebitFile33*)user->accountFile;
      if(acctFile->fileLength==RECORD_A_LENGTH)
         balance = BytesToInt(acctFile->balanceBytes_A, 3);
      else if(acctFile->fileLength==RECORD_B_LENGTH)
         balance = BytesToInt(acctFile->balanceBytes_B, 3);
      else
         OWERROR(OWERROR_BAD_SERVICE_DATA);
   }
   else
      OWERROR(OWERROR_BAD_SERVICE_DATA);

   return balance;
}
Example #6
0
/*
==================
Channel::OnChanOpenConfirmation
==================
*/
void Channel::OnChanOpenConfirmation(const ubyte *data, uint32 len) {
	status = ST_CHAN_OPEN;
	printf("Channel openend\n");

	uint32 b = 6;

	BytesToInt(recChan, data+b);
	b += 4;

	BytesToInt(senChan, data+b);
	b += 4;

	BytesToInt(winSizeOut, data+b);
	b += 4;

	BytesToInt(maxSize, data+b);
	b += 4;

	printf("Rec chan: %i\nSen chan: %i\n", recChan, senChan);
	printf("Cur wind: %i\nMax pack: %i\n", winSizeOut, maxSize);

	SendTTYRequest();
}
Example #7
0
/*
==================
Channel::OnChanData
==================
*/
void Channel::OnChanData(const ubyte *data, uint32 len) {
	uint32 plen, dlen;
	ubyte ub;
	Packet p(data, len);

	/* Raw payload length */
	plen = p.packetLength - p.paddingLength - 1;

	/* Actual data length */
	BytesToInt(dlen, data+10);
	//HexDump(data+14, dlen, "ascii");

	for (int i=0; i<dlen; i++) {
		ub = data[14+i];
		if (IsUbytePrintable(ub)) {
			printf("%c", ub);
		} else {
			HandleUnprintable(ub);
		}
	}
}
Example #8
0
//----------------------------------------------------------------------
// Read Authenticated Page for DS1963S.
//
// 'portnum'     - number 0 to MAX_PORTNUM-1.  This number is provided to
//                 indicate the symbolic port number.
// 'pagenum'     - page number to do a read authenticate
// 'data'        - buffer to read into from page
// 'sign'        - buffer for storing sha computation
// 'resume'      - if true, device access is resumed using the RESUME
//                 ROM command (0xA5).  Otherwise, a a MATCH ROM is
//                 used along with the device's entire address number.
//
// Return: Value of write cycle counter for the page
//         -1 for error
//
int ReadAuthPageSHA18(int portnum, SMALLINT pagenum, uchar* data,
                    uchar* sign, SMALLINT resume)
{
   short send_cnt=0;
   uchar send_block[56];
   short num_verf;
   SMALLINT i;
   ushort lastcrc16;
   int address = pagenum*32, wcc = -1;

   if(!resume)
   {
      // access the device
      OWASSERT( SelectSHA(portnum), OWERROR_ACCESS_FAILED, -1 );
   }
   else
   {
      // transmit RESUME command
      send_block[send_cnt++] = ROM_CMD_RESUME;
   }

   //seed the crc
   setcrc16(portnum,0);

   // change number of verification bytes if in overdrive
   num_verf = (in_overdrive[portnum&0x0FF]) ? 10 : 2;

   // create the send block
   // Read Authenticated Page command
   send_block[send_cnt] = CMD_READ_AUTH_PAGE;
   lastcrc16 = docrc16(portnum, send_block[send_cnt++]);

   // TA1
   send_block[send_cnt] = (uchar)(address & 0xFF);
   lastcrc16 = docrc16(portnum,send_block[send_cnt++]);

   // TA2
   send_block[send_cnt] = (uchar)((address >> 8) & 0xFF);
   lastcrc16 = docrc16(portnum,send_block[send_cnt++]);

   // now add the read bytes for data bytes, counter, and crc16, verification
   //for (i = 0; i < (42 + num_verf); i++)
   //   send_block[send_cnt++] = 0xFF;
   memset(&send_block[send_cnt], 0x0FF, 42+num_verf);
   send_cnt += 42+num_verf;

   // now send the block
   OWASSERT( owBlock(portnum,resume,send_block,send_cnt),
             OWERROR_BLOCK_FAILED, -1 );

   //\\//\\//\\//\\//\\//\\//\\//\\//\\//
   #ifdef DEBUG_DUMP
      debugout(send_block,send_cnt);
   #endif
   //\\//\\//\\//\\//\\//\\//\\//\\//\\//

   // check the CRC
   for (i = resume?4:3; i < (send_cnt - num_verf); i++)
      lastcrc16 = docrc16(portnum,send_block[i]);

   // verify CRC16 is correct
   OWASSERT( lastcrc16==0xB001, OWERROR_CRC_FAILED, -1);

   // check verification
   OWASSERT( ((send_block[send_cnt-1] & 0xF0) == 0x50) ||
             ((send_block[send_cnt-1] & 0xF0) == 0xA0),
             OWERROR_NO_COMPLETION_BYTE, -1);

   // transfer results
   //cnt = 0;
   //for (i = send_cnt - 42 - num_verf; i < (send_cnt - 10 - num_verf); i++)
   //   data[cnt++] = send_block[i];
   memcpy(data, &send_block[send_cnt-42-num_verf], 32);

   wcc = BytesToInt(&send_block[send_cnt-10-num_verf], 4);

   if(sign!=NULL)
   {
      OWASSERT( ReadScratchpadSHA18(portnum, 0, 0, send_block, TRUE),
                OWERROR_READ_SCRATCHPAD_FAILED, FALSE );

      //for(i=0; i<20; i++)
      //   sign[i] = send_block[i+8];
      memcpy(sign, &send_block[8], 20);
   }

   return wcc;
}
Example #9
0
void CChunksEvent::Describe(std::ostream& aOutput) const
    {
	int subcat = SubCategory();
	
	switch (subcat)
        {
        case BTrace::EChunkCreated:
            aOutput << "Chunk Create: [ChunkId=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << Arg1() << "] [MaxSize=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << BytesToInt(Data()) << "] [Name="
                << (Data() + 4) << "] ";
            break;
		
        case BTrace::EChunkDestroyed:
            aOutput << "Chunk Destroy: [ChunkId=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << Arg1() << "] ";
            break;
	
        case BTrace::EChunkInfo:
            aOutput << "Chunk Info: [ChunkId=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << Arg1() << "] [Type=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << BytesToInt(Data()) << "] [Attr=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << BytesToInt(Data()+4) << "] ";
            break;
	
        case BTrace::EChunkMemoryAdded:
            aOutput << "Chunk Memory Added: [ChunkId=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << Arg1() << "] [Offset=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << BytesToInt(Data()) << "] [Size=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << BytesToInt(Data()+4) << "] ";
            break;
		
        case BTrace::EChunkMemoryAllocated:
            aOutput << "Chunk Memory Allocated: [ChunkId=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << Arg1() << "] [Offset=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << BytesToInt(Data()) << "] [Size=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << BytesToInt(Data()+4) << "] ";
            break;
		
        case BTrace::EChunkMemoryDeallocated:
            aOutput << "Chunk Memory Deallocated: [ChunkId=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << Arg1() << "] [Offset=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << BytesToInt(Data()) << "] [Size=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << BytesToInt(Data()+4) << "] ";
            break;
	
        case BTrace::EChunkMemoryRemoved:
            aOutput << "Chunk Memory Removed: [ChunkId=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << Arg1() << "] [Offset=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << BytesToInt(Data()) << "] [Size=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << BytesToInt(Data()+4) << "] ";
            break;
	
        case BTrace::EChunkOwner:
            aOutput << "Chunk Owner: [ChunkId=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << Arg1() << "] [DProcess=0x"
                << std::noshowbase << std::setw(8) << std::setfill('0') << std::nouppercase << std::hex
                << BytesToInt(Data()) << "] ";
            break;

        default:
            aOutput << "Unknown Event ";
            break;
        }
    }
Example #10
0
int main(int nargs, char** argv)
{
    struct  termios             oldTio;
    struct  addrinfo            *hostInfoList = nullptr; // Pointer to the linked list of host_info's.
    struct  ThreadSerialInfo    sInfo = {-1, -1, -1, 1, SIM_NONE, &mySim, 0, {0, 0, 0, 0}};
    auto                        serial = ARDUINO_SP_NAME;
    pthread_t                   threadID;
    
    gettimeofday(&gStartTime, NULL);

    signal(SIGINT, SIG_IGN);
    signal(SIGHUP, signalHandler);


    // Hardcode the serial communication for PC client
    mySim.verbose = atoi(argv[2]);

    if(!CreateSocket(&sInfo.gSocketHandle, hostInfoList))
        return 1;
    
    // Create the the thread
    if(pthread_create(&threadID, NULL, &SocketReadThread, &sInfo)) {
        print("Error: Couldn't create the thread\n");
        
        CloseSocket(&sInfo.gSocketHandle, &sInfo.gListenSocketHandle, hostInfoList);
        return 1;
    }
    
    while(sInfo.gSocketHandle==-1)
        usleep(WAIT_TIME_INF_LOOP);
    
    print("Waiting for python script app to connect...\n");
    
    while(sInfo.gListenSocketHandle==-1)
        usleep(WAIT_TIME_INF_LOOP);
    
    print("Python script connected\n");

    // The third parameter for the app is the port name
    if((gftHandle[giDeviceID] = open(serial, O_RDWR | O_NOCTTY | O_NONBLOCK | O_NDELAY))==-1) {
        print("Error: Could not connect to "); print(serial); print("\n");
        CloseSocket(&sInfo.gSocketHandle, &sInfo.gListenSocketHandle, hostInfoList);
        return 1;
    } else {
        print("Opened device "); print(serial); print("\n");
        
        SetDefaultPortSettings(&gftHandle[giDeviceID], &oldTio);
        
        sInfo.serialPortHandle = gftHandle[giDeviceID];
    
        gWaitDescriptors[0].fd = gftHandle[giDeviceID];
        gWaitDescriptors[0].events = POLLIN;
        gWaitDescriptors[1].fd = sInfo.gListenSocketHandle;
        gWaitDescriptors[1].events = POLLIN;
        
        TR_PL_ID *bufIDs = NULL;
        
        while(sInfo.gCommands!=SIM_END) {
            unsigned char Buf = 0, sParBuf[6], tmpBuf[2048];
            int idx = 0;
            ssize_t dwBytes;
            unsigned int nBufIDSize = 0, parValue = 0;
            int pollRc;
            size_t bytesRead = 0;
            unsigned int test = 0;
            
            //simulate a batch of trajectory
            if(sInfo.gCommands != SIM_NONE)
                mySim.SimulateSinglePath();
            
            //usleep(WAIT_TIME_INF_LOOP);
            
            switch (sInfo.gCommands)
            {
                case SIM_START:
                    
                    nAtriumBeats = 0;
                    nVentricleBeats = 0;
                    gettimeofday(&gStartTime, NULL);
                    
                    
                    gTranList.clear();
                    mySim.StartSimulation();
                    
                    Buf = 'W';
                    WriteToPort(&gftHandle[giDeviceID], 1, &Buf);
                    
                    break;
                    
                case SIM_END:
                    
                    Buf = 'S';
                    WriteToPort(&gftHandle[giDeviceID], 1, &Buf);
                    
                    break;
                    
                case SIM_STOP:
                    sInfo.gCommands = SIM_NONE;
                    
                    std::cerr << "********************************"<<std::endl;
                    std::cerr << "Client simulation stop at time: "<< mySim.curr_time << std::endl;
                    
                    Buf = 'S';
                    WriteToPort(&gftHandle[giDeviceID], 1, &Buf);
                    
                    Buf = 0;
                    while(Buf!=SIM_READY) {
                        pollRc = poll(&gWaitDescriptors[0], 2, -1);
                        
                        if (pollRc < 0) {
                            print("Error: setting the poll\n");
                            sInfo.gCommands = SIM_END;
                        } else if(pollRc > 0) {
                            
                            if( gWaitDescriptors[0].revents & POLLIN )
                                bytesRead = read(gftHandle[giDeviceID], &Buf, (int)1);
                            else if(gWaitDescriptors[0].revents & POLLHUP || gWaitDescriptors[0].revents & POLLERR) {
                                print("Error: poll read gftHandle\n");
                                sInfo.gCommands = SIM_END;
                            }
                        }
    
                    }
                    
                    std::cerr << "Number of atrium beats: "<< nAtriumBeats << std::endl;
                    std::cerr << "Number of ventricle beats: "<< nVentricleBeats << std::endl;
                    
                    break;
                    
                case SIM_GET_ID:
                    sInfo.gCommands = SIM_NONE;
                    
                    print("Number of transition IDs: "); print((float)(gTranList.size())); print("\n");
                    
                    //nBufIDSize = (gTranList.size())*sizeof(TR_PL_ID);
                    nBufIDSize = (gTranList.size())*sizeof(EventTime);
                    
                    if(bufIDs!=NULL) delete [] bufIDs;
                    
                    bufIDs = new TR_PL_ID[nBufIDSize];
                    
                    memset((void*)&bufIDs[0], 0, nBufIDSize);
                    
                    dwBytes = send(sInfo.gListenSocketHandle, (void*)&nBufIDSize, sizeof(nBufIDSize), 0);
                    
                    for (std::list<EventTime>::iterator it=gTranList.begin(); it != gTranList.end(); ++it) {
                        bufIDs[idx] = (*it).event;
                        memcpy(&bufIDs[idx+1], (const void*)&(*it).time, sizeof(unsigned int));
                        //print((float)(*it).time); print(" "); print((float)(*it).event); print("\n");
                        //idx++;
                        idx+=sizeof(EventTime);
                    }
                    
                    dwBytes = send(sInfo.gListenSocketHandle, (void*)bufIDs, (size_t)(nBufIDSize), 0);
                    
                    if(!dwBytes)
                        print("No IDs or write socket error\n");
                    else {
                        print("Number of bytes sent: "); print((float)(dwBytes)); print("\n");
                    }

                    break;
                    
                case SIM_SET_CPAR:
                    sInfo.gCommands = SIM_NONE;
                    
                    parValue = BytesToInt(sInfo.gParBuf);
                    print("Setting Client parameter ID: "); print((float)(sInfo.gParId)); print(" Value: "); print((float)parValue); print("\n");
                    
                    SetParameters(sInfo.gParId, (unsigned long)(parValue));
                    
                    Buf = SIM_READY;
                    dwBytes = send(sInfo.gListenSocketHandle, (void*)&Buf, 1, 0);
                    
                    break;
                    
                case SIM_SET_PPAR:
                    sInfo.gCommands = SIM_NONE;
                    
                    
                    parValue = BytesToInt(sInfo.gParBuf);
                    print("Setting Arduino parameter ID: "); print((float)(sInfo.gParId)); print(" Value: "); print((float)parValue); print("\n");
                    
                    sParBuf[0] = 'D';
                    sParBuf[1] = sInfo.gParId;
                    memcpy((void*)&sParBuf[2], (const void*)&sInfo.gParBuf[0], 4);
                    
                    WriteToPort(&gftHandle[giDeviceID], 6, &sParBuf[0]);
                    
                    
                    pollRc = poll(&gWaitDescriptors[0], 2, -1);
                    
                    if (pollRc < 0) {
                        print("Error: setting the poll\n");
                        sInfo.gCommands = SIM_END;
                    } else if(pollRc > 0) {
                        
                        if( gWaitDescriptors[0].revents & POLLIN ) {
                            bytesRead = read(gftHandle[giDeviceID], &Buf, (int)1);
                            if (Buf!=SIM_READY) {
                                print("Wrong Arduino reply: "); print(Buf); print("\n");
                                sInfo.gCommands = SIM_END;
                            }
                            
                            Buf=SIM_READY;
                            dwBytes = send(sInfo.gListenSocketHandle, (void*)&Buf, 1, 0);

                        }
                        else if(gWaitDescriptors[0].revents & POLLHUP || gWaitDescriptors[0].revents & POLLERR) {
                            print("Error: poll read gftHandle\n");
                            sInfo.gCommands = SIM_END;
                        }
                    }
                    break;
                    
                case SIM_NONE:
                    break;
                    
                default:
                    sInfo.gCommands = SIM_NONE;
            }
            
        }
        
        if(bufIDs!=NULL)
            delete [] bufIDs;
    }
    
    // End the thread
    sInfo.gEndThread = 0;

    // wait for the thread to exit
    pthread_join(threadID, NULL);

    CloseSocket(&sInfo.gSocketHandle, &sInfo.gListenSocketHandle, hostInfoList);
    ClosePortDevice(&gftHandle[giDeviceID], &oldTio);
    
    return (0);
}
unsigned int PacketReader::readInt() {
    return BytesToInt(readChar(), readChar(), readChar(), readChar());
}