Exemplo n.º 1
0
int rs232_OpenComport (U1 *pthreads_ptr, U1 *varlist_ptr, U1 *vm_mem_ptr, S4 threadnum, S8 stacksize)
{
	S8 portnumber, baudrate;
	S8 retvar_index;
	U1 mode[256];
	S8 ret;

	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_OpenComport: retvar stack error!\n");
	if (stpull_s (threadnum, pthreads, stacksize, mode) != ERR_STACK_OK) printf ("rs232_OpenComport: mode stack error!\n");
	if (stpull_l (threadnum, pthreads, stacksize, &baudrate) != ERR_STACK_OK) printf ("rs232_OpenComport: baudrate stack error!\n");
	if (stpull_l (threadnum, pthreads, stacksize, &portnumber) != ERR_STACK_OK) printf ("rs232_OpenComport: portnumber stack error!\n");
	
	ret = RS232_OpenComport (portnumber, baudrate, mode);

	var_lock (varlist, retvar_index);
	if (! let_2array_qint (varlist, vm_mem, ret, retvar_index, 0)) printf ("rs232_OpenComport: return value array overflow!\n");
	var_unlock (varlist, retvar_index);
	
	return (0);
}
Exemplo n.º 2
0
// 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);

}
Exemplo n.º 3
0
Arquivo: amodem.c Projeto: oc224/BB
int amodem_open() {
	printf("open %s\n",modem.dev_path);
	//open serial port, go to command mode, issue at (attention), then check response
	if ((modem.fd=RS232_OpenComport(modem.dev_path, amodem_serial_baudrate))<1) {
		printf("%s, Fail to open.\n",__func__);//error
		return FAIL;
	}
	return SUCCESS;
}
Exemplo n.º 4
0
void LagTestSerialPortComm::initSerialPort()
{
    QString s;
    this->sendDebugMsg(s.sprintf("Opening Com port %d ... ", portN+1));
    if(RS232_OpenComport(portN, this->baudRate))
    {
        this->sendErrorMsg("Can not open Serial port.");
        throw std::exception();
    }
}
FruitSortingApp::FruitSortingApp(int n):lemonSortingVision(n){
	this->alpha=0;
	this->beta=1;
	if(RS232_OpenComport(COMPORT,BAUDRATE) ){
					cout<<"Error in opening comport";
					exit(1);
				}

		cout<<"Successfully opened comport "<<COMPORT<<"\n";

}
Exemplo n.º 6
0
SBGInsIg500N::SBGInsIg500N ( const int _port, const int _baudrate )
	:port(_port),baudrate(_baudrate)
{
	output_mode = SBGOutputFrame::EULER;
	int opened_port = RS232_OpenComport(port,_baudrate);
	if (opened_port != 0){
		ROS_ERROR("Could not open the com port");
		throw InvalidRS232Settings();
	}
	init();
}
Exemplo n.º 7
0
int main()
{
    char HC0x = HC05;
    char pString[128] = {0};

    printf("DeviceType : ");
    scanf ("%d", &HC0x);
    if(HC0x == HC05) {
        baudrate = 38400;
    }
    else {
        printf("Baudrate : ");
        scanf ("%d", &baudrate);
    }

    /* Open COM Port */
    if(!RS232_OpenComport(com_port, baudrate, mode)) {
        printf("Open COM Port Success\n\n");

        do {
            printf("AT Command : ");
            scanf ("%s",pString);
            bt_sendATCommand(HC0x, pString);
        } while(strcmp("EXTI", pString) != 0);

        bt_sendATCommand(HC0x, "AT");
        bt_sendATCommand(HC0x, "AT+ORGL");        //
        bt_sendATCommand(HC0x, "AT+ROLE=1");      //
        bt_sendATCommand(HC0x, "AT+ROLE?");       //
        bt_sendATCommand(HC0x, "AT+PSWD=0000");   //
        bt_sendATCommand(HC0x, "AT+PSWD?");
        bt_sendATCommand(HC0x, "AT+UART=115200,0,0");
        bt_sendATCommand(HC0x, "AT+UART?");
        bt_sendATCommand(HC0x, "AT+CMODE=0");
        bt_sendATCommand(HC0x, "AT+CMODE?");
        printf("AT+BIND=");
        scanf ("%s",pString);
        bt_sendBIND(HC0x, pString);
        bt_sendATCommand(HC0x, "AT+BIND?");
    }
    else {
        printf("Open COM Port Error\n");
    }

    /* Close COM Port */
    RS232_CloseComport(com_port);
    printf("\n\nClose COM Port\n");

    return(0);
}
Exemplo n.º 8
0
// Open the communication (done when you create it)
void CCPCBooster::OpenPort()
{
	if (_currentState == PortOpened)
	{
		ClosePort();
	}

	_currentState = PortFailed;

	if (RS232_OpenComport(_COMPortNumber.c_str(),_baudrate,"8N1",&_COMPortHandle) == 0)
	{
	    _currentState = PortOpened ;
	}
}
Exemplo n.º 9
0
int main(void){
	int i;
	char charReceived, char2Send = 0;
	printf("Test UART, ready to receive character!!!\n");
	RS232_OpenComport(COMPORT, baudrate);
	char2Send = getch();
	while(char2Send != ESC_KEY){
		RS232_SendByte(COMPORT, char2Send);
		charReceived = RS232_ReadByte(COMPORT);
		printf("%c", charReceived);
		char2Send = getch();
	}
	if(char2Send == ESC_KEY)
		printf("BYE\n");
	RS232_CloseComport(COMPORT);
}
// {{{RME choicePoint ':TOP:openPort'
INLINE_METHODS int serialCommunicationCapsule_Actor::choicePoint1_openPort( const void * rtdata, RTProtocol * rtport )
{
	// {{{USR
	if(RS232_OpenComport(COM_PORT, BAUD))
	{
	  cout << "SER: Can not open COM-Port" << endl;
	  return false;
	}

	else
	{
	  cout << "SER: COM-Port open" << endl;
	  return true;
	}

	// }}}USR
}
Exemplo n.º 11
0
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);
}
Exemplo n.º 12
0
void FPGAFitnessCalculator::fitness(std::vector<Cromossomo>& populacao) {
    int bauds = 115200;
    int comport_num = 6;
    char mode[10] = "8N1";
    if (RS232_OpenComport(comport_num, bauds, mode)) {
        fprintf(stderr, "Nao consegui abrir COM port %d\n", comport_num + 1);
        exit(1);
    }

    for (unsigned int i = 0; i < populacao.size(); i++) {
        enviar_individuo(comport_num, populacao[i]);
        populacao[i].set_fitness(
            fitness_calculator(receive_data(comport_num)));
    }

    RS232_CloseComport(comport_num);
}
Exemplo n.º 13
0
void test_uartLoopback_should_echo_bytes_sent(void){
	char buffer[256], *dataPtr = buffer;
	
	RS232_OpenComport(COMPORT, baudrate);
	RS232_SendByte(COMPORT,'H');
	*(dataPtr++) = RS232_ReadByte(COMPORT);
	RS232_SendByte(COMPORT,'e');
	*(dataPtr++) = RS232_ReadByte(COMPORT);
	RS232_SendByte(COMPORT,'l');
	*(dataPtr++) = RS232_ReadByte(COMPORT);
	RS232_SendByte(COMPORT,'l');
	*(dataPtr++) = RS232_ReadByte(COMPORT);
	RS232_SendByte(COMPORT,'o');
	*(dataPtr++) = RS232_ReadByte(COMPORT);
	*(dataPtr++) = '\0';
	RS232_CloseComport(COMPORT);
	
	TEST_ASSERT_EQUAL_STRING("Hello",buffer);
	
}
Exemplo n.º 14
0
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 argc, char **argv)
{
	lx = 0;
	ly = 0;
	lz = 0;
	px = 0;
	py = 0;
	pz = 0;
	if (RS232_OpenComport(COMPORT, 9600) == 0){
		cMode = rest;

		printf("connected\n");
		printf("Hold your hand in a relaxed position and press enter\n");
		waitForEnter();
		acquireData(&grelax,true);
		printData(grelax);

		printf("Hold your hand in a fist (or as best you can) and press enter\n");
		waitForEnter();
		acquireData(&gtense,true);
		printData(gtense);

		gdiff = gtense - grelax;

		printf("Difference is: \n");
		printData(gdiff);

		printf("press enter to continue\n");
		waitForEnter();
		acquireData(&gd,true);
		setOtherLoop(&mainloop);
		glMain(argc, argv);
	}
	else{
		printf("fail\n");
	}
	

	return 0;

}
Exemplo n.º 16
0
/*
 * Start interfacing the IMU using rs232
 */
int IMUManager::init(bool imu_rec, bool sim_snd) {
	while(devid<0 && imu_rec){
		devid = getDev();
		if(devid == -1){sleep(5);}
	}

	if(RS232_OpenComport(devid, BAUD) && imu_rec) {
		logError("Could not connect to comport ");
		return 1;
	}else{
		conn = true;
	}

	// Used for testing simulator!!
	if ((simsock = socket(AF_INET,SOCK_DGRAM,0)) < 0){
		logError("socket error");
		logError(strerror(errno));
		return 1;
	}

	memset((char *)&simAddr, 0, sizeof(simAddr));
	inet_pton(AF_INET, SIM_ADDR, &(simAddr.sin_addr));
	simAddr.sin_port = htons(SIM_PORTEN);


	if(imu_rec){
		std::thread t1 (&IMUManager::readImu, this);
		std::thread t2 (&IMUManager::getControl , this);

		t1.detach();
		t2.detach();
	}
	if(sim_snd){
		std::thread t3 (&IMUManager::sendData, this);

		t3.detach();
	}

	return -1;
}
Exemplo n.º 17
0
int main()
{
  int i=0,
      cport_nr=17,        /* /dev/ttyS0 (COM1 on windows) */
      bdrate=9600;       /* 9600 baud */

  char mode[]={'8','N','1',0},
       str[2][512];


  strcpy(str[0], "The quick brown fox jumped over the lazy grey dog.\n");

  strcpy(str[1], "Happy serial programming!\n");


  if(RS232_OpenComport(cport_nr, bdrate, mode))
  {
    printf("Can not open comport\n");

    return(0);
  }

  while(1)
  {
    RS232_cputs(cport_nr, str[i]);

    printf("sent: %s\n", str[i]);


    usleep(1000000);  /* sleep for 1 Second */


    i++;

    i %= 2;
  }

  return(0);
}
Exemplo n.º 18
0
bool Hardware::Open()
{
#ifndef OS_UBUNTU
	system("echo 18 >/sys/class/gpio/export"); //reset
	system("echo 19 >/sys/class/gpio/export"); //isp0
	system("echo 20 >/sys/class/gpio/export"); //isp1
	system("echo out >/sys/class/gpio/gpio18/direction");
	system("echo out >/sys/class/gpio/gpio19/direction");
	system("echo out >/sys/class/gpio/gpio20/direction");
	system("echo 0 >/sys/class/gpio/gpio19/value");
	system("echo 0 >/sys/class/gpio/gpio20/value");
	system("echo 1 >/sys/class/gpio/gpio18/value");
	system("sleep 1");
	system("echo 0 >/sys/class/gpio/gpio18/value");
	system("sleep 1");
#endif
	
#ifdef USESERIAL
	//board->cache_length = 0;
	return (RS232_OpenComport(SERIAL_PORT, SERIAL_BAND)==0);
#endif
}
Exemplo n.º 19
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);
}
Exemplo n.º 20
0
void test_RS232_OpenComport(void){
	RS232_OpenComport(COMPORT,baudrate);
	RS232_SendByte(COMPORT,0x85);
	RS232_CloseComport(COMPORT);
}
Exemplo n.º 21
0
int openComport(byte serial_port, unsigned long baud_rate){
    if(RS232_OpenComport(serial_port, baud_rate))
    {
        printf("Can not open comport\n");
    }
}
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);
}
Exemplo n.º 23
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;
}
int main(int argc, char* argv[])
{
	int cport_nr=34,        /* /dev/cuaU0 (first serial on FreeBSD) */
	    bdrate=115200,        /* 115200 baud */
	    tvToSelect=-1,
	    inputToSelect=-1;

	char mode[]={'8','N','1',0};
	char commands[32][13]={
        {0xA5, 0x5B, 0x02, 0x03, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF9}, // Switch Input 1, to Output 1
        {0xA5, 0x5B, 0x02, 0x03, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8}, // Switch Input 2, to Output 1
        {0xA5, 0x5B, 0x02, 0x03, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF7}, // Switch Input 3, to Output 1
        {0xA5, 0x5B, 0x02, 0x03, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF6}, // Switch Input 4, to Output 1

        {0xA5, 0x5B, 0x02, 0x03, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8}, // Switch Input 1, to Output 2
        {0xA5, 0x5B, 0x02, 0x03, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF7}, // Switch Input 2, to Output 2
        {0xA5, 0x5B, 0x02, 0x03, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF6}, // Switch Input 3, to Output 2
        {0xA5, 0x5B, 0x02, 0x03, 0x04, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF5}, // Switch Input 4, to Output 2

        {0xA5, 0x5B, 0x02, 0x03, 0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF7}, // Switch Input 1, to Output 3
        {0xA5, 0x5B, 0x02, 0x03, 0x02, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF6}, // Switch Input 2, to Output 3
        {0xA5, 0x5B, 0x02, 0x03, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF5}, // Switch Input 3, to Output 3
        {0xA5, 0x5B, 0x02, 0x03, 0x04, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF4}, // Switch Input 4, to Output 3

        {0xA5, 0x5B, 0x02, 0x03, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF6}, // Switch Input 1, to Output 4
        {0xA5, 0x5B, 0x02, 0x03, 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF5}, // Switch Input 2, to Output 4
        {0xA5, 0x5B, 0x02, 0x03, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF4}, // Switch Input 3, to Output 4
        {0xA5, 0x5B, 0x02, 0x03, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3}, // Switch Input 4, to Output 4

        {0xA5, 0x5B, 0x02, 0x03, 0x01, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF9}, // Switch Input 1, to Output 5
        {0xA5, 0x5B, 0x02, 0x03, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8}, // Switch Input 2, to Output 5
        {0xA5, 0x5B, 0x02, 0x03, 0x03, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF7}, // Switch Input 3, to Output 5
        {0xA5, 0x5B, 0x02, 0x03, 0x04, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF6}, // Switch Input 4, to Output 5

        {0xA5, 0x5B, 0x02, 0x03, 0x01, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8}, // Switch Input 1, to Output 6
        {0xA5, 0x5B, 0x02, 0x03, 0x02, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF7}, // Switch Input 2, to Output 6
        {0xA5, 0x5B, 0x02, 0x03, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF6}, // Switch Input 3, to Output 6
        {0xA5, 0x5B, 0x02, 0x03, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF5}, // Switch Input 4, to Output 6

        {0xA5, 0x5B, 0x02, 0x03, 0x01, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF7}, // Switch Input 1, to Output 7
        {0xA5, 0x5B, 0x02, 0x03, 0x02, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF6}, // Switch Input 2, to Output 7
        {0xA5, 0x5B, 0x02, 0x03, 0x03, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF5}, // Switch Input 3, to Output 7
        {0xA5, 0x5B, 0x02, 0x03, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF4}, // Switch Input 4, to Output 7

        {0xA5, 0x5B, 0x02, 0x03, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF6}, // Switch Input 1, to Output 8
        {0xA5, 0x5B, 0x02, 0x03, 0x02, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF5}, // Switch Input 2, to Output 8
        {0xA5, 0x5B, 0x02, 0x03, 0x03, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF4}, // Switch Input 3, to Output 8
        {0xA5, 0x5B, 0x02, 0x03, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3}  // Switch Input 4, to Output 8

	};

	if(argc <= 1){
		printf("Requires at least one input.\n");
		return(1);
	}

	if(argc == 2){
		inputToSelect = atoi(argv[1]) - 1;
	}

	if(argc >= 3){
		tvToSelect    = atoi(argv[1]) - 1;
		inputToSelect = atoi(argv[2]) - 1;
		if(tvToSelect < 0 || tvToSelect > 3){
			printf("Only TV values of 1-4 are supported.\n");
			return(1);
		}
	}

	if(inputToSelect < 0 || inputToSelect > 3){
		printf("Only input values of 1-4 are supported.\n");
		return(1);
	}

	if(RS232_OpenComport(cport_nr, bdrate, mode)){
		printf("Cannot open the serial port.\n");
		return(0);
	}

	if(tvToSelect >= 0)
		changeInput(cport_nr, commands, inputToSelect, tvToSelect);
	else
		changeAllToInput(cport_nr, commands, inputToSelect);

#ifdef _WIN32
    Sleep(1000);
#else
    usleep(500000);  /* sleep for 1/2 Second */
#endif

  return(0);
}
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);
            }
        }
    }
}
Exemplo n.º 26
0
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);
}
Exemplo n.º 27
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);
}
Exemplo n.º 28
0
void test_RS232_OpenComport(void) {
  RS232_OpenComport(2, 9600);
  RS232_SendByte(2, 0x6a);
  RS232_CloseComport(COMPORT);
}
Exemplo n.º 29
0
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;
}
Exemplo n.º 30
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);
}