Exemplo n.º 1
0
int setupSerial(const char *port, int baudrate) {
	int fd = -1;
	DBG("%s\n", port);
	fd = serialport_init(port, baudrate);
	if( fd==-1 ) {
		ERR("couldn't open port %s @ %d bauds\n", port, baudrate);
		return -1;
	}
	DBG("opened port %s @ %d bps\n",port, baudrate);

	serialport_flush(fd);
	return fd;
};
Exemplo n.º 2
0
//-----------------------------------------------------------------------------
// This function is called by the main OpenPLC routine when it is initializing.
// Hardware initialization procedures should be here.
//-----------------------------------------------------------------------------
void initializeHardware()
{
	char **portsList;
	portsList = new char *[30];
	for(int i = 0; i < 30; i++)
	{
    	portsList[i] = new char[1000];
    	memset(portsList[i],0,sizeof(portsList[i]));
	}

#ifdef __linux__
	if (verifySerialPortsAvailable())
	{
		getSerialPorts(portsList);
		int portId = findCorrectPort(portsList);

		if (portId != -1)
		{
			serial_fd = serialport_init(portsList[portId], 115200);
			sleep_ms(500);
			pthread_t thread;
			pthread_create(&thread, NULL, exchangeData, NULL);
		}
	}
#else
	getSerialPorts_w32(portsList);
	int portId = findCorrectPort(portsList);
	
	if (portId != -1)
	{
		serial_fd = serialport_init(portsList[portId], 115200);
		sleep_ms(500);
		pthread_t thread;
		pthread_create(&thread, NULL, exchangeData, NULL);
	}
#endif

}
Exemplo n.º 3
0
int open_port(void){
    if( fd!=-1 ) {
        serialport_close(fd);
        printf("closed port %s\n",serialport);
    }
    strcpy(serialport,optarg);
    fd = serialport_init(optarg, baudrate);
    if( fd==-1 ){
        printf("couldn't open port");
        return -1;
    } 
    printf("opened port %s\n",serialport);
    serialport_flush(fd);
    
    return 0;
}
int main(int argc, char** argv)
{
  /********************
   * Set up ROS node
   */
  ros::init(argc, argv, "talker");
  ros::NodeHandle n;
  ros::Publisher tableDir_pub = n.advertise<alfred_msg::FSRDirection>("table_direction", 100);
  ros::Publisher tableAngle_pub = n.advertise<alfred_msg::TableAngleStatus>("TableAngleStatus", 100);

  // Set up serial connection
  char buf[20];
  char* modemDevice =  "/dev/ttyACM0";
  if( argc > 1 )
    modemDevice = argv[1];
  int fd = serialport_init(modemDevice, BAUDRATE);  
  if(fd < 0)  return -1;
  usleep(3000 * 1000 ); 
   
  printf("Connected to Arduino, starting loop\n");
  ros::Rate rate(50);
  while(ros::ok())
  {
      // Get the X coordinate
      serialport_write(fd, "x\0");
      serialport_read_until(fd, buf, ':');
      directionMessage.x = atof(buf);
      //printf("Received X:%f\n", directionMessage.x); 
      
      // Get the Y coordinate
      serialport_write(fd, "y");
      serialport_read_until(fd, buf, ':');
      directionMessage.y = atof(buf);
      //printf("Received Y:%f\n", directionMessage.y); 

      // Get the follow indicator
      serialport_write(fd, "f");
      serialport_read_until(fd, buf, ':');
      directionMessage.followPressed = atof(buf) == 1;
      //printf("Received F:%s\n", directionMessage.followPressed ? "true":"false" );

      tableDir_pub.publish(directionMessage);
      rate.sleep();
  }
}
//
// OpenSerialPort()
//  Open the serial port on COM3 to the Arduino.
//
int OpenSerialPort (void)
{
	if( serialFD != -1 )
		return 1;

	// Set up the serial port
	serialFD = serialport_init( "COM3", 9600 );
	if( serialFD == -1 ) {
		if( serialOpenRetry )
			; // TODO:  Start the retry timer

		return 0;
	}

	// Send an initialization command
	SendSerialData( 0, 0.5f );
	return 1;
}
Exemplo n.º 6
0
Arquivo: lold.c Projeto: apirogov/lold
//render a frame to real device or stdout
void render_frame(const char *dev, const char *frame) {
  if (dev==NULL) { //dummy
    dummy_output(frame);
    return;
  }

  //open port if no open port
  if (s_port == -1) {
    s_port = serialport_init(dev, 115200);
    if (s_port == -1) {
      fprintf(stderr, "Could not open serial device file! Aborting.\n");
      exit(EXIT_FAILURE);
    }
  }

  //write frame
  serialport_write(s_port, frame);
  serialport_write(s_port, "\n");
}
Exemplo n.º 7
0
int main(int argc, char *argv[]) 
{

	int baudrate = B9600;  // default
	int fd;
	char cmd = 0;
	char cmdv[3] = "a";
	fd = serialport_init(ARD_LOC, baudrate);
	
	if((argv[1][0]) == 'p'){
		while(1){
			printf("Water Turret$: ");
			scanf("%c",&cmd);
			// printf("1\n");
			cmdv[0] = (char)cmd;
			// printf("2\n");
			if(cmd == 'x'){
				// printf("3\n");
				return 0;
			}
			// printf("4\n");
			serialport_write(fd, cmdv);
		}
	}
	
	serialport_write(fd, "a");
	serialport_write(fd, "w");
	serialport_write(fd, "a");
	serialport_write(fd, "w");
	
	serialport_write(fd, "d");
	serialport_write(fd, "d");
	
	serialport_write(fd, "s");
	
	serialport_write(fd, "s");
	
	


} 
Exemplo n.º 8
0
int main(int argc, char *argv[])
{
    if(argc != 2) {
        printf("%s: Usage\n", argv[0]);
        printf(" lightcontrol [serial port path]\n");
        return -1;
    }

    int fd = serialport_init(argv[1], 9600);
    if (fd == -1) {
        printf("%s: Fatal error", argv[0]);
        return -1;
    }

    bool cont = true;
    while (cont) {
        char *line = readline("lightcontrol> ");
        char *cmd = strsep(&line, " ");
        if (strcmp(cmd, "quit") == 0) {
            cont = false;
        } else if (strcmp(cmd, "color")) {
            int lightid = atoi(strsep(&line, " "));
            int r = atoi(strsep(&line, " "));
            int g = atoi(strsep(&line, " "));
            int b = atoi(strsep(&line, " "));
            if(lightid < 0 || r < 0 || g < 0 || b < 0) {
                printf("Error: Invalid command arguments");
            } else if (r > 255 || g > 255 || b > 255) {
                printf("Error: Color values must be in range 0-255");
            } else {
                serial_set_color(fd, lightid, r, g, b);
            }
        } else {
            printf("Invalid command %s\n", cmd);
        }
    }
    return 0;
}
Exemplo n.º 9
0
//-----------------------------------------------------------------------------
// Test if *portName is the correct serial port
//-----------------------------------------------------------------------------
bool testPort(char *portName)
{
	printf("Trying to open %s\n", portName);
	serial_fd = serialport_init(portName, 115200);
	sleep_ms(500);
	if (serial_fd < 0) return 0;
	
	for (int i = 0; i < 5; i++) //try at least 5 times
	{
		sendPacket();
		sleep_ms(400);
		if (receivePacket())
		{
			close(serial_fd);
			return 1;
		}
		sleep_ms(30);
	}
	
	printf("The port didn't respond properly\n");
	close(serial_fd);
	return 0;
}
Exemplo n.º 10
0
int main(int argc, char* argv[]) {
  if (argc == 1) {
    printf("You have to pass the name of a serial port.\n");
    return -1;
  }
  int baudrate = B9600;
  int arduino = serialport_init(argv[1], baudrate); 
  if (arduino == -1) {
    printf("Could not open serial port %s.\n", argv[1]);
    return -1;
  }
  sleep(2);
  char line[MAX_LINE];
  while (1) {
    int rc = serialport_write(arduino, "a0\n"); 
    if (rc == -1) {
      printf("Could not write to serial port.\n");
    } else {
      serialport_read_until(arduino, line, '\n'); 
      printf("%s", line);
    }
  }
  return 0;
}
Exemplo n.º 11
0
int init_serial(void)
{
    serial_fd = serialport_init("/dev/ttyACM0", BAUD);

    return 0;
}
Exemplo n.º 12
0
int main(int argc, char *argv[])
{
    int fd = 0;
    FILE * tmpfile = stdin;
    char serialport[256];
    int baudrate = B9600;  /* default */
    int rc;
	unsigned char press;
	bool cxn_established = false;

    if (argc == 1)
	{
        usage();
        return EXIT_SUCCESS;
    }

    /* parse options */
    int option_index = 0, opt;
    static struct option loptions[] = {
        {"help",       no_argument,       0, 'h'},
        {"port",       required_argument, 0, 'p'},
        {"baud",       required_argument, 0, 'b'},
        {"file",       required_argument, 0, 'f'}
    };

	while (1)
	{
		opt = getopt_long (argc, argv, "hp:b:f:",
						   loptions, &option_index);

		if (opt == -1) break;

		switch (opt)
		{
			case '0': break;
			case 'h':
				usage();
				break;
			case 'b':
				if (cxn_established)
				{
					fputs("Error: baudrate must come before port number", stderr);
					return EXIT_FAILURE;
				}
				baudrate = strtol(optarg,NULL,10);
				break;
			case 'p':
				strcpy(serialport,optarg);
				fd = serialport_init(optarg, baudrate);
				if (fd == -1) return -1;
				cxn_established = true;
				break;
            case 'f':
                tmpfile = fopen(optarg, "r");
                if (tmpfile == NULL)
                {
                    perror(argv[0]);
                    return EXIT_FAILURE;
                }
                break;
		}
	}

	if (!cxn_established)
	{
		fputs("Error: port number is a required argument", stderr);
		return EXIT_FAILURE;
	}

	if (tmpfile == stdin)
	{
		puts("Press space to exit. l/r to rotate, n to stop, f to fire.");
	}

	while ((press = getc(tmpfile)) != ' ')
	{
		switch (press)
		{
			case 'l':
				puts("Sent a 2");
                                rc = serialport_writebyte(fd, (uint8_t)2);
				break;
			case 'n':
				puts("Sent a 0");
				rc = serialport_writebyte(fd, (uint8_t)0);
				break;
			case 'r':
				puts("Sent a 1");
				rc = serialport_writebyte(fd, (uint8_t)1);
				break;
                        case 'f':
                                puts("Sent a 3 (not yet implemented)");
                                rc = serialport_writebyte(fd, (uint8_t)3);
                                break;
			case 10: /* newline */
				break;
			case 255: /* eof */
				break;
			default:
				printf("Unrecognized: %i\n", (int)press);
				break;
		}
	}

    return EXIT_SUCCESS;
} /* end main */
Exemplo n.º 13
0
void main(int argc, char* argv[])
{

 int            modem_fd;
 int              serialport_init_res = -1;
 struct termios   oldtio;
 char message[160]; 
 char command[255];
 char buf1[256];
 int res=-1;

   //open the modem device
  modem_fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY );  
    if (modem_fd <0) 
    {
       printf("Can't open Modem Device\n"); 
       return ; 
    }
  fcntl(modem_fd, F_SETFL, FNDELAY);
 
  tcgetattr(modem_fd,&oldtio);                                   /* save current serial port settings */
    
  serialport_init_res = serialport_init(&modem_fd);               /* initialize the serial port open above */
    
  if(serialport_init_res == 0)
    {
       printf("GSM Board connected to the Serial Port\n");
    }   
  else
    {
          printf("gsm.c: failed to initialize the serial port\n");
          return;
    }  

  /* You are ready to send message :P */
  /* sample message */

if (argc != 3){
	printf ("Invalid no. of arguments\n");
	return ;
}
   strcpy(message,argv[2]);
	strcpy(command, "AT+CMGS=\"+91");
        strcat(command,argv[1]);
	strcat(command,"\"\r\n");
	printf("Command=%s\n",command);
      write(modem_fd,command,strlen(command));
      write(modem_fd,message,strlen(message));
      write(modem_fd,"\x1A",1);           /*x1A means ctrl+Z */
     
  /* message has been submitted, check the response of the modem */
    while(1)
    {
         res = read(modem_fd,buf1,255);
         if(res==-1)
            {
              usleep(10);
              continue;
            } 
         if(res==1)
             continue;   
         
         buf1[res-1]='\0';             /* set end of string, so we can use printf */
         if (strncmp(buf1,"OK",2)== 0 ||strncmp(buf1,"ERROR",5)==0)
             break;
    }

}
int main(int argc, char *argv[])
{
    int fd = 0;
    char serialport[256];
    int baudrate = B9600;  // default
    char buf[256];
    int rc,n;
    
    if (argc==1) {
        usage();
        exit(EXIT_SUCCESS);
    }
    
    /* parse options */
    int option_index = 0, opt;
    static struct option loptions[] = {
        {"help",       no_argument,       0, 'h'},
        {"port",       required_argument, 0, 'p'},
        {"baud",       required_argument, 0, 'b'},
        {"send",       required_argument, 0, 's'},
        {"receive",    no_argument,       0, 'r'},
        {"num",        required_argument, 0, 'n'},
        {"delay",      required_argument, 0, 'd'}
    };
    
    while(1) {
        opt = getopt_long (argc, argv, "hp:b:s:rn:d:",
                           loptions, &option_index);
        if (opt==-1) break;
        switch (opt) {
            case '0': break;
            case 'd':
                n = strtol(optarg,NULL,10);
                usleep(n * 1000 ); // sleep milliseconds
                break;
            case 'h':
                usage();
                break;
            case 'b':
                baudrate = strtol(optarg,NULL,10);
                break;
            case 'p':
                strcpy(serialport,optarg);
                fd = serialport_init(optarg, baudrate);
                if(fd==-1) return -1;
                break;
            case 'n':
                n = strtol(optarg, NULL, 10); // convert string to number
                rc = serialport_writebyte(fd, (uint8_t)n);
                if(rc==-1) return -1;
                break;
            case 's':
                strcpy(buf,optarg);
                rc = serialport_write(fd, buf);
                if(rc==-1) return -1;
                break;
            case 'r':
                serialport_read_until(fd, buf, '\n');
                printf("read: %s\n",buf);
                break;
        }
    }
    
    exit(EXIT_SUCCESS);
} // end main
Exemplo n.º 15
0
int main(int argc, char *argv[])
{
	uint8_t byte[100];
	uint8_t message[256];
	
	int fd = serialport_init();

	//write(fd, "X", 1);

	int state = 0; // Wait for a recognized pattern
	int msgOffset = 0;
	int needed = 0;
	int index;		
	
	int logFd = open("vistalog.bin", (O_CREAT | O_RDWR), (S_IRUSR | S_IWUSR));
	//int txtFd = open("vistalog.txt", (O_CREAT | O_RDWR), (S_IRUSR | S_IWUSR));
	
	while(1)
	{
		ssize_t size = read(fd, byte, 100);
		
		if (size < 0)
			printf("Read error\n");
		if (size == 0)
			continue;
		

		//printf("%zu:", size);
		int rc = write(logFd, byte, size);
		if (rc == -1)
			printf("Log write failure\n");
		
#if 0
		int rc = write(logFd, byte, size);
		if (rc == -1)
			printf("Log write failure\n");
#endif
		
#if 1
		struct timeval time;
		gettimeofday(&time, NULL);
		printf("[%ld.%06ld]", time.tv_sec, time.tv_usec);
		dump_message(byte, size);
		printf("\n");
#else
		for (index = 0; index < size; index++)
		{
			//printf(" %02X", byte[index]);

			switch (state)
			{
			case 0:  // No message
				if (byte[index] == 0xF7)
				{
					// Keypad message
					state = 1;  // Read message
					needed = 44;
					//printf("state = Read keypad message header (%d)\n", needed);
					message[0] = 0xF7;
					msgOffset = 1;
				}
				else if (byte[index] == 0x9E)
				{
					// 9E message, whatever that is
					state = 1;  // Read message
					needed = 4;
					//printf("state = Read 9E message (%d)\n", needed);
					message[0] = 0x9E;
					msgOffset = 1;
				}
				else if (byte[index] == 0xF6)
				{
					// Appears to be a keypress message but without any indication of what key was pressed, maybe byte 1 is keypad address
					state = 1;  // Read message
					needed = 3;
					message[0] = 0xF6;
					msgOffset = 1;
				}
				else if (byte[index] == 0x00)
				{
					// Keep looking
				}
				else
				{
					printf("Unknown message type (0x%02X)\n", byte[index]);					
				}
				break;
				
			case 1:
				message[msgOffset] = byte[index];
				msgOffset++;
				needed--;
				
				if (needed == 0)
				{
					//printf("Read needed bytes...\n");
					// Entire message received
					struct timeval time;
					gettimeofday(&time, NULL);
#if 0
					time_t ltime; /* calendar time */
					ltime=time(NULL); /* get current cal time */
					char timeStr[256];
					strftime(timeStr, sizeof(timeStr), "", localtime(&ltime)));
#endif
					printf("[%ld.%06ld]", time.tv_sec, time.tv_usec);

					// Handle message
					if (message[0] == 0xF7)
					{
						// keypad message
						printf("Keypad : ");
						dump_message(message, 12);
						message[msgOffset - 1] = 0x00;
						message[12] &= 0x7F;  // The upper bit has some unknown meaning, masked for display
						printf("'%s'\n", &(message[12]));
						write_html((char *)&(message[12]));
					}
					else if (message[0] == 0x9E)
					{
						printf("9E : ");
						dump_message(message, msgOffset);
						printf("\n");
					}
					else if (message[0] == 0xF6)
					{
						printf("Keypress : ");
						dump_message(message, msgOffset);
						printf("\n");
					}
					else
					{
						printf("Trying to process unknown message type (0x%02X)\n", message[0]);
					}
					
					state = 0; // Wait for known message pattern
					msgOffset = 0;
					needed = 0;
				}
			}
			
			//printf("\n");
		}
#endif
	}

	return EXIT_SUCCESS;
}
Exemplo n.º 16
0
int main(int argc, char** argv){

   /*******************
    *  Base Drive Variables
    *
    * LOOP_RATE         defines how fast we send orders to the arduino
    * ORDER_TIMEOUT     is the maximum amount of time between recieving orders
    *                   before we shut the motors off
    *
    * BAUDRATE          baudrate to arduino
    * SERIAL_DEV        the defauly dev file pointing to the arduino
    * READ_CHAR_TIMEOUT the timeout to wait for the next character in a
    *                   message, in us
    * SERIAL_RESPONSE_TIMEOUT The timeout to wait for a response to our
    *                         query, in us
    */
   double LOOP_RATE = 10.0;
   double ORDER_TIMEOUT = 0.25;

   int BAUDRATE = B115200;
   char* SERIAL_DEV = "/dev/ttyUSB0";
   int READ_CHAR_TIMEOUT = 30;
   int SERIAL_RESPONSE_TIMEOUT = 100;
   char START_CHAR = '`';

   /********************
    * Set up ROS node
    */
   ros::init(argc, argv, "TableMotorToSerial");
   ros::NodeHandle n;

   ROS_INFO( "Starting Subscriber" );
   ros::Subscriber sub = n.subscribe("DriveTable", 2, callbackTableMotorToSerial ); 

   ros::Publisher pub = n.advertise<alfred_msg::TableEncoders>("TableEncoders", 2);

   /********************
    * Setup loop variables and start serial
    */
   char* serialDevice = SERIAL_DEV;
   if( argc > 1 )
      serialDevice = argv[1];

   int fd = serialport_init(serialDevice, BAUDRATE);
   if(fd < 0){
      ROS_ERROR( "Could not open serial device \'%s\'\n", serialDevice); 
      return -1;
   }
   usleep( 3000 * 1000 );
   
   ros::Rate rate(LOOP_RATE);
   int maxNumLoopsWithoutOrder = (int)( ORDER_TIMEOUT * LOOP_RATE );
   int numLoopsWithoutOrder(-1);
    
   
   while (n.ok()) {

      // If we haven't yet started
      if( numLoopsWithoutOrder == -1){
         tableOrder_serialArduino1 = 0.0;
         tableOrder_serialArduino2 = 0.0;
         tableOrder_serialArduino3 = 0.0;
         tableOrder_serialArduino4 = 0.0;
      }
      // Safety Check 1 : time without orders
      else if( numLoopsWithoutOrder >= maxNumLoopsWithoutOrder ){

         tableOrder_serialArduino1 = 0.0;
         tableOrder_serialArduino2 = 0.0;
         tableOrder_serialArduino3 = 0.0;
         tableOrder_serialArduino4 = 0.0;
         ROS_ERROR( "Base Motor to Serial hasn't received a new motor order in %f mS!", 1000 * ORDER_TIMEOUT );
      }
      // Safety check passed, send 
    
      if( numLoopsWithoutOrder >= 0 ) 
         numLoopsWithoutOrder++;
      if( receivedOrder_serialArduino == true ){
         numLoopsWithoutOrder = 0;
         receivedOrder_serialArduino = false;
      }

      ROS_INFO( "Sending output to table: [%f, %f, %f, %f]",
                  tableOrder_serialArduino1,
                  tableOrder_serialArduino2,
                  tableOrder_serialArduino3,
                  tableOrder_serialArduino4);
 
      //write
      std::stringstream ss;
      ss << "`" 
         << tableOrder_serialArduino1 << ";"
         << tableOrder_serialArduino2 << ";"
         << tableOrder_serialArduino3 << ";"
         << tableOrder_serialArduino4 << ";\0";
      std::string msg = ss.str();
   
      int isok = serialport_write(fd, msg.c_str() );

      // now read, and wait for the arduino to reply with the encoder values
      int encoders[4];
      char buf[10];

      // First, wait for a response      
      if( serialport_read_until(fd, buf, START_CHAR, SERIAL_RESPONSE_TIMEOUT) <= 0)
      {
         ROS_ERROR("ERROR: Timeout on serial response message start!");
         for( int i(0); i < 4; i++ )
            encoders[i]=-1;
      }
      else{
         for( int i(0); i < 4; i++ ){
            isok = serialport_read_until(fd, buf, ';',  READ_CHAR_TIMEOUT );
            if( isok <= 0 ){
               ROS_ERROR("ERROR: Timeout reading message");
               break;
            }
            encoders[i] = std::atoi(buf);
         }
         if( isok <= 0 )
            for( int i(0); i < 4; i++ )
               encoders[i]=-1;
      }

      ROS_INFO( "Publishing Encoder Vals: [%d, %d, %d, %d]",
                  encoders[0],
                  encoders[1],
                  encoders[2],
                  encoders[3]);

      alfred_msg::TableEncoders encTopic;
      encTopic.enc1 = encoders[0];
      encTopic.enc2 = encoders[1];
      encTopic.enc3 = encoders[2];
      encTopic.enc4 = encoders[3];

      pub.publish(encTopic);
   
      ROS_INFO("\n");
      rate.sleep();
      ros::spinOnce();
   }

   serialport_close(fd);
   return 0;
}
Exemplo n.º 17
0
int main(int argc, char *argv[]) 
{
    struct mg_context *ctx;

    int baudrate = 9600;  // default
    char httpport[16] = "8080"; 
    char serialport[256];
    
    /* parse options */
    int option_index = 0, opt;
    static struct option loptions[] = {
        {"help",       no_argument,       0, 'h'},
        {"httpport",   required_argument, 0, 'P'},
        {"serialport", required_argument, 0, 'p'},
        {"baud",       required_argument, 0, 'b'},
        {"quiet",      no_argument,       0, 'q'},
        {NULL,         0,                 0, 0}
    };
  

    while(1) {
        opt = getopt_long (argc, argv, "hP:p:b:q",
                           loptions, &option_index);
        if (opt==-1) break;
        switch (opt) {
        case '0': break;
        case 'h':
            usage();
            break;
        case 'b':
            baudrate = strtol(optarg,NULL,10);
            break;
        case 'p':
            strcpy(serialport,optarg);
            fd = serialport_init(optarg, baudrate);
            if( fd==-1 ) error("couldn't open port");
            serialport_flush(fd);
            break;
        case 'P':
            strcpy(httpport,optarg);
            break;
        }
    }
    
    char *options[] = {"listening_ports", httpport, NULL};

  
    //fd = serialport_init("/dev/tty.usbserial-A800f8ib", 19200);
    fd = serialport_init( serialport, baudrate );
    if( fd==-1 ) fprintf(stderr, "couldn't open port");
    printf("opened serialport %s @ %d bps\n", serialport, baudrate);

    ctx = mg_start(&callback, NULL, (const char**) options);
    printf("arduino-serial-server: running on port %s\n",
           mg_get_option(ctx, "listening_ports"));
    getchar();  // Wait until user hits "enter"
    
    mg_stop(ctx);
    
    return 0;
}
Exemplo n.º 18
0
int main(int argc, char *argv[])
{
    /*accelerometer related declarations*/
    const int buf_max = 2048;

    int fd = -1;
    char serialport[buf_max];
    int baudrate = 9600;  // default
    char quiet=0;
    char eolchar = ' ';
    int timeout = 5000;
    char buf[buf_max];
    int rc,n,p;
    float xDat[103],yDat[103],zDat[103];
    float sumX=0,sumY=0,sumZ=0;
    float sum1=0,sum2=0,sum3=0;
    float stdX=0,stdY=0,stdZ=0,avgX=0,avgY=0,avgZ=0,varX=0,varY=0,varZ=0,recal=0;
    int total=1;
    int calibrate=0;
    /*---------------------------------*/

//    char stdbuffer[10];
    /*socket related declarations*/    
    int sockfd, portno, n2;
    struct sockaddr_in serv_addr;
    struct hostent *server;

    char buffer[256];
    int sendMessage=1;
   /*----------------------------*/

    if (argc==1) {
        usage();
    }

    /* parse options */
    int option_index = 0, opt;
    static struct option loptions[] = {
        {"help",       no_argument,       0, 'h'},
        {"port",       required_argument, 0, 'p'},
        {"baud",       required_argument, 0, 'b'},
        {"send",       required_argument, 0, 's'},
        {"setup",      no_argument,       0, 'S'},
        {"receive",    no_argument,       0, 'r'},
        {"flush",      no_argument,       0, 'F'},
        {"num",        required_argument, 0, 'n'},
        {"delay",      required_argument, 0, 'd'},
        {"eolchar",    required_argument, 0, 'e'},
        {"timeout",    required_argument, 0, 't'},
        {"quiet",      no_argument,       0, 'q'},
        {NULL,         0,                 0, 0}
    };

    while(1) {
        opt = getopt_long (argc, argv, "hp:b:s:rSFn:d:qe:t:",
                           loptions, &option_index);
        if (opt==-1) break;
        switch (opt) {
        case '0': break;
        case 'q':
            quiet = 1;
            break;
        case 'e':
            eolchar = optarg[0];
            if(!quiet) printf("eolchar set to '%c'\n",eolchar);
            break;
        case 't':
            timeout = strtol(optarg,NULL,10);
            if( !quiet ) printf("timeout set to %d millisecs\n",timeout);
            break;
        case 'd':
            n = strtol(optarg,NULL,10);
            if( !quiet ) printf("sleep %d millisecs\n",n);
            usleep(n * 1000 ); // sleep milliseconds
            break;
        case 'h':
            usage();
            break;
        case 'b':
            baudrate = strtol(optarg,NULL,10);
            break;
        case 'p':
            if( fd!=-1 ) {
                serialport_close(fd);
                if(!quiet) printf("closed port %s\n",serialport);
            }
            strcpy(serialport,optarg);
            fd = serialport_init(optarg, baudrate);
            if( fd==-1 ) error("couldn't open port");
            if(!quiet) printf("opened port %s\n",serialport);
            serialport_flush(fd);
            break;
        case 'n':
            if( fd == -1 ) error("serial port not opened");
            n = strtol(optarg, NULL, 10); // convert string to number
            rc = serialport_writebyte(fd, (uint8_t)n);
            if(rc==-1) error("error writing");
            break;
        case 'S':
	     portno = 52002;//atoi(argv[2]);
             /* Create a socket point*/ 
             sockfd = socket(AF_INET, SOCK_STREAM, 0);
             if (sockfd < 0) 
             {
                perror("ERROR opening socket");
                exit(1);
             }
             server = gethostbyname("192.168.2.103");//gethostbyname(argv[1]);
             if (server == NULL) {
                fprintf(stderr,"ERROR, no such host\n");
                exit(0);
             }

             bzero((char *) &serv_addr, sizeof(serv_addr));
             serv_addr.sin_family = AF_INET;
             bcopy((char *)server->h_addr, 
                   (char *)&serv_addr.sin_addr.s_addr,
                         server->h_length);
             serv_addr.sin_port = htons(portno);

             /* Now connect to the server */
             if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0) 
             {
                  perror("ERROR connecting");
                  exit(1);
              }
              while(1){
              int r;
              int a1, a2, a3;
	      char a4[sizeof(float)*3+3];
              memset (buf, 0, 256);
              r = serialport_read_until(fd, buf);
              //fprintf (stderr, "VAL: %s -->", buf);
              if (r >= 0)
              {
               sscanf (buf, "A1:%d\tA2:%d\tA3:%d", &a1, &a2, &a3);
              // fprintf (stderr, "(%d)(%d)(%d)\n", a1, a2, a3);
               if(calibrate==0){
                  sumX= sumX + a1; sumY= sumY + a2; sumZ= sumZ + a3;
                  xDat[total]=a1;yDat[total]=a2;zDat[total]=a3;
                  total++;
              if (total==100){ 
		  calibrate=1;
                  avgX = sumX/(float)total; avgY = sumY/(float)total; avgZ = sumZ/(float)total;
                  for(p = 1; p<total;p++){
                  sum1 = sum1 + pow((xDat[p]-avgX),2); sum2 = sum2 + pow((yDat[p]-avgY),2); sum3 = sum3 + pow((zDat[p]-avgZ),2);
                  }
		   varX= sum1/(float)total; varY=sum2/(float)total; varZ=sum3/(float)total;
                   stdX=sqrt(varX); stdY=sqrt(varY); stdZ=sqrt(varZ);
               }
	       }
               if(calibrate==1){snprintf(a4, sizeof a4*7, "%f %f %f %f %f %f %f %f %f", (float)a1, (float)a2,(float)a3,avgX,avgY,avgZ,stdX,stdY,stdZ);}
               while(sendMessage==1&&calibrate==1){
                /* Send message to the server*/ 
                //printf("here");
		n2 = write(sockfd,a4,strlen(a4));
                if (n2 < 0) 
                {
                        perror("ERROR writing to socket");
                        exit(1);
                }
                /* Now read server response */
                bzero(buffer,256);
                n2 = read(sockfd,buffer,255);
                    if (n2 < 0) 
                {
                        perror("ERROR reading from socket");
                        exit(1);
                }
//                printf("Received message: %s\n",buffer);
                 sendMessage=0;
                }
             sendMessage=1; 
	     }
              sendMessage=1;
              fflush (0);
              //sleep (5);
           }    
           break;
        case 's':
            if( fd == -1 ) error("serial port not opened");

            sprintf(buf, (opt=='S' ? "%s\n" : "%s"), optarg);

            if( !quiet ) printf("send string:%s\n", buf);
            rc = serialport_write(fd, buf);
            if(rc==-1) error("error writing");
            break;
        case 'r':
	  while (1)
	    {
	      int r;
	      int a1, a2, a3;

	      memset (buf, 0, 256);
	      r = serialport_read_until(fd, buf);
              fprintf (stderr, "VAL: %s -->", buf);
//              printf("%d",r);
	      if (r >= 0)
		{
		 sscanf (buf, "A1:%d\tA2:%d\tA3:%d", &a1, &a2, &a3);
		 fprintf (stderr, "(%d)(%d)(%d)\n", a1, a2, a3);
                 //fgets(stdbuffer,10,stdin);
	         //if(strcmp(stdbuffer,"getData")==0){
		 // printf("%d",a1);
                 // printf("%d",a2);
                 // printf("%d",a3);}
                //}
        /*       while(sendMessage==1){
    		/* Send message to the server 
    		n2 = write(sockfd,"measure",strlen("measure"));
    		if (n2 < 0) 
    		{
         		perror("ERROR writing to socket");
         		exit(1);
    		}
    		/* Now read server response 
    		bzero(buffer,256);
    		n2 = read(sockfd,buffer,255);
        	    if (n2 < 0) 
    		{
         		perror("ERROR reading from socket");
         		exit(1);
    		}
    		printf("Received message: %s\n",buffer);
                sendMessage=0;
   		}*/
              }
	      fflush (0);
	      usleep (10000);
	    }
            break;
        case 'F':
            if( fd == -1 ) error("serial port not opened");
            if( !quiet ) printf("flushing receive buffer\n");
            serialport_flush(fd);
            break;

        }
    }

    exit(EXIT_SUCCESS);
} // end main
Exemplo n.º 19
0
int main( int argc, char** argv )
{
    ///////////
    //serial stuff
    int fd = 0;
    char serialport[256];
    int baudrate = B19200;
    //int baudrate = B115200;  // default
    
    fd = serialport_init("/dev/ttyUSB0", baudrate);
            if(fd==-1) return -1;
    usleep(3000 * 1000 );
    ///////////
    
    
    int c = 0, fps = 0;

    //capture from camera
    CvCapture *capture = cvCaptureFromCAM(1);
    //quit if camera not found
    if(!capture) {
        printf("cannot init capture!\n");
        return -1;
    }

    //display original video stream
    cvNamedWindow("stream", CV_WINDOW_AUTOSIZE);
    cvNamedWindow("hue", CV_WINDOW_NORMAL);
    cvResizeWindow("hue", 320, 240);
    cvMoveWindow("hue", 640, 0);

    CvFont font;
    cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 1.0, 1.0, 0, 2, CV_AA);

    //keep capturing frames until escape
    while(c != 27) //27 is escape key
    {
        //quit if can't grab frame
        if(!(frame = cvQueryFrame(capture))) break;

        //show the default image
        //cvShowImage("stream", frame);

        //edge detection - todo: HSV color filtering
        findLine(frame);

        //edge detection
        findEdge(frame);
        if(flag == 2)
            cvPutText(frame, "right edge", cvPoint(30, 400), &font, cvScalar(255, 0, 0, 0));
        else if(flag == 1)
            cvPutText(frame, "left edge", cvPoint(30, 400), &font, cvScalar(255, 0, 0, 0));

        //display center of gravity in coordinates
        COG(&cog_x, &cog_y);
        char x_coord[10];
        char y_coord[10];
        sprintf(x_coord, "%1.2f", cog_x);
        sprintf(y_coord, "%1.2f", cog_y);
	


        
        //find center of y coordinate in left and right edge
        COG_edges(&left_y, &right_y);

printf("%1.2f\n", left_y);
printf("%1.2f\n", right_y);

        
        
        uint8_t b = 0b00000000;
        //motor logic
        char motor1[10];
        char motor2[10];
        if(flag == 1) 
        {
            b = 0b00010001;
            sprintf(motor1, "%s", "backward");
            sprintf(motor2, "%s", "backward");
        }
        else if(flag == 2)
        {
            b = 0b10011001;
            sprintf(motor1, "%s", "forward");
            sprintf(motor2, "%s", "forward");
        }
        else if((int)(left_y/10.0) - (int)(right_y/10.0) < -4) //rotate right
        {
            b = 0b10010001;
            sprintf(motor1, "%s", "forward");
            sprintf(motor2, "%s", "backward");
        }
        else if((int)(right_y/10.0) - (int)(left_y/10.0) < -4) //rotate left
        {
            b = 0b00011001;
            sprintf(motor1, "%s", "backward");
            sprintf(motor2, "%s", "forward");
        }
        else 
        {
            b = 0;
            sprintf(motor1, "%s", "STOP");
            sprintf(motor2, "%s", "STOP");
        }
            
        
        //SERIAL - motor logic
        //xxxx_xxxx = motor1_motor2, 1-15 -> -7,7 -> 8 = 0 = 1000
        //edges
        
        write(fd,&b,1);
        
        
        //cvPutText(frame, x_coord, cvPoint(30,300), &font, cvScalar(255, 0, 0, 0));
        cvPutText(frame, "y:", cvPoint(0,350), &font, cvScalar(255, 0, 0, 0));
        cvPutText(frame, y_coord, cvPoint(30,350), &font, cvScalar(255, 0, 0, 0));
        
        
        cvPutText(frame, "motor1:", cvPoint(0,150), &font, cvScalar(255, 0, 0, 0));
        cvPutText(frame, motor1, cvPoint(150,150), &font, cvScalar(255, 0, 0, 0));
        cvPutText(frame, "motor2:", cvPoint(0,200), &font, cvScalar(255, 0, 0, 0));
        cvPutText(frame, motor2, cvPoint(150,200), &font, cvScalar(255, 0, 0, 0));

        cvShowImage("stream", frame);
        c = cvWaitKey(10);
    }

    cvReleaseCapture(&capture);
        //avoid memory leaks
        cvReleaseImage(&image);
        cvReleaseImage(&red);
        cvReleaseImage(&green);
        cvReleaseImage(&red_edge);
        cvReleaseImage(&green_edge);
        cvReleaseImage(&edge);
        cvReleaseImage(&final);
        cvReleaseImage(&frame);
	cvReleaseImage(&bw);
	cvReleaseImage(&gray);

    return 0;
}
Exemplo n.º 20
0
/* a little test program */
int main(int argc, char *argv[])
{
	int  joy_file, received, serial_file;
	int  done = 0;
	char joy_address[32] = "/dev/input/\0";
	int  axis_values[8] = {0};
	int  button_values[11] = {0};

	struct js_event jse;

	if(argc > 2)
	{
		printf("Too many arguments, exiting.");
		return 0;
	}
	if(argc == 2)
	{
		strcat(joy_address, argv[1]);
		joy_file = open_joystick(joy_address);
	}
	else if(argc == 1)
	{
		joy_file = open_joystick("/dev/input/js0");
	}
	
	if (joy_file < 0) 
	{
		printf("Joystick open failed.\n");
		exit(1);
	}

	serial_file = serialport_init(ARDUINO_COMM_LOCATION, ROBOT_BAUDRATE);
	
	if(serial_file < 0)
	{
		printf("Can't open serial port.");
		exit(2);
	}

	clearPort(serial_file);

	while (!done) {
		received = read_joystick_event(&jse);
		usleep(1000);
		if (received == 1) {
			switch(jse.type)
			{
				case TYPE_NOT_BUTTON:
					if(axis_values[jse.number] != jse.value)
						axis_values[jse.number] = jse.value;
					break;	
				case TYPE_BUTTON:
					if(button_values[jse.number] != jse.value)
					{
						button_values[jse.number] = jse.value;
						send_button_update(&jse, serial_file);
					}
					break;
			}	
		}
	}
}
Exemplo n.º 21
0
void HardwareSerial::begin(long baud)
{
    _fd = serialport_init(_deviceFile.c_str(),baud);
}
Exemplo n.º 22
0
int main( int argc, char** argv )
{
    /*
     * serial stuff
     */
    int fd = 0;
    char serialport[256];
    int baudrate = B19200;
    //FIXME
    fd = serialport_init("/dev/ttyUSB0", baudrate);
            if(fd==-1) return -1;
    usleep(3000 * 1000);
    ///////////////////////////////////////////////////////


    int c = 0, fps = 0;

    //capture from camera
    CvCapture *capture = cvCaptureFromCAM(1);
    //quit if camera not found
    if(!capture) {
        printf("cannot init capture!\n");
        return -1;
    }


    //display original video stream
    cvNamedWindow("stream", CV_WINDOW_NORMAL);
    cvResizeWindow("stream", 320, 240);
    cvNamedWindow("hue", CV_WINDOW_NORMAL);
    cvResizeWindow("hue", 320, 240);
    cvMoveWindow("hue", 320, 0);

    CvFont font;
    cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 1.0, 1.0, 0, 2, CV_AA);

    //keep capturing frames until escape
    while(c != 27) //27 is escape key
    {
        //quit if can't grab frame
        if(!(frame = cvQueryFrame(capture))) break;

        //show the default image
        //cvShowImage("stream", frame);

        //edge detection - todo: HSV color filtering
        findLine(frame);

        //edge detection
        findEdge(frame);
        if(flag == 2)
            cvPutText(frame, "right edge", cvPoint(30, 400), &font, cvScalar(255, 0, 0, 0));
        else if(flag == 1)
            cvPutText(frame, "left edge", cvPoint(30, 400), &font, cvScalar(255, 0, 0, 0));

        //display center of gravity in coordinates
        COG(&cog_x, &cog_y);
        char x_coord[10];
        char y_coord[10];
        sprintf(x_coord, "%1.2f", cog_x);
        sprintf(y_coord, "%1.2f", cog_y);

        //find center of y coordinate in left and right edge
        COG_edges(&left_y, &right_y);
		//printf("%1.2f\n", left_y);
		//printf("%1.2f\n", right_y);

		//find slant
		findSlant(frame);
		char write_slant[15];
		if(slant && offset) sprintf(write_slant, "%s", "crooked slant!");		//eventually invokes s movement
        else sprintf(write_slant, "%s", "\0");

        
        //TODO: FIXME
		//motor1 is closer to bottom, motor 2 is closer to top (in starting config)
        uint8_t b = 0b00000000;
        //motor logic
        char motor1[10];
        char motor2[10];
		
		//handles any errors - move 0.5 second for now
        //might have to flip these
        if(flag == 1)
        {
            b = 0b00000111;	
            sprintf(motor1, "%s", "backward");
            sprintf(motor2, "%s", "backward");
            write(fd,&b,1);
        }
        else if(flag == 2)
        {
            b = 0b00000100;
            sprintf(motor1, "%s", "forward");
            sprintf(motor2, "%s", "forward");
            write(fd,&b,1);
        }
        else if(ROR) //rotate right (eventually look at angle and change timing appropriately)
        {
            printf("%s\n", "ROTATE RIGHT");
            sleep(2);
            b = 0b00000101;
            sprintf(motor1, "%s", "forward");
            sprintf(motor2, "%s", "backward");
            write(fd,&b,1);
        }
        else if(ROL) //rotate left (eventually look at angle and change timing appropriately)
        {
            printf("%s\n", "ROTATE LEFT");
            sleep(2);
            b = 0b00000110;
            sprintf(motor1, "%s", "backward");
            sprintf(motor2, "%s", "forward");
            write(fd,&b,1);
        }
		//NO ERROR - THIS HANDLES LOGIC TO DRIVE ROBOT IN CORRECT SEQUENCE
		//determines the amount of time and directions in which to move the motors.
		//the arduino is responsible for sending stop command to wheels!
        else
        {
			switch(count)
			{
				//first shingle - already in place
				case 0:
				b = 0b00000000;	//do nothing
				write(fd,&b,1);
				//sleep(6); //however long it takes to place shingle, or wait until arduino says go
                printf("%s\n", "case 0");
				break;
				
				//second/third shingle - drive forward one foot (for now 2 secs, figure this out!)
				case 1:
				case 2:
				b = 0b01000000;	//forward 1 foot
				write(fd,&b,1);
				sleep(3);
                printf("%s\n", "case 1/2");
				break;
				
				//left (viewing from bottom) overhang
				case 3:
				b = 0b00100011;	//backward 1/2 foot
				write(fd,&b,1);
				b = 0b00110001;	//ROR 90 degrees
				write(fd,&b,1);
				b = 0b00100011;	//backward 1/2 foot
				write(fd,&b,1);
				//sleep(12);
                printf("%s\n", "case 3");
				break;
				
				//right overhang
				case 4:
				b = 0b00110001;	//ROR 90 degrees
				write(fd,&b,1);
				b = 0b01000000;	//forward 1 foot
				write(fd,&b,1);
				b = 0b00110001;	//ROR 90 degrees
				write(fd,&b,1);
				//sleep(14);
                printf("%s\n", "case 4");
				break;
				
				//next to right overhang
				case 5:
				b = 0b01000011;	//backward 1 foot
				write(fd,&b,1);
				b = 0b00110001;	//ROR 90 degrees
				write(fd,&b,1);
				//sleep(8);
				break;
				
				//next to left overhang
				case 6:
				b = 0b01000000;	//forward 1 foot
				write(fd,&b,1);
				//sleep(6);
				break;
				
				//reposition at beginning position 
				case 7:
				b = 0b00110001;	//ROR 90 degrees
				write(fd,&b,1);
				b = 0b00100000;	//forward 1/2 foot
				write(fd,&b,1);
				b = 0b00110010; //ROL 90 degrees
				write(fd,&b,1);
				b = 0b01100011;	//backward 1+1/2 foot
				write(fd,&b,1);
                //sleep(14);
                break;
				
				//should not get here
				default:
				b = 0; //error
				write(fd,&b,1);
				//sleep(20);
				break;
			}
			
			//count = (count+1)%8;      //FIXME
        }
            
        
        //SERIAL - motor logic
        //xxxx_xxyy -> y = motor1/motor2, 0 = forward, 1 = backward, x = time in ms
        //edges

        //write(fd,&b,1);

        //cvPutText(frame, x_coord, cvPoint(30,300), &font, cvScalar(255, 0, 0, 0));
        cvPutText(frame, "y:", cvPoint(0,350), &font, cvScalar(255, 0, 0, 0));
        cvPutText(frame, y_coord, cvPoint(30,350), &font, cvScalar(255, 0, 0, 0));
        cvPutText(frame, "motor1:", cvPoint(0,150), &font, cvScalar(255, 0, 0, 0));
        cvPutText(frame, motor1, cvPoint(150,150), &font, cvScalar(255, 0, 0, 0));
        cvPutText(frame, "motor2:", cvPoint(0,200), &font, cvScalar(255, 0, 0, 0));
        cvPutText(frame, motor2, cvPoint(150,200), &font, cvScalar(255, 0, 0, 0));

        cvPutText(frame, write_slant, cvPoint(0,50), &font, cvScalar(255, 0,
                    0, 0));

        cvShowImage("stream", frame);
        c = cvWaitKey(10);


        //release images

	    //cvReleaseImage(&image);
	    //cvReleaseImage(&edge);
	    //cvReleaseImage(&final);

	    //cvReleaseImage(&frame);
	    //cvReleaseImage(&bw);
	    //cvReleaseImage(&gray);
    }

	//release created images
	cvReleaseCapture(&capture);

    return 0;
}
Exemplo n.º 23
0
int main(void)
{
    port_init();
	serialport_init();
	timer_init();
	tempSensor_init();
	//alpha_init();
	
	// activate interrupts
	sei();
	
	uint8_t i,j;						// multi used index variables
	uint16_t k;
	
	uint8_t messageCtr = 0;				// message counter for automatic messages 
	
	CARRIAGE aDataSet;					// a data set used for communication
	
	uint8_t temperature[24];			// the temperatures, actual only 0-7 are in use
	uint8_t spare_temperature[8];		// the spare values for the aida values (actual not in use)
	uint8_t spare_temperatureTimer = 5; // timeout timer for AIDA temperature (use spare values until values are older then 4 seconds)
	
	uint16_t literPerHour = 0;
		
	CHANNELDATA channel_data[NUMBEROFCHANNELS];		// the permanent data of the 4 channels (fan 1-3 and analog)
	CHANNELSTATUS channel_status[NUMBEROFCHANNELS];	// the actual status of the channels
	
	LEDDATA led_data;					// data for the led channels
	uint16_t ledCtr = 0;				// a rotary counter value for led sweep calculation, incremented every 100 ms
	
	ALERTDATA alert_data;				// data for alert
	ALERTSTATUS alert_status;			// actual status
	
	uint8_t time[3] = {0,0,0};			// = {h,m,s}
	uint16_t pcStatus[4] = {0,0,0,0};	// = {CPU_CLK,CPU%,GPU%,RAM%}
	
	uint16_t pulsePerLiter;
	
	
	if (eeprom_read_word(&eeprom_eepromVersionChecker) != EEPROMVERSION_BITS)			// EEPROM is not OK
	{		
		
		// serialport_printf("#EEPROM FAILED, START TO OVERWRITE IT!#\r");
		
		for (j=0;j<NUMBEROFCHANNELS;j++)
		{
			for (i=0;i<sizeof(CHANNELDATA);i++)
			{
				eeprom_write_byte(((uint8_t *)&eeprom_channel_data[j])+i,pgm_read_byte(((uint8_t *)&default_channel_data)+i));
			}			
		}
		
		// serialport_printf("#CHANNELS COMPLETE#\r");
				
		for (i=0;i<8;i++)
		{
			eeprom_write_byte((&eeprom_spare_temperature[i]),pgm_read_byte(&default_spare_temperature[i]));
		}
		
		// serialport_printf("#SPARE TEMPERATURES COMPLETE#\r");
		
		for (i=0;i<sizeof(LEDDATA);i++)
		{
			eeprom_write_byte(((uint8_t *)&eeprom_led_data)+i,pgm_read_byte(((uint8_t *)&default_led_data)+i));
		}
		
		// serialport_printf("#LED COMPLETE#\r");
		
		for (i=0;i<sizeof(ALERTDATA);i++)
		{
			eeprom_write_byte(((uint8_t *)&eeprom_alert_data)+i,pgm_read_byte(((uint8_t *)&default_alert_data)+i));
		}
		
		// serialport_printf("#ALERT COMPLETE#\r");
		
		eeprom_write_word(&eeprom_pulsePerLiter,pgm_read_word(&default_pulsePerLiter));
		
		// serialport_printf("#PULSEPERLITER COMPLETE#\r");
		
		for (k=0;k<sizeof(ALPHANUMERIC);k++)
		{
			eeprom_write_byte(((uint8_t *)&eeprom_alphaDisplay)+k,pgm_read_byte(((uint8_t *)&default_alphaDisplay)+k));
		}
		
		// serialport_printf("\r#DISPLAY COMPLETE#\r");
		
		eeprom_write_word(&eeprom_eepromVersionChecker,EEPROMVERSION_BITS);
		
		// serialport_printf("#EEPROMVERSION COMPLETE#\r");
		// serialport_printf("#EEPROM OVERRIDE COMPLETE, START#\r");
	}
	
	
	pulsePerLiter = eeprom_read_word(&eeprom_pulsePerLiter);	// impulses per liter of the flow meter
	timer_setImpulsePerLiter(pulsePerLiter);							// inform the timer
	
	//ALPHANUMERIC alphaDisplay;
	//uint8_t screenIndex = 0;
	//uint8_t screenCountdown;
	//uint8_t screenOverlayMessageCountdown = 0;
	//
	//uint8_t switch1_ctr = 0;
	//uint8_t switch2_ctr = 0;
	//
	//uint8_t buzzerEnable = 1;
	
	// read the EEPROM
	eeprom_read_block((void*)channel_data, (const void*)eeprom_channel_data, (NUMBEROFCHANNELS*sizeof(CHANNELDATA)));
	eeprom_read_block((void*)spare_temperature, (const void*)eeprom_spare_temperature, 8);
	eeprom_read_block((void*)&led_data, (const void*)&eeprom_led_data, sizeof(LEDDATA));
	eeprom_read_block((void*)&alert_data, (const void*)&eeprom_alert_data, sizeof(ALERTDATA));
	//eeprom_read_block((void*)&alphaDisplay, (const void*)&eeprom_alphaDisplay, sizeof(ALPHANUMERIC));
	//timer_setPwm(BACKLIGHT,alphaDisplay.backlight);
	//alpha_setContrast(alphaDisplay.contrast);
	//screenCountdown = alphaDisplay.screen[0];	
	
	
	for (i=0;i<NUMBEROFCHANNELS;i++)
	{
		channel_status[i].startupTimer = channel_data[i].startupTime;
		channel_status[i].status = startup;		
	}
	
		
	
	
	//#ifdef REV2_1
		//alpha_displayOverlayMessage("    ConFLiCT                    FW: C0.3 HW: 2.1");
	//#endif
	//#ifdef REV2_2
		//alpha_displayOverlayMessage("    ConFLiCT                    FW: C0.3 HW: 2.2"); 
	//#endif	
	//screenOverlayMessageCountdown = 10; 
		
	while(1)						// main loop
    {
        		
		// use spare temperatures if aida temperatures are to old
		if (spare_temperatureTimer > 4)
		{
			for (i=0;i<8;i++)
			{
				temperature[i+16] = spare_temperature[i];
			}
		}
				
		alert_status.overtemp = 0;				// reset the overtemp alert 
		
		// calculate the channel power
		for (i=0;i<NUMBEROFCHANNELS;i++)
		{	
					
			if (channel_data[i].automaticMode)		// automatic mode
			{
				uint8_t cooling = 0;			// temporary cooling value
				uint8_t d1, d2;					// temporary variable for calculation
				for (j=0;j<24;j++)
				{
					if ((temperature[j] >= channel_data[i].minTemp[j]) && (temperature[j] <= channel_data[i].maxTemp[j])) // temperature is between min and max
					{
						d1 = 100 / (channel_data[i].maxTemp[j] - channel_data[i].minTemp[j]);	// calculate cooling value
						d2 = (temperature[j] - channel_data[i].minTemp[j]) * d1;
						if (d2 > cooling)	// save the highest cooling value	
						{
							cooling = d2;
						}						
					}
					if (temperature[j] > channel_data[i].maxTemp[j])	// a temperature over maximum! o.O
					{
						// over temperature
						if (alert_data.overtempEnable)
						{
							alert_status.overtemp = 1;
						}					
						cooling = 100;
					}				
				}
				
				switch (channel_status[i].status)						// check the status
				{
					case off:		
						channel_status[i].power = 0;					// turn it off
						if (channel_data[i].stopEnable)					// off allowed
						{
							if (cooling > channel_data[i].threshold)	// if cooling is higher then threshold
							{
								channel_status[i].status = startup;		// start the channel and reset the startup timer
								channel_status[i].startupTimer = channel_data[i].startupTime;
							}							
						}
						else                                            // off is not allowed (anymore)
						{
							channel_status[i].status = startup;			// start the channel and reset the startup timer
							channel_status[i].startupTimer = channel_data[i].startupTime;
						}
						break;
					
					case startup:										
						channel_status[i].power = 100;					// 100 % for startup
						break;
					
					case on:
						if ((cooling == 0) && (channel_data[i].stopEnable == 1))	// if stop is enabled and no cooling needed
						{
							channel_status[i].status = off;				// turn it off
						}
						// calculate the power value out off the minimum value and the cooling value
						channel_status[i].power = (uint8_t)((((uint16_t)(100-channel_data[i].minimumPower))*cooling)/100 + channel_data[i].minimumPower);
						break;
				}				
			}
			 
			else								// manual mode
			{
				switch (channel_status[i].status)					// check the status
				{
					case off:						
						channel_status[i].power = 0;				// turn it off
						if (channel_data[i].manualPower > 0)		
						{
							channel_status[i].status = startup;		// start the channel and reset the startup timer
							channel_status[i].startupTimer = channel_data[i].startupTime;
						}					
						break;
					
					case startup:
						channel_status[i].power = 100;				// 100 % for startup
						break;
						
					case on:
						channel_status[i].power = channel_data[i].manualPower;
						if (channel_data[i].manualPower == 0)		// if no power, go to off
						{
							channel_status[i].status = off;
						}
						break;						
				}						
			}	
					
		}
		
		alert_status.fanblock = 0;		// reset the fan block status
		
		// exchange channel with hardware timer
		for (i=0;i<NUMBEROFCHANNELS;i++)
		{
			timer_setPwm(i,channel_status[i].power);
			channel_status[i].rpm = timer_getRpm(i);
			if (channel_status[i].status == on && channel_status[i].rpm == 0 && alert_data.fanblockEnable && i != 3)
			{
				alert_status.fanblock = 1;		// fan is blocked or not started correctly
			}			
		}
		
		// get liter per hour
		literPerHour = timer_getLH();
		if (literPerHour < alert_data.minWaterFlow)
		{
			alert_status.lowWaterFlow = 1;
		}
		else
		{
			alert_status.lowWaterFlow = 0;
		}
			
		
		
		// led exchange and calculating
		switch (led_data.mode)		
		{
			case 0:		// manual mode
				timer_setPwm(LED_RED,led_data.manualPower[0]);
				timer_setPwm(LED_GREEN,led_data.manualPower[1]);
				timer_setPwm(LED_BLUE,led_data.manualPower[2]);
				break;
				
			case 1:
				// Do calculation with ledCtr, timer_setPWM(LED_X,value), and local variables only!
				if (ledCtr < 100)
				{
					timer_setPwm(LED_RED,ledCtr);
					timer_setPwm(LED_GREEN,0);
					timer_setPwm(LED_BLUE,0);
				} 
				else if(ledCtr < 200)
				{
					timer_setPwm(LED_RED,200-ledCtr);
					timer_setPwm(LED_GREEN,0);
					timer_setPwm(LED_BLUE,0);
				}
				else if (ledCtr < 300)
				{
					timer_setPwm(LED_GREEN,ledCtr-200);
					timer_setPwm(LED_RED,0);
					timer_setPwm(LED_BLUE,0);
				}
				else if (ledCtr < 400)
				{
					timer_setPwm(LED_GREEN,400-ledCtr);
					timer_setPwm(LED_RED,0);
					timer_setPwm(LED_BLUE,0);
				}
				else if (ledCtr < 500)
				{
					timer_setPwm(LED_BLUE,ledCtr-400);
					timer_setPwm(LED_RED,0);
					timer_setPwm(LED_GREEN,0);
				}
				else if (ledCtr < 600)
				{
					timer_setPwm(LED_BLUE,600-ledCtr);
					timer_setPwm(LED_RED,0);
					timer_setPwm(LED_GREEN,0);
				} 
				else
				{
					ledCtr = 0;
				}
				break;
				
			default:	// wrong mode, red led on
				timer_setPwm(LED_BLUE,0);
				timer_setPwm(LED_GREEN,0);
				timer_setPwm(LED_RED,100);
				break;				
		} 
		
				
			
		
		// each 524ms
		if (timer_524ms())
		{			
			// decrement the channel startup timers
			for (i=0;i<NUMBEROFCHANNELS;i++)
			{
				if (channel_status[i].startupTimer > 1)
				{
					channel_status[i].startupTimer--;
				}
				if (channel_status[i].startupTimer == 1)
				{
					channel_status[i].startupTimer = 0;
					channel_status[i].status = on;		// go to on if startup time is over
				}
			}
			
			// increment the spare temperature timer
			if (spare_temperatureTimer < 255)
			{
				spare_temperatureTimer ++;
			}
			
			// beeper
			//if ((alert_status.fanblock || alert_status.lowWaterFlow || alert_status.overtemp) && buzzerEnable)
			//{
				//// toggle beeper
				//PORTR_OUTTGL = 1;
			//} 
			//else
			//{
				//// turn beeper off
				//PORTR_OUTCLR = 1;
			//}
			
			
			// display
			//screenCountdown --;						
			//if (screenCountdown == 0)
			//{
				//screenIndex ++;
				//if (alphaDisplay.screen[screenIndex] == 0)		// screen is not available
				//{
					//screenIndex = 0;		// go to first screen					
				//} 
				//screenCountdown = alphaDisplay.screen[screenIndex];				
			//}
			//if (screenOverlayMessageCountdown == 0)
			//{
				//// if no alert is active, show normal display content
				//if (alert_status.fanblock == 0 && alert_status.lowWaterFlow == 0 && alert_status.overtemp == 0)
				//{
					//alpha_updateScreen(screenIndex,alphaDisplay.content,temperature,time,pcStatus,&literPerHour,channel_status);
				//}
				//else // else show the alert
				//{
					//alpha_displayAlert(alert_status);
				//}
			//} 
			//else
			//{
				//screenOverlayMessageCountdown--;
			//}
			
				
		}
			
		// each 100ms
		if (timer_100ms())
		{
			// get the temperatures
			for (i=0;i<16;i++)
			{
				temperature[i] = tempSensor_getTemp(i);		// read out up to 8 NTC-Sensors and 8 1-Wire sensors
			}
						
			
			ledCtr++;
			
			// check switch 1, left button
			//if (SWITCH1)
			//{
				//if (switch1_ctr < 255)
				//{
					//switch1_ctr++;
				//}
			//}
			//else
			//{
				//switch1_ctr = 0;
			//}
			//
			//if (switch1_ctr == 2)
			//{
				//if (buzzerEnable)
				//{
					//buzzerEnable = 0;
					//// turn beeper off
					//PORTR_OUTCLR = 1;
					//alpha_displayOverlayMessage("buzzer disabled");
				//}
				//else
				//{
					//buzzerEnable = 1;
					//alpha_displayOverlayMessage("buzzer enabled");
				//}
				//screenOverlayMessageCountdown = 2;				
			//}
			
			// check the next button (switch 2, right button)
			//if (SWITCH2)
			//{				
				//if (switch2_ctr < 255)
				//{					
					//switch2_ctr++;					
				//}		
			//}
			//else
			//{
				//switch2_ctr = 0;
			//}
			//
			//
			//// change display content if button 2 is short pressed or every 1 second pressed
			//if (switch2_ctr == 10)
			//{
				//switch2_ctr = 1;
			//}
			//
			//if (switch2_ctr == 1)
			//{
				//screenIndex ++;
				//if (alphaDisplay.screen[screenIndex] == 0)		// screen is not available
				//{
					//screenIndex = 0;		// go to first screen
				//}
				//screenCountdown = alphaDisplay.screen[screenIndex];
				//// if no alert is active, show normal display content
				//if (alert_status.fanblock == 0 && alert_status.lowWaterFlow == 0 && alert_status.overtemp == 0)
				//{
					//alpha_updateScreen(screenIndex,alphaDisplay.content,temperature,time,pcStatus,&literPerHour,channel_status);
				//}
			//}
			
			
			
			// send some actual information to the PC
			// every 100 ms an other of these messages 
			messageCtr++;
			aDataSet.dA = SERIALPORT_DATA;
			switch (messageCtr)
			{
				case 1:		// temperatures
					aDataSet.id = 30;					
					for (i=0;i<24;i++)
					{
						aDataSet.index = i + 1;
						aDataSet.data = temperature[i];
						serialport_writeCarriage(&aDataSet);
					}
					break;
			
				case 2:		// alerts
					aDataSet.id = 50;
					aDataSet.index = 1;
					aDataSet.data = alert_status.overtemp;
					serialport_writeCarriage(&aDataSet);
					aDataSet.index = 2;
					aDataSet.data = alert_status.fanblock;
					serialport_writeCarriage(&aDataSet);
					aDataSet.index = 3;
					aDataSet.data = alert_status.lowWaterFlow;
					serialport_writeCarriage(&aDataSet);
					break;
			
				case 3:		// water flow
					aDataSet.id = 60;
					aDataSet.index = 1;
					aDataSet.data = literPerHour;
					serialport_writeCarriage(&aDataSet);
					break;
			
				case 4:		// RPM of channels
					aDataSet.id = 61;
					for (i= 0;i<4;i++)
					{
						aDataSet.index = i + 1;
						aDataSet.data = channel_status[i].rpm;
						serialport_writeCarriage(&aDataSet);
					}
					break;
			
				case 5:		// power values
					aDataSet.id = 62;
					aDataSet.dA = SERIALPORT_DATA;
					for (i= 0;i<NUMBEROFCHANNELS;i++)
					{
						aDataSet.index = i + 1;
						aDataSet.data = channel_status[i].power;
						serialport_writeCarriage(&aDataSet);
					}
					messageCtr = 0;
					break;			
			}				
		}			
		
		
		// check for received carriages
		if (serialport_getLastCarriage(&aDataSet) == 0)								// new carriage received
		{
						
			if (aDataSet.dA == SERIALPORT_DATA)			// new data
			{
				switch(aDataSet.id)
				{
					case 01:							// reset
						if (aDataSet.index == 170 && aDataSet.data == 85)
						{
							cli();						// disable interrupts
							wdt_reset();				// reset via watchdog
							_delay_ms(1);				// wait until reset occurs
						}						
						break;
						
					case 30:							// temperatures from AIDA or other PC software
						temperature[aDataSet.index-1] = aDataSet.data;
						spare_temperatureTimer = 0;
						break;
					
					case 11:							// minimum temperatures channel 0
						channel_data[0].minTemp[aDataSet.index-1] = aDataSet.data;
						eeprom_update_byte(&eeprom_channel_data[0].minTemp[aDataSet.index-1], channel_data[0].minTemp[aDataSet.index-1]);
						break;
					
					case 21:							// maximum temperatures channel 0
						channel_data[0].maxTemp[aDataSet.index-1] = aDataSet.data;
						eeprom_update_byte(&eeprom_channel_data[0].maxTemp[aDataSet.index-1], channel_data[0].maxTemp[aDataSet.index-1]);
						break;
					
					case 12:							// minimum temperatures channel 1
						channel_data[1].minTemp[aDataSet.index-1] = aDataSet.data;
						eeprom_update_byte(&eeprom_channel_data[1].minTemp[aDataSet.index-1], channel_data[1].minTemp[aDataSet.index-1]);
						break;
					
					case 22:							// maximum temperatures channel 1
						channel_data[1].maxTemp[aDataSet.index-1] = aDataSet.data;
						eeprom_update_byte(&eeprom_channel_data[1].maxTemp[aDataSet.index-1], channel_data[1].maxTemp[aDataSet.index-1]);
						break;
						
					case 13:							// minimum temperatures channel 2
						channel_data[2].minTemp[aDataSet.index-1] = aDataSet.data;
						eeprom_update_byte(&eeprom_channel_data[2].minTemp[aDataSet.index-1], channel_data[2].minTemp[aDataSet.index-1]);
						break;
					
					case 23:							// maximum temperatures channel 2
						channel_data[2].maxTemp[aDataSet.index-1] = aDataSet.data;
						eeprom_update_byte(&eeprom_channel_data[2].maxTemp[aDataSet.index-1], channel_data[2].maxTemp[aDataSet.index-1]);
						break;	
						
					case 14:							// minimum temperatures channel 3
						channel_data[3].minTemp[aDataSet.index-1] = aDataSet.data;
						eeprom_update_byte(&eeprom_channel_data[3].minTemp[aDataSet.index-1], channel_data[3].minTemp[aDataSet.index-1]);
						break;
					
					case 24:							// maximum temperatures channel 3
						channel_data[3].maxTemp[aDataSet.index-1] = aDataSet.data;
						eeprom_update_byte(&eeprom_channel_data[3].maxTemp[aDataSet.index-1], channel_data[3].maxTemp[aDataSet.index-1]);
						break;
						
					case 31:							// spare temperatures
						spare_temperature[aDataSet.index-17] = aDataSet.data;
						eeprom_update_byte(&eeprom_spare_temperature[aDataSet.index-17], spare_temperature[aDataSet.index-17]);
						break;	
						
					case 40:							// time
						time[aDataSet.index-1] = aDataSet.data;
						break;
					
					case 41:							// PC information
						pcStatus[aDataSet.index-1] = aDataSet.data;
						break;
					
					case 51:							// alert enable
						if (aDataSet.index == 1)
						{
							alert_data.overtempEnable = aDataSet.data;
							eeprom_update_byte(&eeprom_alert_data.overtempEnable, alert_data.overtempEnable);
						} 
						else if (aDataSet.index == 2)
						{
							alert_data.fanblockEnable = aDataSet.data;
							eeprom_update_byte(&eeprom_alert_data.fanblockEnable, alert_data.fanblockEnable);
						}
						break;
					
						
					case 70:							// Pulse per liter of flowMeter
						if (aDataSet.index == 1)
						{
							pulsePerLiter = aDataSet.data;
							timer_setImpulsePerLiter(pulsePerLiter);
							eeprom_update_word(&eeprom_pulsePerLiter, pulsePerLiter);
						}
						else if (aDataSet.index == 2)
						{
							alert_data.minWaterFlow = aDataSet.data;
							eeprom_update_word(&eeprom_alert_data.minWaterFlow, alert_data.minWaterFlow);
						}
						break;
					
					case 71:							// manual power
						channel_data[aDataSet.index-1].manualPower = aDataSet.data;
						eeprom_update_byte(&eeprom_channel_data[aDataSet.index-1].manualPower, channel_data[aDataSet.index-1].manualPower);
						break;
						
					case 72:							// startup times
						if (aDataSet.data == 0)
						{
							channel_data[aDataSet.index-1].startupTime = 1;							
						} 
						else
						{
							channel_data[aDataSet.index-1].startupTime = aDataSet.data;
						}
						eeprom_update_byte(&eeprom_channel_data[aDataSet.index-1].startupTime, channel_data[aDataSet.index-1].startupTime);
						break;
					
					case 73:							// minimum power
						channel_data[aDataSet.index-1].minimumPower = aDataSet.data;
						eeprom_update_byte(&eeprom_channel_data[aDataSet.index-1].minimumPower, channel_data[aDataSet.index-1].minimumPower);
						break;
						
					case 74:							// automatic mode
						channel_data[aDataSet.index-1].automaticMode = aDataSet.data;
						eeprom_update_byte(&eeprom_channel_data[aDataSet.index-1].automaticMode, channel_data[aDataSet.index-1].automaticMode);
						break;
						
					case 75:							// stop enable
						channel_data[aDataSet.index-1].stopEnable = aDataSet.data;
						eeprom_update_byte(&eeprom_channel_data[aDataSet.index-1].stopEnable, channel_data[aDataSet.index-1].stopEnable);
						break;
						
					case 76:							// threshold
						channel_data[aDataSet.index-1].threshold = aDataSet.data;
						eeprom_update_byte(&eeprom_channel_data[aDataSet.index-1].threshold, channel_data[aDataSet.index-1].threshold);
						break;
						
					case 77:							// backlight and contrast
						//if (aDataSet.index == 1)
						//{
							//alphaDisplay.backlight = aDataSet.data;
							//timer_setPwm(BACKLIGHT,alphaDisplay.backlight);
							//eeprom_update_byte(&eeprom_alphaDisplay.backlight, alphaDisplay.backlight);
						//}
						//else if (aDataSet.index == 2)
						//{
							//alphaDisplay.contrast = aDataSet.data;
							//alpha_setContrast(alphaDisplay.contrast);
							//eeprom_update_byte(&eeprom_alphaDisplay.contrast, alphaDisplay.contrast);
						//}
						break;
					
					case 78:							// led mode
						led_data.mode = aDataSet.data;
						eeprom_update_byte(&eeprom_led_data.mode, led_data.mode);
						ledCtr = 0;
						break;
						
					case 79:							// led manual power
						led_data.manualPower[aDataSet.index-1] = aDataSet.data;
						eeprom_update_byte(&eeprom_led_data.manualPower[aDataSet.index-1], led_data.manualPower[aDataSet.index-1]);
						break;
						
					case 80:							// display content
						//alphaDisplay.content[aDataSet.index-1] = aDataSet.data;
						//eeprom_update_byte(&eeprom_alphaDisplay.content[aDataSet.index-1], alphaDisplay.content[aDataSet.index-1]);
						break;
						
					case 81:							// display screens
						//alphaDisplay.screen[aDataSet.index-1] = aDataSet.data;
						//eeprom_update_byte(&eeprom_alphaDisplay.screen[aDataSet.index-1], alphaDisplay.screen[aDataSet.index-1]);
						break;												
				}				
			}
			
			if (aDataSet.dA == SERIALPORT_ASK)			// new ask
			{
				aDataSet.dA = SERIALPORT_DATA;			// return always data
				switch(aDataSet.id)
				{
					case 0:								// ask for everything
						aDataSet.id = 02;
						aDataSet.index = 1;
						aDataSet.data = FIRMWAREVERSION;
						serialport_writeCarriage(&aDataSet);
						aDataSet.index = 2;
						aDataSet.data = EEPROMVERSION;
						serialport_writeCarriage(&aDataSet);
						for (i=0;i<24;i++)
						{
							aDataSet.id = 11;			// 11
							aDataSet.index = i+1;
							aDataSet.data = channel_data[0].minTemp[i];
							serialport_writeCarriage(&aDataSet);
							aDataSet.id = 21;			// 21
							aDataSet.data = channel_data[0].maxTemp[i];
							serialport_writeCarriage(&aDataSet);
							aDataSet.id = 12;			// 12
							aDataSet.data = channel_data[1].minTemp[i];
							serialport_writeCarriage(&aDataSet);
							aDataSet.id = 22;			// 22
							aDataSet.data = channel_data[1].maxTemp[i];
							serialport_writeCarriage(&aDataSet);
							aDataSet.id = 13;			// 13
							aDataSet.data = channel_data[2].minTemp[i];
							serialport_writeCarriage(&aDataSet);
							aDataSet.id = 23;			// 23
							aDataSet.data = channel_data[2].maxTemp[i];
							serialport_writeCarriage(&aDataSet);
							aDataSet.id = 14;			// 14
							aDataSet.data = channel_data[3].minTemp[i];
							serialport_writeCarriage(&aDataSet);
							aDataSet.id = 24;			// 24
							aDataSet.data = channel_data[3].maxTemp[i];
							serialport_writeCarriage(&aDataSet);							
						}
						aDataSet.id = 31;				// 31
						for (i=0;i<8;i++)
						{
							aDataSet.index = i+17;
							aDataSet.data = spare_temperature[i];
							serialport_writeCarriage(&aDataSet);
						}						
						aDataSet.id = 32;				// 32
						aDataSet.index = 1;
						aDataSet.data = tempSensor_getOneWireAmount();
						serialport_writeCarriage(&aDataSet);												
						aDataSet.id = 33;				// 33
						for (i=0;i<(8*tempSensor_getOneWireAmount());i++)
						{
							aDataSet.index = i+1;
							aDataSet.data = tempSensor_getOneWireID(i);
							serialport_writeCarriage(&aDataSet);
						}						
						aDataSet.id = 51;				// 51
						aDataSet.index = 1;
						aDataSet.data = alert_data.overtempEnable;
						serialport_writeCarriage(&aDataSet);
						aDataSet.index = 2;
						aDataSet.data = alert_data.fanblockEnable;
						serialport_writeCarriage(&aDataSet);
						aDataSet.id = 70;				// 70
						aDataSet.index = 1;
						aDataSet.data = pulsePerLiter;
						serialport_writeCarriage(&aDataSet);
						aDataSet.index = 2;
						aDataSet.data = alert_data.minWaterFlow;
						serialport_writeCarriage(&aDataSet);
						for (i=0;i<4;i++)
						{
							aDataSet.id = 71;				// 71
							aDataSet.index = i+1;
							aDataSet.data = channel_data[i].manualPower;
							serialport_writeCarriage(&aDataSet);
							aDataSet.id = 72;				// 72
							aDataSet.data = channel_data[i].startupTime;
							serialport_writeCarriage(&aDataSet);
							aDataSet.id = 73;				// 73
							aDataSet.data = channel_data[i].minimumPower;
							serialport_writeCarriage(&aDataSet);
							aDataSet.id = 74;				// 74
							aDataSet.data = channel_data[i].automaticMode;
							serialport_writeCarriage(&aDataSet);
							aDataSet.id = 75;				// 75
							aDataSet.data = channel_data[i].stopEnable;
							serialport_writeCarriage(&aDataSet);
							aDataSet.id = 76;				// 76
							aDataSet.data = channel_data[i].threshold;
							serialport_writeCarriage(&aDataSet);							
						}
						//aDataSet.id = 77;					// 77
						//aDataSet.index = 1;
						//aDataSet.data = alphaDisplay.backlight;
						//serialport_writeCarriage(&aDataSet);
						//aDataSet.index = 2;
						//aDataSet.data = alphaDisplay.contrast;
						//serialport_writeCarriage(&aDataSet);						
						aDataSet.id = 78;					// 78
						aDataSet.index = 1;
						aDataSet.data = led_data.mode;
						serialport_writeCarriage(&aDataSet);
						aDataSet.id = 79;					// 79
						for (i=0;i<3;i++)
						{
							aDataSet.index = i+1;
							aDataSet.data = led_data.manualPower[i];
							serialport_writeCarriage(&aDataSet);
						}
						//aDataSet.id = 80;					// 80
						//for (i=0;i<255;i++)				
						//{
							//aDataSet.index = i+1;
							//aDataSet.data = alphaDisplay.content[i];
							//serialport_writeCarriage(&aDataSet);
						//}
						//aDataSet.id = 81;					// 81
						//for (i=0;i<31;i++)
						//{
							//aDataSet.index = i+1;
							//aDataSet.data = alphaDisplay.screen[i];
							//serialport_writeCarriage(&aDataSet);
						//}									
						break;
					
					case 02:
						if (aDataSet.index == 0)		// ask for all of them
						{
							aDataSet.index = 1;
							aDataSet.data = FIRMWAREVERSION;
							serialport_writeCarriage(&aDataSet);
							aDataSet.index = 2;
							aDataSet.data = EEPROMVERSION;
							serialport_writeCarriage(&aDataSet);
						}
						else if (aDataSet.index == 1)
						{
							aDataSet.data = FIRMWAREVERSION;
							serialport_writeCarriage(&aDataSet);
						}
						else if (aDataSet.index == 2)
						{
							aDataSet.data = EEPROMVERSION;
							serialport_writeCarriage(&aDataSet);
						}
						break;
					
					case 11:
						if (aDataSet.index == 0)		// ask for all of them
						{							
							for (i=0;i<24;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = channel_data[0].minTemp[i];
								serialport_writeCarriage(&aDataSet);	
							}							
						} 
						else							// ask for a specific one
						{
							aDataSet.data = channel_data[0].minTemp[aDataSet.index-1];
							serialport_writeCarriage(&aDataSet);
						}					
						break;
						
					case 21:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<24;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = channel_data[0].maxTemp[i];
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = channel_data[0].maxTemp[aDataSet.index-1];
							serialport_writeCarriage(&aDataSet);
						}
						break;
					
					case 12:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<24;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = channel_data[1].minTemp[i];
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = channel_data[1].minTemp[aDataSet.index-1];
							serialport_writeCarriage(&aDataSet);
						}
						break;
						
					case 22:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<24;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = channel_data[1].maxTemp[i];
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = channel_data[1].maxTemp[aDataSet.index-1];
							serialport_writeCarriage(&aDataSet);
						}
						break;
					
					case 13:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<24;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = channel_data[2].minTemp[i];
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = channel_data[2].minTemp[aDataSet.index-1];
							serialport_writeCarriage(&aDataSet);
						}
						break;
						
					case 23:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<24;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = channel_data[2].maxTemp[i];
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = channel_data[2].maxTemp[aDataSet.index-1];
							serialport_writeCarriage(&aDataSet);
						}
						break;
						
					case 14:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<24;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = channel_data[3].minTemp[i];
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = channel_data[3].minTemp[aDataSet.index-1];
							serialport_writeCarriage(&aDataSet);
						}
						break;
						
					case 24:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<24;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = channel_data[3].maxTemp[i];
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = channel_data[3].maxTemp[aDataSet.index-1];
							serialport_writeCarriage(&aDataSet);
						}
						break;
					
					case 31:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<8;i++)
							{
								aDataSet.index = i+17;
								aDataSet.data = spare_temperature[i];
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = spare_temperature[aDataSet.index-17];
							serialport_writeCarriage(&aDataSet);
						}
						break;
					
					case 32:
						aDataSet.index = 1;
						aDataSet.data = tempSensor_getOneWireAmount();
						serialport_writeCarriage(&aDataSet);
						break;
					
					case 33:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<(8*tempSensor_getOneWireAmount());i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = tempSensor_getOneWireID(i);
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = tempSensor_getOneWireID(aDataSet.index-1);
							serialport_writeCarriage(&aDataSet);
						}
						break;
					
					case 51:
						switch (aDataSet.index)
						{
							case 0:
								aDataSet.index = 1;
								aDataSet.data = alert_data.overtempEnable;
								serialport_writeCarriage(&aDataSet);
								aDataSet.index = 2;
								aDataSet.data = alert_data.fanblockEnable;
								serialport_writeCarriage(&aDataSet);
								break;
								
							case 1:
								aDataSet.data = alert_data.overtempEnable;
								serialport_writeCarriage(&aDataSet);
								break;
								
							case 2:
								aDataSet.data = alert_data.fanblockEnable;
								serialport_writeCarriage(&aDataSet);
								break;			
						}
						break;
					
					case 70:
						switch (aDataSet.index)
						{
							case 0:
								aDataSet.index = 1;
								aDataSet.data = pulsePerLiter;
								serialport_writeCarriage(&aDataSet);
								aDataSet.index = 2;
								aDataSet.data = alert_data.minWaterFlow;
								serialport_writeCarriage(&aDataSet);
								break;
							
							case 1:
								aDataSet.data = pulsePerLiter;
								serialport_writeCarriage(&aDataSet);
								break;
							
							case 2:
								aDataSet.data = alert_data.minWaterFlow;
								serialport_writeCarriage(&aDataSet);
								break;
						}
						break;
					
					case 71:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<4;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = channel_data[i].manualPower;
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = channel_data[aDataSet.index-1].manualPower;
							serialport_writeCarriage(&aDataSet);
						}
						break;
						
					case 72:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<4;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = channel_data[i].startupTime;
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = channel_data[aDataSet.index-1].startupTime;
							serialport_writeCarriage(&aDataSet);
						}
						break;
					
					case 73:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<4;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = channel_data[i].minimumPower;
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = channel_data[aDataSet.index-1].minimumPower;
							serialport_writeCarriage(&aDataSet);
						}
						break;
						
					case 74:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<4;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = channel_data[i].automaticMode;
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = channel_data[aDataSet.index-1].automaticMode;
							serialport_writeCarriage(&aDataSet);
						}
						break;
						
					case 75:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<4;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = channel_data[i].stopEnable;
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = channel_data[aDataSet.index-1].stopEnable;
							serialport_writeCarriage(&aDataSet);
						}
						break;
						
					case 76:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<4;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = channel_data[i].threshold;
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = channel_data[aDataSet.index-1].threshold;
							serialport_writeCarriage(&aDataSet);
						}
						break;
						
					case 77:							// display backlight and contrast
						//switch (aDataSet.index)
						//{
							//case 0:
								//aDataSet.index = 1;
								//aDataSet.data = alphaDisplay.backlight;
								//serialport_writeCarriage(&aDataSet);
								//aDataSet.index = 2;
								//aDataSet.data = alphaDisplay.contrast;
								//serialport_writeCarriage(&aDataSet);
								//break;
						//
							//case 1:
								//aDataSet.data = alphaDisplay.backlight;
								//serialport_writeCarriage(&aDataSet);
								//break;
						//
							//case 2:
								//aDataSet.data = alphaDisplay.contrast;
								//serialport_writeCarriage(&aDataSet);
								//break;
						//}
						break;
						
					case 78:
						aDataSet.index = 1;
						aDataSet.data = led_data.mode;
						serialport_writeCarriage(&aDataSet);
						break;
						
					case 79:
						if (aDataSet.index == 0)		// ask for all of them
						{
							for (i=0;i<3;i++)
							{
								aDataSet.index = i+1;
								aDataSet.data = led_data.manualPower[i];
								serialport_writeCarriage(&aDataSet);
							}
						}
						else							// ask for a specific one
						{
							aDataSet.data = led_data.manualPower[aDataSet.index-1];
							serialport_writeCarriage(&aDataSet);
						}
						break;
						
					case 80:						// display content
						//if (aDataSet.index == 0)		// ask for all of them
						//{
							//for (i=0;i<255;i++)
							//{
								//aDataSet.index = i+1;
								//aDataSet.data = alphaDisplay.content[i];
								//serialport_writeCarriage(&aDataSet);
							//}
						//}
						//else							// ask for a specific one
						//{
							//aDataSet.data = alphaDisplay.content[aDataSet.index-1];
							//serialport_writeCarriage(&aDataSet);
						//}
						break;
						
					case 81:						// display screens
						//if (aDataSet.index == 0)		// ask for all of them
						//{
							//for (i=0;i<31;i++)
							//{
								//aDataSet.index = i+1;
								//aDataSet.data = alphaDisplay.screen[i];
								//serialport_writeCarriage(&aDataSet);
							//}
						//}
						//else							// ask for a specific one
						//{
							//aDataSet.data = alphaDisplay.screen[aDataSet.index-1];
							//serialport_writeCarriage(&aDataSet);
						//}
						break;
					
				}				
			}
		
									
		}	
		
    }		// while(1) end
}			// main end
Exemplo n.º 24
0
int main(int argc, char *argv[])
{
	int sd = -1;
	char *conf_file = NULL;
	struct mosquitto *mosq;
	struct module *md;
	struct device *dev;
	int rc;
	int i;
	
	if (!quiet) printf("Version: %s\n", version);

    signal(SIGINT, handle_signal);
    signal(SIGTERM, handle_signal);
	signal(SIGUSR1, handle_signal);
	signal(SIGUSR2, handle_signal);
	signal(SIGALRM, each_sec);
	
	for (i=1; i<argc; i++) {
		if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--config")){
			if(i==argc-1){
                fprintf(stderr, "Error: -c argument given but no file specified.\n\n");
				print_usage(argv[0]);
                return 1;
            }else{
				conf_file = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "--quiet")){
				quiet = true;
		}else{
				fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]);
				print_usage(argv[0]);
				return 1;
		}
	}
	
	if(!conf_file) {
		fprintf(stderr, "Error: No config file given.\n");
		return 1;
	}

	memset(&config, 0, sizeof(struct bridge_config));
	if(config_parse(conf_file, &config)) return 1;
	
	if (quiet) config.debug = 0;
	if (config.debug != 0) printf("Debug: %d\n", config.debug);

	if (!device_isValid_id(config.id)) {
		fprintf(stderr, "Invalid id.\n");
		return -1;
	}
	if (device_init(&bridge, config.id) == -1)
		return 1;

	mosquitto_lib_init();
	mosq = mosquitto_new(config.id, true, NULL);
	if(!mosq){
		fprintf(stderr, "Error creating mqtt instance.\n");
		switch(errno){
			case ENOMEM:
				fprintf(stderr, " out of memory.\n");
				break;
			case EINVAL:
				fprintf(stderr, " invalid id.\n");
				break;
		}
		return 1;
	}
	snprintf(gbuf, GBUF_SIZE, "%d", PROTO_ST_TIMEOUT);
	mosquitto_will_set(mosq, bridge.status_topic, strlen(gbuf), gbuf, config.mqtt_qos, MQTT_RETAIN);
	mosquitto_connect_callback_set(mosq, on_mqtt_connect);
	mosquitto_disconnect_callback_set(mosq, on_mqtt_disconnect);
	mosquitto_message_callback_set(mosq, on_mqtt_message);
	mosquitto_user_data_set(mosq, &sd);

	if (config.debug > 1) printf("Subscribe topic: %s\n", bridge.config_topic);

	rc = device_add_module(&bridge, MODULE_MQTT_ID, bridge.id);				//TODO: autogen id?
	if (rc) {
		fprintf(stderr, "Failed to add mqtt module.\n");
		return 1;
	}

	if (config.scripts_folder) {
		if (access(config.scripts_folder, R_OK )) {
			fprintf(stderr, "Couldn't open scripts folder: %s\n", config.scripts_folder);
			return 1;
		}
		rc = device_add_module(&bridge, MODULE_SCRIPT_ID, bridge.id);		//TODO: autogen id?
		if (rc) {
			fprintf(stderr, "Failed to add script module.\n");
			return 1;
		}
	}
	if (config.interface) {
		//TODO: check if interface exists
		if (access("/proc/net/dev", R_OK )) {
			fprintf(stderr, "Couldn't open /proc/net/dev\n");
			return 1;
		}
		rc = device_add_module(&bridge, MODULE_BANDWIDTH_ID, bridge.id);		//TODO: autogen id?
		if (rc) {
			fprintf(stderr, "Failed to add bandwidth module.\n");
			return 1;
		}
		bandwidth = true;
	}
	if (config.serial.port) {
		sd = serialport_init(config.serial.port, config.serial.baudrate);
		if( sd == -1 ) {
			fprintf(stderr, "Couldn't open serial port.\n");
			return 1;
		} else {
			rc = device_add_module(&bridge, MODULE_SERIAL_ID, bridge.id);		//TODO: autogen id?
			if (rc) {
				fprintf(stderr, "Failed to add serial module.\n");
				return 1;
			}
			serialport_flush(sd);
			bridge.serial_ready = true;

			if (config.debug) printf("Serial ready.\n");
		}
	}

	rc = device_add_module(&bridge, MODULE_SIGUSR1_ID, bridge.id);			//TODO: autogen id?
	if (rc) {
		fprintf(stderr, "Failed to add sigusr1 module.\n");
		return 1;
	}

	rc = device_add_module(&bridge, MODULE_SIGUSR2_ID, bridge.id);			//TODO: autogen id?
	if (rc) {
		fprintf(stderr, "Failed to add sigusr2 module.\n");
		return 1;
	}

	device_print_modules(&bridge);

	rc = mosquitto_connect(mosq, config.mqtt_host, config.mqtt_port, 60);
	if (rc) {
		fprintf(stderr, "Wrong MQTT parameters. Check your config.\n");
		return -1;
	}

	alarm(1);

	while (run) {
		if (bridge.serial_ready) {
			rc = serial_in(sd, mosq, MODULE_SERIAL_ID);
			if (rc == -1) {
				serial_hang(mosq);
			} else if (rc > 0) {
				bridge.serial_alive = ALIVE_CNT;
			}
		}

		if (user_signal) {
			if (config.debug > 1) printf("Signal - SIGUSR: %d\n", user_signal);
			signal_usr(sd, mosq);
		}

		rc = mosquitto_loop(mosq, -1, 1);
		if (run && rc) {
			if (config.debug > 2) printf("MQTT loop: %s\n", mosquitto_strerror(rc));
			usleep(100000);	// wait 100 msec
			mosquitto_reconnect(mosq);
		}

		if (every30s) {
			every30s = false;

			bridge.controller = false;
			for (i = 0; i < bridge.devices_len; i++) {
				dev = &bridge.devices[i];
				if (dev->alive) {
					dev->alive--;
					if (!dev->alive) {
						snprintf(gbuf, GBUF_SIZE, "%d,%s", PROTO_ST_TIMEOUT, dev->id);
						mqtt_publish(mosq, bridge.status_topic, gbuf);

						if (dev->md_deps->type == MODULE_MQTT && dev->type == DEVICE_TYPE_NODE) {
							snprintf(gbuf, GBUF_SIZE, "status/%s", dev->id);
							rc = mosquitto_unsubscribe(mosq, NULL, gbuf);
							if (rc)
								fprintf(stderr, "Error: MQTT unsubscribe returned: %s\n", mosquitto_strerror(rc));
						}

						if (config.debug) printf("Device timeout - id: %s\n", dev->id);
					} else {
						if (dev->type == DEVICE_TYPE_CONTROLLER)
							bridge.controller = true;
					}
				}
			}

			if (!bridge.controller)
				bridge.modules_update = false;

			if (connected) {
				snprintf(gbuf, GBUF_SIZE, "%d,%d", PROTO_ST_ALIVE, bridge.modules_len);
				mqtt_publish(mosq, bridge.status_topic, gbuf);

				if (bridge.modules_update) {
					snprintf(gbuf, GBUF_SIZE, "%d", PROTO_ST_MODULES_UP);
					if (mqtt_publish(mosq, bridge.status_topic, gbuf))
						bridge.modules_update = false;
				}

				if (bandwidth) {
					md = device_get_module(&bridge, MODULE_BANDWIDTH_ID);
					if (md) {
						if (mqtt_publish_bandwidth(mosq, md->topic) == -1)
							break;
					}
				}
			} else {
				if (config.debug != 0) printf("MQTT Offline.\n");
			}

			if (bridge.serial_alive) {
				bridge.serial_alive--;
				if (!bridge.serial_alive) {
					if (config.debug > 1) printf("Serial timeout.\n");
					serial_hang(mosq);
				}
			} else {
				if (config.serial.port && !bridge.serial_ready) {
					if (config.debug > 1) printf("Trying to reconnect serial port.\n");
					serialport_close(sd);
					sd = serialport_init(config.serial.port, config.serial.baudrate);
					if( sd == -1 )
						fprintf(stderr, "Couldn't open serial port.\n");
					else {
						serialport_flush(sd);
						bridge.serial_ready = true;
						if (config.debug) printf("Serial reopened.\n");
					}
				}
			}
		}
		usleep(20);
	}

	if (bridge.serial_ready) {
		serialport_close(sd);
	}

	mosquitto_destroy(mosq);

	mosquitto_lib_cleanup();
	config_cleanup(&config);

	printf("Exiting..\n\n");

	return 0;
}
void main(void)
{

    int fd, Error;
    int baud = 9600;
    char serialport[] = "/dev/ttyACM0";

    union uuFreq {
        char fBytes[4];
        float fFloat;
    } uFreq;
    uFreq.fFloat = 50.00;

    union uuTime {
        char tBytes[4];
        unsigned long tLong;
    } uTime;
    uTime.tLong = 5000;

    union uuChannel {
       char cBytes[2]; 
       unsigned int cInt;
    } uChannel;
    uChannel.cInt = 1;

    fd = serialport_init(serialport, baud);
    Error = serialport_flush(fd);


    // Loop through several times then send song over

    for (int i = 0; i < 71; i++)
    {
    if (i == 70) 
    {
        uFreq.fFloat = 0xFFFFFFFF;
        uTime.tLong = 0xFFFF;
        uChannel.cInt = 0xFF;
    }

    // Send Frequency - incremented by 20
    uFreq.fFloat = uFreq.fFloat + 20.0;
    Error = serialport_writebyte(fd, uFreq.fBytes[0]);
    tcdrain(fd);
    Error = serialport_writebyte(fd, uFreq.fBytes[1]);
    tcdrain(fd);
    Error = serialport_writebyte(fd, uFreq.fBytes[2]);
    tcdrain(fd);
    Error = serialport_writebyte(fd, uFreq.fBytes[3]);
    tcdrain(fd);

    // Send Time - incremented by 500 ms
    uTime.tLong = uTime.tLong + 500;
    Error = serialport_writebyte(fd, uTime.tBytes[0]);
    tcdrain(fd);
    Error = serialport_writebyte(fd, uTime.tBytes[1]);
    tcdrain(fd);
    Error = serialport_writebyte(fd, uTime.tBytes[2]);
    tcdrain(fd);
    Error = serialport_writebyte(fd, uTime.tBytes[3]);
    tcdrain(fd);

    // Send Channel
    Error = serialport_writebyte(fd, uChannel.cBytes[0]);
    tcdrain(fd);
    Error = serialport_writebyte(fd, uChannel.cBytes[1]);
    tcdrain(fd);

    // Send \0
    Error = serialport_writebyte(fd, '\0');
    
    usleep(50000);
    tcdrain(fd);
    }


    serialport_close(fd);


//return 0;
}
int main(int argc, char **argv) {
	char serialport[256];
    int n;

    if (argc==1) {
        exit(EXIT_SUCCESS);
    }

    // Parse options from the command line.
    int option_index = 0, opt;
    static struct option loptions[] = {
    	{"port", required_argument, 0, 'p'},		// Command line for setting port: -p /dev/tty.usbmodem####
	    {"delay", required_argument, 0, 'd'}		// Command line for zero delay: -d 0
	};

    while(1) {
    	opt = getopt_long(argc, argv, "hp:b:s:rn:d:", loptions, &option_index);
    	if (opt==-1) break;
    	switch (opt) {
			case '0': break;
	        case 'd':
	            n = strtol(optarg,NULL,10);
	            usleep(n * 1000); 									// Delay (sleep in milliseconds).
	            break;
	        case 'p':
	            strcpy(serialport,optarg);
	            fd = serialport_init(optarg, baudrate);
	            if(fd==-1) return -1;
	            break;
    	}
    }
	
	// Opens MATLAB engine, creates matrices & pointers for visual and timing samples.
	ep = engOpen(NULL);
	cppVisualSamples = mxCreateDoubleMatrix(numberOfSamples, 1, mxREAL);
	cppTimingSamples = mxCreateDoubleMatrix(numberOfSamples, 1, mxREAL);
	dataSetVisual = mxGetPr(cppVisualSamples);
	dataSetTiming = mxGetPr(cppTimingSamples);
    glutInit(&argc,argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowSize(window_width,window_height);					// Window size (in pixels).
	glutInitWindowPosition(100,100);								// Window position (from upper left).
	glutCreateWindow("Torquometer Visual Field");					// Window title.
	init();
	glutKeyboardFunc(myKeyboardFunc);								// Handles "normal" ascii symbols (letters).
	glutSpecialFunc(mySpecialKeyFunc);								// Handles "special" keyboard keys (up, down).
	glutDisplayFunc(display);										// Default display mode.
	glutIdleFunc(idleDisplay);										// Used with glutSwapBuffers();
	glEnable(GL_DEPTH_TEST);
	//glEnable(GL_TEXTURE_2D);
	makeCheckImage();												// Generates the gradient pattern in the background.
	glGenTextures(1, &texName);
	glBindTexture(GL_TEXTURE_2D, texName);
	//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, checkImageWidth, checkImageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage);
	glutMainLoop();
}
Exemplo n.º 27
0
int main(int argc, char *argv[])
{
	int sd = -1;
	char *conf_file = NULL;
	struct mosquitto *mosq;
	struct module *md;
	struct device *dev;
	int rc;
	int i;
	
	gbuf[0] = 0;

	if (!quiet) printf("Version: %s\n", version);

    signal(SIGINT, handle_signal);
    signal(SIGTERM, handle_signal);
	signal(SIGUSR1, handle_signal);
	signal(SIGUSR2, handle_signal);
	signal(SIGALRM, each_sec);
	
	for (i=1; i<argc; i++) {
		if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--config")){
			if(i==argc-1){
                fprintf(stderr, "Error: -c argument given but no file specified.\n\n");
				print_usage(argv[0]);
                return 1;
            }else{
				conf_file = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "--quiet")){
				quiet = true;
		}else{
				fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]);
				print_usage(argv[0]);
				return 1;
		}
	}
	
	if (!conf_file) {
		fprintf(stderr, "Error: No config file given.\n");
		return 1;
	}

	memset(&config, 0, sizeof(struct bridge_config));
	if (config_parse(conf_file, &config)) return 1;
	
	if (quiet) config.debug = 0;
	if (config.debug != 0) printf("Debug: %d\n", config.debug);

	rc = bridge_init(&bridge, config.id, MODULES_BRIDGE_ID);
	if (rc) {
		if (config.debug) printf("Error: Failed to initialize bridge: %d\n", rc);
		return 1;
	}

	mosquitto_lib_init();
	mosq = mosquitto_new(config.id, true, NULL);
	if(!mosq){
		fprintf(stderr, "Error creating mqtt instance.\n");
		switch(errno){
			case ENOMEM:
				fprintf(stderr, " out of memory.\n");
				break;
			case EINVAL:
				fprintf(stderr, " invalid id.\n");
				break;
		}
		return 1;
	}
	snprintf(gbuf, GBUF_SIZE, "%d", PROTOCOL_TIMEOUT);
	mosquitto_will_set(mosq, bridge.bridge_dev->status_topic, strlen(gbuf), gbuf, config.mqtt_qos, MQTT_RETAIN);

	mosquitto_connect_callback_set(mosq, on_mqtt_connect);
	mosquitto_disconnect_callback_set(mosq, on_mqtt_disconnect);
	mosquitto_message_callback_set(mosq, on_mqtt_message);
	mosquitto_user_data_set(mosq, &sd);

	md = bridge_add_module(bridge.bridge_dev, MODULES_MQTT_ID, true);
	if (!md) {
		fprintf(stderr, "Failed to add MQTT module.\n");
		return 1;
	}

	if (config.scripts_folder) {
		if (access(config.scripts_folder, R_OK )) {
			fprintf(stderr, "Couldn't open scripts folder: %s\n", config.scripts_folder);
			return 1;
		}
		md = bridge_add_module(bridge.bridge_dev, MODULES_SCRIPT_ID, true);
		if (!md) {
			fprintf(stderr, "Failed to add script module.\n");
			return 1;
		}
	}

	if (config.interface) {
		//TODO: check if interface exists
		if (access("/proc/net/dev", R_OK )) {
			fprintf(stderr, "Couldn't open /proc/net/dev\n");
			return 1;
		}
		md = bridge_add_module(bridge.bridge_dev, MODULES_BANDWIDTH_ID, true);
		if (!md) {
			fprintf(stderr, "Failed to add bandwidth module.\n");
			return 1;
		}
		bandwidth = true;
	}

	if (config.serial.port) {
		sd = serialport_init(config.serial.port, config.serial.baudrate);
		if( sd == -1 ) {
			fprintf(stderr, "Couldn't open serial port.\n");
			return 1;
		} else {
			md = bridge_add_module(bridge.bridge_dev, MODULES_SERIAL_ID, true);
			if (!md) {
				fprintf(stderr, "Failed to add serial module.\n");
				return 1;
			}
			serialport_flush(sd);
			bridge.serial_ready = true;

			if (config.debug) printf("Serial ready.\n");
		}
	}

	if (config.debug > 2) bridge_print_modules(bridge.bridge_dev);

	rc = mosquitto_connect(mosq, config.mqtt_host, config.mqtt_port, 60);
	if (rc) {
		fprintf(stderr, "ERROR: %s\n", mosquitto_strerror(rc));
		return -1;
	}

	alarm(1);

	while (run) {
		if (bridge.serial_ready) {
			rc = serial_in(sd, mosq, MODULES_SERIAL_ID);
			if (rc == -1) {
				serial_hang(mosq);
			} else if (rc > 0) {
				bridge.serial_alive = DEVICE_ALIVE_MAX;
			}
		}

		if (user_signal) {
			if (config.debug > 2) printf("Signal - SIGUSR: %d\n", user_signal);
			signal_usr(sd, mosq);
		}

		rc = mosquitto_loop(mosq, 100, 1);
		if (run && rc) {
			if (config.debug > 2) printf("MQTT loop: %s\n", mosquitto_strerror(rc));
			usleep(100000);	// wait 100 msec
			mosquitto_reconnect(mosq);
		}
		usleep(20);

		if (every1s) {
			every1s = false;

			for (dev = bridge.dev_list; dev != NULL; dev = dev->next) {
				if (dev->alive) {
					dev->alive--;
					if (!dev->alive) {
						if (connected) {
							snprintf(gbuf, GBUF_SIZE, "%d", PROTOCOL_TIMEOUT);
							mqtt_publish(mosq, dev->status_topic, gbuf);
							rc = mosquitto_unsubscribe(mosq, NULL, dev->config_topic);
							if (rc)
								fprintf(stderr, "Error: MQTT unsubscribe returned: %s\n", mosquitto_strerror(rc));
						}
						if (config.debug) printf("Device: %s - Timeout.\n", dev->id);
						bridge_remove_device(&bridge, dev->id);
					}
				}
			}
		}

		if (every30s) {
			every30s = false;

			if (connected) {
				send_alive(mosq);

				if (bandwidth) {
					md = bridge_get_module(bridge.bridge_dev, MODULES_BANDWIDTH_ID);
					if (md) {
						snprintf(gbuf, GBUF_SIZE, "%.0f,%.0f", upspeed, downspeed);
						mqtt_publish(mosq, md->topic, gbuf);
						if (config.debug > 2) printf("down: %f - up: %f\n", downspeed, upspeed);
					}
				}
			} else {
				if (config.debug) printf("MQTT Offline.\n");
			}

			if (bridge.serial_alive) {
				bridge.serial_alive--;
				if (!bridge.serial_alive) {
					if (config.debug > 1) printf("Serial timeout.\n");
					serial_hang(mosq);
				}
			} else {
				if (config.serial.port && !bridge.serial_ready) {
					if (config.debug > 1) printf("Trying to reconnect serial port.\n");
					serialport_close(sd);
					sd = serialport_init(config.serial.port, config.serial.baudrate);
					if( sd == -1 ) {
						fprintf(stderr, "Couldn't open serial port.\n");
					} else {
						serialport_flush(sd);
						bridge.serial_ready = true;
						snprintf(gbuf, GBUF_SIZE, "%d", MODULES_SERIAL_OPEN);
						mqtt_publish(mosq, md->topic, gbuf);
						if (config.debug) printf("Serial reopened.\n");
					}
				}
			}
		}
	}

	if (bridge.serial_ready) {
		serialport_close(sd);
	}

	mosquitto_destroy(mosq);

	mosquitto_lib_cleanup();
	config_cleanup(&config);

	printf("Exiting..\n\n");

	return 0;
}
Exemplo n.º 28
0
/*---------------------------------------------------------------------------*/
int main(int argc, char**argv)
{
	int i;
	int fd = 0;
	uint16_t trial = 0;
	char* portPath = NULL;
	char* rx_addressString = NULL;
	char* tx_addressString = NULL;

	printf("> Simple message listener for tea-bootloader compatible nodes\n");        
	
	/*-----------------------------------------------------------------------*/
	
	if(argc == 4)
	{
		portPath = argv[1];		
		rx_addressString = argv[2];
		sscanf(rx_addressString,"%X:%X:%X:%X:%X",rx_addressBuffer,rx_addressBuffer+1,rx_addressBuffer+2,rx_addressBuffer+3,rx_addressBuffer+4);
		tx_addressString = argv[3];
		sscanf(tx_addressString,"%X:%X:%X:%X:%X",tx_addressBuffer,tx_addressBuffer+1,tx_addressBuffer+2,tx_addressBuffer+3,tx_addressBuffer+4);
	}
	else
	{
		printf("> Argument parsing error!\n");
		printf("> Usage: [port path] [dongle RX address] [node RX address]\n");
		printf("> Example: ./main /dev/tty.usbserial-A900cbrd 0xE7:0xE7:0xE7:0xE7:0x00 0xD7:0xD7:0xD7:0xD7:0xD7\n");
		return 0;
	}			

	/*-----------------------------------------------------------------------*/	   

    fd = serialport_init(portPath,115200,'n');

    if(fd < 0)
    {
        printf("[err]: Connection error.\n");
        return 0;
    }
    else
   	{
        printf("> Conection OK.\n");
        serialport_flush(fd);
        printf("> Serial port flush OK.\n");   

        if(loopbackTest(fd) != 0)
        {
        	printf("> Loopback test failed!\r\n");
        	return 0;
        }
        else
        {        	
        	uint8_t version = getVersion(fd);
        	printf("> Dongle version: %d.%d\r\n",(version>>4),(version&0x0F));
        }                    
    }   

    printf("> Setting the TX address ...\n");
    setTXAddress(fd,tx_addressBuffer);

    printf("> Setting the RX address ...\n");
    setRXAddress(fd,rx_addressBuffer);

    while(1)
    {
    	uint8_t thisBuffer[1024];
    	char sendBuffer[256];
    	uint8_t len;
    	int temp;
    	float realval;
    	if(getRxFifoCount(fd))
    	{
			len = getRxFifoCount(fd);
			printf("> ---------------------------------------------------------------------------\n");
			printf("> New message!\n");
			printf("> Length: %d\n",len);
			pullDataFromFifo(fd,len,thisBuffer);

			hexDump("> Dump",thisBuffer,len);			

			temp = (thisBuffer[0]<<8)+thisBuffer[1];
			realval  = ((float)temp * 1100.0) / 1024.0;              
			realval -= 500;
			realval /= 10.0;

			printf("> Raw: %d\n",temp);
			printf("> Readout: %f\n",realval);
			sprintf(sendBuffer,"./phant_client.rb %f",realval);
			system(sendBuffer);
			printf("> Phant.io send process done.\n");
    	}
    }


}
Exemplo n.º 29
0
Arquivo: hand.c Projeto: donghee/hand
int main(void)
{
    modbus_t *ctx;
    int i;
    uint16_t tab_reg[64];

    int rc;
    uint16_t b[3] = {0x6101, 0x0fa0, 0x0fa0};
    
    int fd =0;
    char buf[256];
    char value;

    ctx = modbus_new_rtu("/dev/ttyUSB0", 38400, 'N', 8, 1);
    modbus_set_slave(ctx, SERVER_ID); // 엄지 선택
	modbus_set_debug(ctx, 1);

    if (modbus_connect(ctx) == -1) {
        fprintf(stderr, "Connection failed: %s\n",
                modbus_strerror(errno));
        modbus_free(ctx);
        return -1;
    }

    usleep(15000);
    x_axis_stop(ctx);

    // Arduino init
    fd = serialport_init("/dev/ttyUSB1", 9600);
    
    while (1)
        {
            value = serialport_read(fd);
            if (value != -1) {
                printf("From arduino: %d \n",value);
            }
            usleep(1500);

            switch (value) {
            case 1:
                printf("엄지 선택\n");
                modbus_set_slave(ctx, 1);
                break;
            case 2:
                printf("검지 선택 \n");
                modbus_set_slave(ctx, 2);
                break;
            case 3:
                printf("중지 선택\n");
                modbus_set_slave(ctx, 3);
                break;

            case 4:
                printf("약지 선택\n");
                modbus_set_slave(ctx, 4);
                break;

            case 5:
                printf("약지 선택\n");
                modbus_set_slave(ctx, 5);
                break;
                
            case 'b' :
                printf("b\n");
                x_axis_stop(ctx);
                x_axis_turn_right(ctx);
                break;
            case 'f' :
                printf("f\n");
                x_axis_stop(ctx);
                x_axis_turn_left(ctx);            
                break;                
            }
        }
    
    x_axis_stop(ctx);

    /* Close the connection */
    modbus_close(ctx);
    modbus_free(ctx);

    return 0;
}
Exemplo n.º 30
0
ModCom::ModCom(void) {
	assigned = 0;
	dd = "";
	char ttyport[33];
	char *serial_name;
	vector<string>::iterator redodev;

	// Search ttyUSB_'N' serial devices
	for(int n = 0; n < 10; n++){
		sprintf(ttyport, "/dev/ttyUSB%d", n);   
		serial_name = strdup(ttyport);
		fd = serialport_init(serial_name, 9600);
		if (fd != -1){
			redodev = find(devDescriptionList.begin(), devDescriptionList.end(), string(ttyport));
			if (redodev == devDescriptionList.end() || devDescriptionList.size() == 0) {
				if (this->checkdev()){
					dd = string(ttyport);
					devDescriptionList.push_back(string(ttyport));
					assigned = 1;
					return;
				}
			}
		}
		serialport_close(fd);
	}

	// Search ttyACM_'N' arduino serial devices
	for(int n = 0; n < 10; n++){
		sprintf(ttyport, "/dev/ttyACM%d", n);  
		serial_name = strdup(ttyport);
		fd = serialport_init(serial_name, 9600);
		if (fd != -1){
			redodev = find(devDescriptionList.begin(), devDescriptionList.end(), string(ttyport));
			if (redodev == devDescriptionList.end() || devDescriptionList.size() == 0) {
				if (this->checkdev()){
					dd = string(ttyport);
					devDescriptionList.push_back(string(ttyport));
					assigned = 1;
					return;
				}
			}
		}
		serialport_close(fd);
	}

	// Search rfcomm_'N' arduino bluetooth devices
	for(int n = 0; n < 10; n++){
		sprintf(ttyport, "/dev/rfcomm%d", n);  
		serial_name = strdup(ttyport);
		fd = serialport_init(serial_name, 9600);
		if (fd != -1){
			redodev = find(devDescriptionList.begin(), devDescriptionList.end(), string(ttyport));
			if (redodev == devDescriptionList.end() || devDescriptionList.size() == 0) {
				if (this->checkdev()){
					dd = string(ttyport);
					devDescriptionList.push_back(string(ttyport));
					assigned = 1;
					return;
				}
			}
		}
		serialport_close(fd);
	}
}