// Read a byte. If the buffer is empty, wait for a byte to come void CCPCBooster::ReadWaitByte(unsigned char &val) { int ret; do { ret = RS232_PollComport(_COMPortHandle, &val, 1); } while (ret != 1); }
void acquireData(gloveData_t *gd, bool clear = false){ unsigned char *buf; char *bigBuf; buf = (unsigned char*)malloc(sizeof(unsigned char) * 2); bigBuf = (char *)malloc(sizeof(char) * 100); int bbP = 0; buf[1] = '\0'; int n; bool done = false; if(clear){ clearBuffer(COMPORT); } while (!done){ n = RS232_PollComport(COMPORT, buf, 1); if (n>0) { if (bbP > 98){bbP = 0;} bigBuf[bbP] = buf[0]; bbP++; if (buf[0] == ']'){ bigBuf[bbP] = '\0'; bbP = 0; //printf("%s\n", bigBuf); if (parseData(gd, bigBuf)){ done = true; } } } } }
// need new name and to work on variable declarations const char * rain(const char * cmds, const char * rtrn) { static int l; int i, n, k, /*needed for utility*/ cport_nr=2, /* com port 3 */ bdrate=9600; /* 9600 baud */ unsigned char buf[4096]; k = 1; /* used to terminate program -- hopefully */ if (l !=1) { if(RS232_OpenComport(cport_nr, bdrate)) { printf("Can not open comport\n"); return(0); } else l = 1; } while(k==1) { //send command //printf("2nd_232 %s\n", cmds); RS232_cputs(cport_nr, cmds); Sleep(100); /* sleep for 100 milliSeconds */ //now ck for response n = RS232_PollComport(cport_nr, buf, 4095); if(n > 0) { buf[n] = 0; /* always put a "null" at the end of a string! */ for(i=0; i < n; i++) { if(buf[i] < 32) /* replace unreadable control-codes by dots */ { buf[i] = '.'; } } //printf("here\n"); //printf("received %i bytes: %s\n", n, (char *)buf); rtrn = (char*)buf; //I think that this is 'casting' memset(buf,0,strlen(buf)); } k = 0; } #ifdef _WIN32 Sleep(100); #else usleep(100000); /* sleep for 100 milliSeconds */ #endif return(cmds); }
void programByte(uint8_t dat) { uint8_t datr; again: RS232_SendByte(24,dat); RS232_PollComport(24,&datr,1); if (datr!='N') printf("Error programming byte letter code '%c'\n",datr); }
void bt_getReturnINQ( void ) { int lens = 0; unsigned char pString[128] = {0}; lens = RS232_PollComport(com_port, pString, 100); printf("[%i]\n", lens); printf(pString); printf("\n"); }
char _RS232_ReadByte(int comport_number, int line){ char data = -1; int count = 0; while(RS232_PollComport(comport_number, &data, 1) == 0 && count < MAX_TRIES) count++; if(count >= MAX_TRIES){ RS232_CloseComport(COMPORT); UNITY_TEST_FAIL(line,"Attempt to read byte but comport seems not responsive"); } return data; }
void receiveBuffer(){ byte buf[4096]; int n = RS232_PollComport(TTYACM0, buf, 4095); if(n > 0) { for(int i=0; i < n; i++) { serial.handleIncomingByte(buf[i]); } } }
static void amodem_readthread(void *arg){ char dump[BUFSIZE]; char *remote_msg; int n; int type; char *pNL; while(1){ usleep(10000); pthread_mutex_lock(&modem.readthread); n=RS232_PollComport(modem.fd,dump,BUFSIZE); pthread_mutex_unlock(&modem.readthread); if (n<1) continue; /*store to input buffer*/ if ((pNL=strstr(dump,"\r"))!=NULL) *pNL = '\0'; if ((pNL=strstr(dump,"\n"))!=NULL) *pNL = '\0'; // dump[n-2]='\0';/*remove newline char*/ //#ifdef MASTER_H // packet for address signal if (strstr(dump,"$Packet ")!=NULL){ sscanf(dump,"%*s %*s %*s %d",&type); printf("recv command %d\n",type); task_push(&task_recv_master,type,0," "); continue;} /*return if text = user <>*/ //#endif //store to msg list (local & remote)*/ if (strstr(dump,"DATA")==NULL) amodem_msg_push(&msg_local,dump);//local //#ifdef MASTER_H else {//remote remote_msg=strstr(dump,":")+1; //if msg from remote , show it printf("Remote : %s\n",remote_msg); amodem_msg_push(&msg_remote,remote_msg); //if go slave request, be slave*/ remote_msg=strstr(dump,"REQ"); if (remote_msg!=NULL){ remote_msg+=3; sscanf(remote_msg,"%d",&type); printf("recv command %d\n",type); task_push(&task_recv_master,type,0," "); continue; } } //#endif } }
// Write serial data to file - used for ROM and RAM dumping void write_to_file(char* filename, char* cmd, int blocksize) { // Create a new file FILE *pFile = fopen(filename, "wb"); RS232_cputs(cport_nr, cmd); int Kbytesread = 0; int uptoKbytes = 1; unsigned char buf[4096]; int n = 0; int timeout = 0; while(1) { n = RS232_PollComport(cport_nr, buf, 4095); if (n > 0) { buf[n] = 0; fwrite((char *) buf, 1, n, pFile); printf("#"); Kbytesread += n; if (blocksize == 32) { if (Kbytesread / 32768 == uptoKbytes) { printf("%iK", (Kbytesread/32768) * 32); uptoKbytes++; } } else { if (Kbytesread / 1024 >= uptoKbytes) { printf("%iK", (Kbytesread/1024)); uptoKbytes++; } } fflush(stdout); timeout = 0; } else { timeout++; if (timeout >= 50) { break; } #ifdef _WIN32 Sleep(50); #else usleep(50000); // Sleep for 50 milliseconds #endif } } fclose(pFile); }
int main() { int i, n, cport_nr=24, /* /dev/ttyACM0 */ bdrate=9600; /* 9600 baud */ unsigned char buf[4096]; char mode[]={'8','N','1',0}; if(RS232_OpenComport(cport_nr, bdrate, mode)) { printf("Can not open comport\n"); return(0); } while(1) { n = RS232_PollComport(cport_nr, buf, 4095); if(n > 0) { buf[n] = 0; /* always put a "null" at the end of a string! */ for(i=0; i < n; i++) { if(buf[i] < 32) /* replace unreadable control-codes by dots */ { buf[i] = '.'; } } printf("received %i bytes: %s\n", n, (char *)buf); } #ifdef _WIN32 Sleep(100); #else usleep(100000); /* sleep for 100 milliSeconds */ #endif } return(0); }
// Read multiple bytes at once, waiting if there isn't enough bool CCPCBooster::ReadWaitBuffer(unsigned char *buffer, const long nbBytes) { long bytesLeft = nbBytes; while(bytesLeft != 0) { int i = RS232_PollComport(_COMPortHandle, buffer, bytesLeft); if (i >= 0) { bytesLeft -= i; buffer += i; } else { // error! return false; } } return true; }
// {{{RME enter ':TOP:pollData' INLINE_METHODS void serialCommunicationCapsule_Actor::enter4_pollData( void ) { // {{{USR int i = 0; int n = 0; unsigned char buf[4096]; n = RS232_PollComport(COM_PORT, buf, 4095); if(n > 0) { //buf[n] = 0; /* always put a "null" at the end of a string! */ byteArray data(buf, n-1); //cout << "SER: Received " << n << " bytes: "; //data.print(); serialPort.dataReceived(data).send(); } // }}}USR }
void waitRDY(void) { static const char Sig[]="RDY"; uint8_t tempC,x; uint32_t junkC=0; puts("Waiting for RDY command"); for (x=0;x<3;++x){ do { RS232_PollComport(24,&tempC,1); if (tempC != Sig[x]){ junkC++; printf("Junk Char %d or %c while waiting for %c so far skiped %d\n",tempC,tempC,Sig[x],junkC); } putchar(tempC); } while (tempC != Sig[x]); } if (junkC != 0) printf("%d junk bytes skipped\n",junkC); puts("Ready recived"); }
int main() { int n, cport_nr=0, /* /dev/ttyS0 is reserved for the testing port */ bdrate=230400; uint8_t buf[8192]; uint8_t compBuf[8192]; memset(compBuf, 0, 8192); memset(buf, 0, 8192); char mode[]={'8','N','1',0}; if(RS232_OpenComport(cport_nr, bdrate, mode)) { printf("Can not open comport\n"); return(0); } int lastTracker = 0; do { n = RS232_PollComport(cport_nr, buf, 4095); if (n + lastTracker >= 8191) { compBuf[8192] = 0; printf("Saturated the buffer; exiting\n"); printf("read compBuf content = %s", compBuf); break; } else { memcpy(compBuf+lastTracker, buf, n); lastTracker += n; } // usleep(100); } while (1); return(0); }
int main() { int state = RS232_ERROR; int com_port = 6; /* COM7 */ int baudrate = 115200; /* 115200 */ char mode[] = {'8', 'N', '1', 0}; int i = 0, n = 0; unsigned long count = 2000000; unsigned char recv_buf[RECV_BUF_SIZE + 1] = {0}; /* Open COM Port */ state = RS232_OpenComport(com_port, baudrate, mode); if(!state) printf("Open COM Port Success\n\n"); do { n = RS232_PollComport(com_port, recv_buf, RECV_BUF_SIZE); // printf("count = %4i, n = %i, recv data = ", count, n); if(n == 5) { printf("count = %7i, n = %i, recv data = ", count, n); recv_buf[n] = '\0'; printf("%s", (char *)recv_buf); } else if(n > 0) { printf("count = %4i, n = %i, recv data = ", count, n); printf("*****\n"); } // Sleep(1); } while(--count); /* Close COM Port */ RS232_CloseComport(com_port); printf("\nClose COM Port\n"); return(0); }
int rs232_PollComport (U1 *pthreads_ptr, U1 *varlist_ptr, U1 *vm_mem_ptr, S4 threadnum, S8 stacksize) { S8 portnumber, size, i; S8 retvar_index; S8 ret; S8 bvar_index; U1 buf[4096]; struct pthreads *pthreads; struct varlist *varlist; struct vm_mem *vm_mem; pthreads = (struct pthreads *) pthreads_ptr; varlist = (struct varlist *) varlist_ptr; vm_mem = (struct vm_mem *) vm_mem_ptr; if (stpull_l (threadnum, pthreads, stacksize, &retvar_index) != ERR_STACK_OK) printf ("rs232_PollComport: stack error!\n"); if (stpull_l (threadnum, pthreads, stacksize, &size) != ERR_STACK_OK) printf ("rs232_PollComport: stack error!\n"); if (stpull_l (threadnum, pthreads, stacksize, &bvar_index) != ERR_STACK_OK) printf ("rs232_PollComport: stack error!\n"); if (stpull_l (threadnum, pthreads, stacksize, &portnumber) != ERR_STACK_OK) printf ("rs232_PollComport: stack error!\n"); ret = RS232_PollComport (portnumber, buf, size); var_lock (varlist, bvar_index); for (i = 0; i < ret; i++) { if (! let_2array_byte (varlist, vm_mem, buf[i], bvar_index, i)) printf ("rs232_PollComport: return value array overflow!\n"); } var_unlock (varlist, bvar_index); var_lock (varlist, retvar_index); if (! let_2array_qint (varlist, vm_mem, ret, retvar_index, 0)) printf ("rs232_PollComport: return value array overflow!\n"); var_unlock (varlist, retvar_index); return (0); }
std::vector<std::vector<std::bitset<8>>> FPGAFitnessCalculator::receive_data( int comport_num) { unsigned char buffer[4096]; std::vector<std::vector<std::bitset<8>>> results; for (int i = 0; i < (int) pow(2, genetic_params.num_in); i++) { unsigned int total = 0; RS232_SendByte(comport_num, (unsigned char) SET_VALUE); RS232_SendByte(comport_num, (unsigned char) i); results.emplace_back(std::vector<std::bitset<8>>()); Timer timeout_timer; timeout_timer.start(1000); while (total < num_samples) { timeout_timer.update(); if (timeout_timer.isDone()) { std::cout << "TIMEOUT Detectado com " << total << " amostras coletadas." << std::endl; std::cout << "Replicando a ultima amostra." << std::endl; for (unsigned int j = total; j < num_samples; j++) { results[i].emplace_back(results[i][total - 1]); } break; } int n = RS232_PollComport(comport_num, buffer, 4096); if (n != 0) { // Se dados foram recebidos timeout_timer.start(1000); } for (int j = 0; j < n; j++, total++) { results[i].emplace_back(std::bitset<8>(buffer[j])); } } Sleep(100); } return results; }
int main(int argc, char *argv[]) { char *ptr; int i; for (i = 1; i < argc; i++) { if (argv[i][0] == '-') { if (argv[i][1] == 's') // -s number of slaves { i++; numOfSlaves = strtol(argv[i],&ptr,10); if (numOfSlaves >= 10 || numOfSlaves <= 0){ printf("pocet slave zariadeni musi byt v rozmedzi 1-9\n"); printf("pouzitie: 'PktReader [cislo portu] [-b, -s, -h, -p]'\n"); printf("priklad: 'PktReader 3 -b 9600' com 3, baudRate 9600 \n"); return 0; } }else if (argv[i][1] == 'b') // -b baudrate parameter { i++; baudRate = strtol(argv[i],&ptr,10); if (baudRate == 0){ printf("zle zadany baudrate\n"); printf("pouzitie: 'PktReader [cislo portu] [-b, -s, -h, -p]'\n"); printf("priklad: 'PktReader 3 -b 9600' com 3, baudRate 9600 \n"); return 0; } }else if (argv[i][1] == 'p') // -p comport number parameter { i++; comPort = strtol(argv[1],&ptr,10); if (comPort == 0){ printf("zle zadane cilo com portu\n"); printf("pouzitie: 'PktReader [cislo portu] [-b, -s, -h, -p]'\n"); printf("priklad: 'PktReader 3 -b 9600' com 3, baudRate 9600 \n"); return 0; } }else if (argv[i][1] == 'o') // -o output log file { i++; strcpy(logFile,argv[i]); }else if (argv[i][1] == 'h') // -h help { printf("\nPkrReader je program spolupracujuci s programom PktGenerator\n"); printf("Program cita pakety generovane programom PktGenerator\n"); printf("Data cita z UARTu\n"); printf("pouzitie: 'PktReader [cislo portu] [-b, -s, -h, -p]'\n"); printf("priklad: 'PktReader 3 -b 9600' com 3, baudRate 9600 \n"); printf("parametre: -b baudrate [115200]\n"); printf(" -p comPort [3]\n"); printf(" -s pocet slave zariadeni [4]\n"); printf(" -o output vystupny log subor [log.txt]\n"); printf(" -h help \n"); printf("\n"); return 0; }else{ printf("Invalid option %s", argv[i]); return 2; } } else { if (i == 1){ comPort = strtol(argv[1],&ptr,10); if (comPort == 0){ printf("zle zadane cilo com portu\n"); printf("pouzitie: 'PktReader [cislo portu] [-b, -s, -h, -p]'\n"); printf("priklad: 'PktReader 3 -b 9600' com 3, baudRate 9600 \n"); return 0; } }else{ printf("Invalid option %s",argv[i]); return 0; } } } bool synchronizeFlag = true; struct PRNGslave slaves[numOfSlaves]; char message[100]; unsigned char buffer[250]; int bufferPointer = 0; logFilePointer = fopen(logFile,"w+"); atexit(close_all); //inicializovanie hodnot pre slave zariadenia for(i=0; i<numOfSlaves;i++) PRNGinit(&slaves[i],i+1); //inicialaizacia a otvorenie com portu char mode[]={'8','N','1',0}; if(RS232_OpenComport(comPort -1, BAUD_RATE, mode)) { printf("Can not open comport\n"); printf("neda sa otvorit com port (com port je pravdepodobne otvoreny inou aplikaciou)\n"); fclose(logFilePointer); RS232_CloseComport(comPort -1); return 0; } else{ printf ( "seriovy com%d port uspesne otvoreny",comPort); RS232_flushRXTX(comPort -1); std::chrono::time_point<std::chrono::system_clock> start, end; start = std::chrono::system_clock::now(); //nekonecna slucka primajuca data unsigned char c; while(1){ while ( 0 == RS232_PollComport(comPort -1, &c, 1)); //if message if (c == '\n')//begining of message { while(c != '#')//packet { fputc(c,logFilePointer); putchar(c); while ( 0 == RS232_PollComport(comPort -1, &c, 1)); } fputc(c,logFilePointer); putchar(c); while ( 0 == RS232_PollComport(comPort -1, &c, 1)); } //skontroluj ci je prijimanie synchronizovane if (synchronizeFlag == true){ if (c <= '9' || c >= '0' || c >= 'A' || c <= 'F' || c == '$'){//if hexadecimal chars buffer[bufferPointer] = c; bufferPointer++; } else{ printf("\nunexpected char %c ",c); } } else{//cakaj na synchronizacny znak if(c == '$')//packet end identifier { bufferPointer = 0; synchronizeFlag = true; }else{ fputc(c,logFilePointer); putchar(c); } } end = std::chrono::system_clock::now(); // pociatanie uplynuleho casoveho useku std::chrono::duration<double> elapsed_seconds = end-start; if (elapsed_seconds.count() >= 1) { //after 1 sec. print_output(slaves, numOfSlaves); start = std::chrono::system_clock::now(); } if (bufferPointer >= sizeof(struct PRNGrandomPacket)*2 && synchronizeFlag == true){ //konvertuj paket z hexadecimalnej do binarnej podoby hexaToBin(&buffer[bufferPointer - sizeof(struct PRNGrandomPacket)*2],buffer,sizeof(struct PRNGrandomPacket)); buffer[(sizeof(struct PRNGrandomPacket))] = '$'; buffer[(sizeof(struct PRNGrandomPacket))+1] = '\0'; if (PRNGcheck(slaves,(struct PRNGrandomPacket*)buffer,(uint8_t *)message,numOfSlaves)){ puts(message); fputs(message,logFilePointer); synchronizeFlag = false; } else{ //printf("packet is valid"); } bufferPointer -= ((sizeof(struct PRNGrandomPacket)*2) +1); } } } }
void clearBuffer(int port){ unsigned char buf[999]; while (RS232_PollComport(port, buf, 999) == 999){} }
char* ComC(int a, int cport_nr, char *b) { static int j=0; int i, k=0, n, bdrate=115200; /* cport_nr 15 is (COM16 on windows) */ /* 115200 baud */ int bytes_sent, bytes_received; unsigned char buf[4096]; //key[70]; char temp [65];//char temp [64]; unsigned char login[6] = "root\r"; unsigned char getValue[11]="fpga info\r"; //a=1; if( a<2 && RS232_OpenComport(cport_nr, bdrate) ) { printf("Can not open comport\n"); return b[0]; } while(1 && j <1 && a <2) { n = RS232_PollComport(cport_nr, buf, 4095); if(n > 0) { buf[n] = 0; /* always put a "null" at the end of a string! */ for(i=0; i < n; i++) { if(buf[i] < 32) /* replace unreadable control-codes by dots */ { buf[i] = '.'; } } printf("%s", (char*) buf); if (strstr((char*) buf,"login:"******"Sent %i bytes\n",bytes_sent); // printf("received %i bytes: %s\n", n, (char *)buf); j++; } } } while (a<2) { a=1; printf("%s", (char*) buf); memset(&buf[0], 0, sizeof(buf)); Sleep(1000); bytes_sent = RS232_SendBuf(cport_nr,getValue, 10); Sleep(1000); n = RS232_PollComport(cport_nr, buf, 4095); Sleep(1000); printf("%s", (char*) buf); a++; } j=0; //while (j<1 && a>=2 && a <= 64) while (j<1 && a>=2 ) { //printf("%s", (char*) buf); memset(&buf[0], 0, sizeof(buf)); Sleep(1000); bytes_sent = RS232_SendBuf(cport_nr,getValue, 10); Sleep(1000); n = RS232_PollComport(cport_nr, buf, 4095); Sleep(1000); printf("%s \n", (char*) buf); fflush(stdout); i=0; while(k<66) { if((buf[112+k]!= 13) && (buf[112+k]!= 10)) { temp[i] = buf[112+k]; printf("%c", temp[i]); i++; } k++; } temp[i] = '\0'; printf("\n\nThe string is %s", temp); a++; j++; } strcpy(b,temp); printf("\n%s",b); Sleep(100); //Print for Debug return b; }
void Hardware::OnEvent() { uint8_t buffer[BUFFER_SIZE]; int size = RS232_PollComport(SERIAL_PORT, buffer, BUFFER_SIZE); if (size >0){ serial_packet *s_data = &this->prve_packet; uint8_t *enc = buffer; if(size < 5 && (s_data->data_size==0) && ((this->cache_length+size) < 5)){ memcpy(this->cache + this->cache_length, buffer, size); this->cache_length += size; return; } if(this->cache_length > 0){ uint8_t temp[BUFFER_SIZE]; memcpy(temp, this->cache, this->cache_length); memcpy(temp + this->cache_length, buffer, size); size+= this->cache_length; memcpy(buffer, temp, size); this->cache_length = 0; } while(size > 0){ if(s_data->data_size == 0x0){ if(enc[0] == 0xBC && enc[1]==0xAC){ s_data->head = *enc++; s_data->ack = *enc++; s_data->data_size = *enc++; size-=3; }else{ enc++; size--; } }else if(s_data->read_size < s_data->data_size){ uint8_t read_size = s_data->data_size - s_data->read_size; if(read_size > size) { read_size = size; } if(s_data->read_size+read_size<260){ //jyc20150911debug memcpy(s_data->data+s_data->read_size, enc, read_size); s_data->read_size +=read_size; enc+=read_size; } size -= read_size; }else{ s_data->end_ack = *enc++; size--; if(s_data->ack == s_data->end_ack){ //printf("rec %d\n",s_data->read_size); onPacketRead(s_data); } memset(s_data, 0, sizeof(serial_packet)); } } } }
// Non-blocking read of a byte. Returns the number of bytes read. int CCPCBooster::ReadByte(unsigned char &val) { return RS232_PollComport(_COMPortHandle, &val, 1); }
// read multiple bytes, non-blocking. long CCPCBooster::ReadBuffer(unsigned char *buffer, const long nbBytes) { return RS232_PollComport(_COMPortHandle, buffer, nbBytes); }
int main(void) { int n, cport_nr = 4, /* 6 (COM5 on windows) */ bdrate = 38400; /* 9600 baud */ uint8_t buf[BUF_SIZE + 1]; uint8_t data[MAX_DATA_SIZE]; char mode[] = {'8','N','1',0}; if (RS232_OpenComport(cport_nr, bdrate, mode)) { printf("Can not open comport\n"); return(0); } int received_cnt = 0; while (1) { n = RS232_PollComport(cport_nr, buf, BUF_SIZE); if (n > 0) { /* always put a "null" at the end of a string! */ buf[n] = 0; printf("Received %i bytes: %s\n", n, (char *) buf); if (arr_search("TKENDTKENDTKENDTKEND", BUF_SIZE, buf, n) > 0) { printf("%s\n", "Starting reception..."); memset(data, 0, MAX_DATA_SIZE); /* Initialize the array */ received_cnt = 0; } else { int pos = -1; /* If receiving the end of current compressed buffer, send & reinitialize */ if ((pos = arr_search("TKENDTKENDTKENDTKE", DELIMITER_LEN, buf, n)) >= 0) { int eff_len = pos - DELIMITER_LEN + 1; uint8_t temp[eff_len]; memcpy(temp, buf, eff_len); memcpy(data + received_cnt, temp, eff_len); received_cnt += eff_len; /* Discard the last five bytes of indicators*/ char size_buf[2]; memcpy(size_buf, buf + pos + 1, 2); int size = size_buf[1] + (size_buf[0] << 4); printf("Received data total size: %d\n", size); uint8_t comp[size]; memcpy(comp, data, size); decompress(comp, size); /* Clean up */ memset(data, 0, MAX_DATA_SIZE); received_cnt = 0; /* Also need to store rest of the data to avoid loss */ // uint8_t lost[n - eff_len - 5]; // memcpy(lost, buf + pos + 1, n - pos - 1); // memcpy(data, lost, n - pos - 1); // received_cnt += n - pos - 1; } else { /* If regular data packets, store it*/ memcpy(data + received_cnt, buf, n); received_cnt = received_cnt + n; } } } #ifdef _WIN32 Sleep(100); #else usleep(100000); /* sleep for 100 milliSeconds */ #endif } return (0); }
int main ( int argc, char *argv[] ) { int n,j, cport_nr=22, /* /dev/ttyAMA0 */ bdrate=9600; /* 9600 baud */ unsigned char buf[128]; // Parse the command line options for (j = 1; j < argc; j++) { int more = j+1 < argc; // There are more arguments if (!strcmp(argv[j],"--port") && more) { cport_nr=atoi(argv[++j]); } else if (!strcmp(argv[j],"--baud") && more) { bdrate=atoi(argv[++j]); } else if (!strcmp(argv[j],"--debug")) { debug=1; } else if (!strcmp(argv[j],"--verbose")) { verbose=1; } else if (!strcmp(argv[j],"--demo")) { demoMode=1; } else if (!strcmp(argv[j],"--help")) { showHelp(); exit(0); } else { fprintf(stderr, "Unknown or not enough arguments for option '%s'.\n\n", argv[j]); showHelp(); exit(1); } } if (debug==1) { printf("Using port %i\n", cport_nr); printf("Baud Rate %i\n", bdrate); } unsigned char requestString[] = {0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xEB, 0x90, 0xEB, 0x90, 0xEB, 0x90, 0x16, 0xA0, 0x00, 0xB1, 0xA7, 0x7F}; int sentChars; if (demoMode == 0) { if(RS232_OpenComport(cport_nr, bdrate)) { if (debug == 1) printf("Can not open comport\n"); return(0); } sentChars = RS232_SendBuf(cport_nr,requestString,18); if(sentChars<0) { if (debug == 1) printf("Can not send request\n"); return(0); } } else { sentChars = 18; } if (debug == 1) { printf("Sent %i bytes: ", sentChars); print_hex_memory((char *)requestString, 18); } if (demoMode == 0) { usleep(100000); n = RS232_PollComport(cport_nr, buf, 127); } else { //Manually fake a response unsigned char buf2[] = {0xEB, 0x90, 0xEB, 0x90, 0xEB, 0x90, 0x00, 0xA0, 0x18, 0xC9, 0x05, 0x36, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x4E, 0x04, 0xAE, 0x05, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x01, 0x01, 0x2E, 0x5D, 0x01, 0x00, 0x21, 0xF2, 0x7F, 0x00}; memcpy(buf, buf2, 36); n=36; } if(n > 0) { buf[n] = 0; /* always put a "null" at the end of a string! */ if (debug == 1) { printf("received %i bytes\n", n); print_hex_memory((char *)buf, n); } if (verbose == 1) process_string_verbose((char *)buf); else process_string((char *)buf); } return(0); }
int main() { read_config(); printf("GBCartRead v1.8 by insideGadgets\n"); printf("################################\n\n"); printf("Opening COM PORT %d at %d baud...\n\n", cport_nr+1, bdrate); // Open COM port if(RS232_OpenComport(cport_nr, bdrate)) { printf("Can not open comport\n"); return(0); } #ifdef _WIN32 Sleep(2000); #else usleep(2000000); // Sleep for 2 seconds #endif char userInput = '0'; while (1) { printf ("\nSelect an option below\n0. Read Header\n1. Dump ROM\n2. Save RAM\n3. Write RAM\n4. Exit\n"); printf (">"); userInput = read_one_letter(); if (userInput == '0') { headercounter = 0; RS232_cputs(cport_nr, "HEADER\n"); unsigned char buffer[4096]; int n = 0; int waitingforheader = 0; while (1) { n = RS232_PollComport(cport_nr, buffer, 4095); if (n > 0) { buffer[n] = 0; fflush(stdout); break; // Got the data, exit } else { waitingforheader++; if (waitingforheader >= 50) { break; } #ifdef _WIN32 Sleep(50); #else usleep(50000); // Sleep for 100 milliseconds #endif } } char* tokstr = strtok ((char *) buffer, "\r\n"); while (tokstr != NULL) { if (headercounter == 0) { printf ("\nGame title... "); printf ("%s\n", tokstr); strncpy(gametitle, tokstr, 30); } if (headercounter == 1) { printf ("MBC type... "); cartridgeType = atoi(tokstr); switch (cartridgeType) { case 0: printf ("ROM ONLY\n"); break; case 1: printf ("MBC1\n"); break; case 2: printf ("MBC1+RAM\n"); break; case 3: printf ("MBC1+RAM+BATTERY\n"); break; case 5: printf ("MBC2\n"); break; case 6: printf ("MBC2+BATTERY\n"); break; case 8: printf ("ROM+RAM\n"); break; case 9: printf ("ROM ONLY\n"); break; case 11: printf ("MMM01\n"); break; case 12: printf ("MMM01+RAM\n"); break; case 13: printf ("MMM01+RAM+BATTERY\n"); break; case 15: printf ("MBC3+TIMER+BATTERY\n"); break; case 16: printf ("MBC3+TIMER+RAM+BATTERY\n"); break; case 17: printf ("MBC3\n"); break; case 18: printf ("MBC3+RAM\n"); break; case 19: printf ("MBC3+RAM+BATTERY\n"); break; case 21: printf ("MBC4\n"); break; case 22: printf ("MBC4+RAM\n"); break; case 23: printf ("MBC4+RAM+BATTERY\n"); break; case 25: printf ("MBC5\n"); break; case 26: printf ("MBC5+RAM\n"); break; case 27: printf ("MBC5+RAM+BATTERY\n"); break; case 28: printf ("MBC5+RUMBLE\n"); break; case 29: printf ("MBC5+RUMBLE+RAM\n"); break; case 30: printf ("MBC5+RUMBLE+RAM+BATTERY\n"); break; case 99: printf ("WISDOM TREE MAPPER\n"); break; case 252: printf("Gameboy Camera\n"); break; default: printf ("Not found\n"); } } else if (headercounter == 2) { printf ("ROM size... "); romSize = atoi(tokstr); switch (romSize) { case 0: printf ("32KByte (no ROM banking)\n"); break; case 1: printf ("64KByte (4 banks)\n"); break; case 2: printf ("128KByte (8 banks)\n"); break; case 3: printf ("256KByte (16 banks)\n"); break; case 4: printf ("512KByte (32 banks)\n"); break; case 5: if (cartridgeType == 1 || cartridgeType == 2 || cartridgeType == 3) { printf ("1MByte (63 banks)\n"); } else { printf ("1MByte (64 banks)\n"); } break; case 6: if (cartridgeType == 1 || cartridgeType == 2 || cartridgeType == 3) { printf ("2MByte (125 banks)\n"); } else { printf ("2MByte (128 banks)\n"); } break; case 7: printf ("4MByte (256 banks)\n"); break; case 82: printf ("1.1MByte (72 banks)\n"); break; case 83: printf ("1.2MByte (80 banks)\n"); break; case 84: printf ("1.5MByte (96 banks)\n"); break; default: printf ("Not found\n"); } } else if (headercounter == 3) { printf ("RAM size... "); ramSize = atoi(tokstr); switch (ramSize) { case 0: if (cartridgeType == 6) { printf ("512 bytes (nibbles)\n"); } else { printf ("None\n"); } break; case 1: printf ("2 KBytes\n"); break; case 2: printf ("8 KBytes\n"); break; case 3: printf ("32 KBytes (4 banks of 8Kbytes)\n"); break; case 4: printf ("128 KBytes (16 banks of 8Kbytes)\n"); break; default: printf ("Not found\n"); } } else if (headercounter == 4) { printf ("Logo check... "); logoCheck = atoi(tokstr); if (logoCheck == 1) { printf ("OK\n"); } else { printf ("Failed\n"); } } tokstr = strtok (NULL, "\r\n"); headercounter++; } fflush(stdout); } else if (userInput == '1') { printf ("\nDumping ROM to %s.gb... ", gametitle); strncpy(filename, gametitle, 20); strcat(filename, ".gb"); write_to_file(filename, "READROM\n", 32); printf ("\nFinished\n"); } else if (userInput == '2') { printf ("\nDumping RAM to %s.sav... ", gametitle); strncpy(filename, gametitle, 20); strcat(filename, ".sav"); write_to_file(filename, "READRAM\n", 1); printf ("\nFinished\n"); } else if (userInput == '3') { printf ("\nGoing to write to RAM from %s.sav...", gametitle); printf ("\n*** This will erase the save game from your Gameboy Cartridge ***"); printf ("\nPress y to continue or any other key to abort."); printf ("\n>"); char userInputConfirm = read_one_letter(); if (userInputConfirm == 'y') { printf ("\nWriting to RAM from %s.sav... ", gametitle); strncpy(filename, gametitle, 20); strcat(filename, ".sav"); read_from_file(filename, "WRITERAM\n"); printf ("\nFinished\n"); } else { printf ("\nAborted\n"); } } else if (userInput == '4') { RS232_CloseComport(cport_nr); return(0); } else { printf ("\nOption not recognised, please try again.\n"); } } return(0); }
int main() { int i, n, cport_nr=16, /* /dev/ttyUSB0 (COM1 on windows) */ bdrate=9600; /* 9600 baud */ unsigned char buf[ARDUINOBUFFER]; char mode[]={'8','N','1',0}; if(RS232_OpenComport(cport_nr, bdrate, mode)) { putError("Can not open serial port"); return(0); } char* result[2]; result[0] = malloc(BUFFER_SIZE); result[1] = malloc(BUFFER_SIZE); regex_t r; const char * regex_text; regex_text = "([[:digit:]]+)[^[:digit:]]+([[:digit:]]+)"; int cr = compile_regex(& r, regex_text); if (cr != 0) { return cr; } float humidities[COUNTPERMINUTE]; float temperatures[COUNTPERMINUTE]; long attempts = 0; char t[16], h[16]; char currentMeasurement[64]; while(1) { n = RS232_PollComport(cport_nr, buf, ARDUINOBUFFER-1); if(n > 0) { buf[n] = 0; /* always put a "null" at the end of a string! */ for(i=0; i < n; i++) { if(buf[i] < 32) /* replace unreadable control-codes by dots */ { buf[i] = '.'; } } //printf("received %i bytes: %s\n", n, (char *)buf); int success = match_regex(& r, (char*)buf, result); if (success == 0) { attempts++; sprintf(currentMeasurement, "Temperature %s Humidity %s", result[0], result[1]); //puts(currentMeasurement); syslog(LOG_INFO, currentMeasurement); int idx = attempts % COUNTPERMINUTE; humidities[idx] = atof(result[1]); temperatures[idx] = atof(result[0]); if (idx == 0 && attempts>=COUNTPERMINUTE) { float sumTemp, sumHum; int u = 0; for (u=0; u< COUNTPERMINUTE; u++) { sumTemp += temperatures[u]; sumHum += humidities[u]; } sprintf(t, "%.2lf",sumTemp/COUNTPERMINUTE); sprintf(h, "%.2lf",sumHum/COUNTPERMINUTE); // printf("Avg Temperature %s Humidity %s\r\n", t, h); postWeather(t,h,"AF993B68-0EF7-4842-8A36-8FD03A695456"); sumTemp = 0; sumHum = 0; } } else { putError("Can not parse response"); putError((char*)buf); } } usleep(100000); /* sleep for 100 milliSeconds */ } regfree (& r); return(0); }
int main(int argc,char ** argv) { uint8_t dump=0; if (argc!=2&&argc!=3){ help(); return 1; } else if(argc==3){ if(strcmp("-d",argv[2])==0) dump=1; else{ printf("To specify dumping you need to use -d but you did %s instead\nThis program will show help and exit\n",argv[2]); help(); return 1; } } if(RS232_OpenComport(24,500000)){ puts("Com-port 24 could not be opened"); return 1; } waitRDY(); RS232_SendByte(24,'R'); if(dump) RS232_SendByte(24,'R'); else RS232_SendByte(24,'W'); waitRDY(); uint8_t id,manid; RS232_PollComport(24,&manid,1); printf("Manufacture ID: 0x%X\nDetcted as: ",manid); if(manid==0xBF) puts("SST/microchip"); else puts("Unkown manufacturer"); RS232_PollComport(24,&id,1); printf("Device ID: 0x%X\n",id); uint32_t capcity=524288; switch(id){ case 0xB5: puts("SST39SF010A"); capcity=131072; case 0xB6: puts("SST39SF020A"); capcity=262144; break; case 0xB7: puts("SST39SF040"); capcity=524288; break; default: puts("ERROR: cannot deterim chip capacity defaulting to 524288"); break; } FILE* fp; uint8_t* dat; if(!dump){ fp=fopen(argv[1],"rb"); fseek(fp, 0L, SEEK_END); size_t size = ftell(fp); if (size > capcity){ puts("Your file is too large"); fclose(fp); return 1; } rewind(fp); dat=calloc(1,capcity); if (dat==0){ puts("Error allocating memory"); fclose(fp); return 1; } fread(dat,1,size,fp); fclose(fp); RS232_PollComport(24,&id,1); //putchar(id);//should be upercase 'D' if(id!='D'){ puts("An error has occuring exiting..."); free(dat); return 1; } putchar('\n'); RS232_PollComport(24,&id,1); if (id == 'S') puts("Chip is erased"); else{ printf("Error erasing chip code %c\n",id); free(dat); return 1; } }else fp=fopen(argv[1],"wb"); //now program the chip putchar('\n'); uint32_t x; for (x=0;x<capcity;++x){ uint8_t data; if(dump){ RS232_PollComport(24,&data,1); fputc(data,fp); }else{ programByte(dat[x]); RS232_PollComport(24,&data,1); if (data!=dat[x]) printf("Byte %d at address %d should be %d\n\n",data,x,dat[x]); } printf("Progress : %% %f\r",(float)x/(float)capcity*100.0); } if(dump) fclose(fp); free(dat); return 0; }
// TODO : Multiple return statements, fix this std::shared_ptr<SBGOutputFrame> SBGInsIg500N::getNextFrame() { DataFrame frame; // Used to parse the data read from the RS-232 port std::shared_ptr<SBGOutputFrame> resultFrame; u_int8_t header_buffer[HEADER_LENGTH]; u_int8_t header_temp[HEADER_LENGTH-1]; u_int8_t sync_byte[1]; //************* SYNC BYTE **************// if ( RS232_PollComport(port, sync_byte, 1 ) == 0 ){ return 0; } if( sync_byte[0] != SYNCX_VALUE){ ROS_WARN("Comm line not sync"); return 0; } //************* HEADER *************// if( RS232_PollComport(port,header_temp,HEADER_LENGTH-1) == 0 ){ // Read 4 bytes return 0; } header_buffer[0] = sync_byte[0]; for(int i = 0; i < HEADER_LENGTH-1; ++i) header_buffer[i+1] = header_temp[i]; frame.setHeader(header_buffer); //************* PARSE HEADER *************// u_int8_t command = header_buffer[(STX_LENGTH+SYNCX_LENGTH)]; u_int8_t msb_value = header_buffer[(STX_LENGTH+SYNCX_LENGTH+CMD_LENGTH)]; u_int8_t lsb_value = header_buffer[(STX_LENGTH+SYNCX_LENGTH+CMD_LENGTH+LEN_MSB_LENGTH)]; frame.setCMD(command); //************* DATA *************// u_int8_t temp_buffer[1]; u_int16_t data_length = ((msb_value << 8 )|lsb_value); ROS_INFO("Data Length:"); ROS_INFO(std::to_string((int)data_length).c_str()); u_int8_t* data_buffer = new u_int8_t(data_length); int read = 0, temp; while ( read < data_length ){ temp = RS232_PollComport(port,temp_buffer,1); if( temp == 1 ){ data_buffer[read] = temp_buffer[0]; read += temp; } } frame.setData(data_buffer); //************* FOOTER *************// u_int8_t footer_buffer[FOOTER_LENGTH]; if( RS232_PollComport(port,footer_buffer,FOOTER_LENGTH) == 0 ){ // Read 3 bytes return 0; } if ( footer_buffer[FOOTER_LENGTH-1] != ETX_VALUE ) return 0; frame.setFooter(footer_buffer); //************* CRC *************// u_int16_t crc = ((footer_buffer[0] << 8) | footer_buffer[1]); u_int8_t crc_buffer [HEADER_LENGTH+data_length+FOOTER_LENGTH]; for( int i = 0; i < HEADER_LENGTH; ++i ) crc_buffer[i] = header_buffer[i]; for(int i = 0; i < data_length; ++i) crc_buffer[(HEADER_LENGTH)+i] = data_buffer[i]; for(int i = 0; i < FOOTER_LENGTH; ++i) crc_buffer[(HEADER_LENGTH+data_length)+i] = footer_buffer[i]; u_int16_t calculated_crc = SBGFrame::calcCRC(crc_buffer,data_length); //************* PARSE COMMAND *************// if( crc == calculated_crc){ parseCommand(frame, resultFrame); } else { ROS_WARN(" Wrong CRC value "); return 0; } delete data_buffer; if ( resultFrame != 0 || resultFrame != nullptr ) return resultFrame; else return 0; }
int SBGInsIg500N::getNextAck() { DataFrame frame; // Used to parse the data read from the RS-232 port std::shared_ptr<SBGOutputFrame> resultFrame; u_int8_t header_buffer[HEADER_LENGTH]; u_int8_t header_temp[HEADER_LENGTH-1]; u_int8_t sync_byte[1]; //************SYNC BYTE***********// while( sync_byte[0] != SYNCX_VALUE ) while( RS232_PollComport(port, sync_byte, 1 )== 0) continue; //********** HEADER *************// u_int8_t tmp_buf[HEADER_LENGTH-1]; int read = 0, temp; while ( read < (HEADER_LENGTH-1) ){ temp = RS232_PollComport(port,tmp_buf,1); if( temp == 1 ){ header_temp[read] = tmp_buf[0]; read += temp; } } header_buffer[0] = sync_byte[0]; for(int i = 0; i < HEADER_LENGTH-1; i++){ header_buffer[i+1] = header_temp[i]; } frame.setHeader(header_buffer); //************* PARSE HEADER *************// u_int8_t command_ack = header_buffer[(STX_LENGTH+SYNCX_LENGTH)]; u_int8_t msb_value = header_buffer[(STX_LENGTH+SYNCX_LENGTH+CMD_LENGTH)]; u_int8_t lsb_value = header_buffer[(STX_LENGTH+SYNCX_LENGTH+CMD_LENGTH+LEN_MSB_LENGTH)]; if(command_ack != DEFAULT_ACK){ ROS_INFO("Not an acknowledge frame"); return 1; } //*************** DATA******************// u_int8_t data_temp[1]; u_int16_t data_length = ((msb_value << 8 )|lsb_value); if(data_length != ACK_LENGTH){ ROS_INFO("The data length isn't equal to 0x01"); return 1; } u_int8_t* data_buffer= new u_int8_t(ACK_LENGTH); while ( RS232_PollComport(port, data_buffer, data_length) == 0 ) continue; //**************** FOOTER ************// u_int8_t footer_buffer[FOOTER_LENGTH]; if(RS232_PollComport(port, footer_buffer, FOOTER_LENGTH) == 0){ return 1; } if(footer_buffer[FOOTER_LENGTH-1] != ETX_VALUE){ return 1; } //***************** CRC *************// u_int16_t crc = ((footer_buffer[0]<<8)|footer_buffer[1]); u_int8_t crc_buffer [HEADER_LENGTH+data_length+FOOTER_LENGTH]; for(int i = 0; i < HEADER_LENGTH; i++){ crc_buffer[i] = header_buffer[i]; } for(int i = 0; i < data_length; i++){ crc_buffer[HEADER_LENGTH + i] = data_buffer[i]; } for(int i = 0; i < FOOTER_LENGTH; i++){ crc_buffer[HEADER_LENGTH + data_length + i] = footer_buffer[i]; } u_int16_t calculated_crc = SBGFrame::calcCRC(crc_buffer,data_length); //************* PARSE COMMAND *************// if(crc == calculated_crc){ parseACK(frame); } else{ ROS_INFO("Error with the crc"); return 1; } delete data_buffer; return 0; }