static void *callback(enum mg_event event, struct mg_connection *conn, const struct mg_request_info *request_info) { const int buf_max = 1000; char result[buf_max] = "none"; if (event == MG_NEW_REQUEST) { //const char* uri = request_info->uri; // get query args char cmd[32]; char timeoutStr[5]; int timeout; char str[256]; get_qsvar(request_info, "cmd", cmd, sizeof(cmd)); get_qsvar(request_info, "str", str, sizeof(str)); get_qsvar(request_info, "timeout", timeoutStr, sizeof(timeoutStr)); timeout = timeoutStr[0] == '\0' ? 5000 : atoi(timeoutStr); if( ! cmd[0] ) { // cmd is empty /// do something useful here } else { if( strcasecmp(cmd, "read")==0 ) { serialport_flush(fd); serialport_read_until(fd, str, '\n', buf_max, timeout); sprintf(result, "read:\n%s\n",str); // debug } else if( strcasecmp(cmd, "send")==0 ) { serialport_write(fd, str); sprintf(result, "send:\n%s\n",str); } else if( strcasecmp(cmd, "sendline")==0 ) { sprintf(str, "%s\r\n ", str); serialport_write(fd, str); sprintf(result, "sendline:\n%s",str); } else { sprintf(result, "uknown cmd '%s'",cmd); } } printf("result:%s\n",result); // Echo requested URI back to the client mg_printf(conn, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n\r\n" "%s" "\n", result ); return ""; // Mark as processed } else { return NULL; } }
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; }
int readSerial(int fd, char *buf, int buf_max, int timeout) { char eolchar = '\n'; int sr = serialport_read_until(fd, buf, eolchar, buf_max, timeout); if(buf[0] != eolchar) DBG("DEBUG:\t%s", buf); return sr; };
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(); } }
int ReadRX(ServoStates* st){ int retVal = 0; short* a = st->Angle; char buf[128]; if(retVal = serialport_read_until(USB, buf, '\n', 128, 1000)){ sscanf(buf, "%d,%d,%d,%d,%d,%d,%d,%d", &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6], &a[7] ); //printf("%s\n", buf); return retVal; } return -1; }
void getTextFromSerial(gchar* text) { char buf[BUF_MAX]; char timeText[BUF_MAX*2]; char eolchar = '\n'; memset(buf,0,BUF_MAX); serialport_read_until(fd, buf, eolchar, BUF_MAX, 5000); #ifdef DEBUG printf("Value from serial %s\n", buf); #endif if (buf[0] != '\0' && buf[0] != '\n') { time_t now; memset(timeText,0,BUF_MAX*2); now = time(NULL); strftime(timeText, sizeof(timeText), "T:%Y-%m-%d %H:%M:%S ", localtime(&now)); strcat(timeText,buf); strcpy(text,timeText); } }
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
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; }
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
int serial_in(int sd, struct mosquitto *mosq, char *md_id) { static char serial_buf[SERIAL_MAX_BUF]; static int buf_len = 0; char *buf_p; char id[DEVICE_ID_SIZE + 1]; struct device *dev; int rc, sread; if (buf_len) buf_p = &serial_buf[buf_len - 1]; else buf_p = &serial_buf[0]; sread = serialport_read_until(sd, buf_p, eolchar, SERIAL_MAX_BUF - buf_len, config.serial.timeout); if (sread == -1) { fprintf(stderr, "Serial - Read Error.\n"); return -1; } if (sread == 0) return 0; buf_len += sread; if (serial_buf[buf_len - 1] == eolchar) { serial_buf[buf_len - 1] = 0; //replace eolchar buf_len--; // eolchar was counted, decreasing 1 if (config.debug > 3) printf("Serial - size:%d, serial_buf:%s\n", buf_len, serial_buf); if (buf_len < SERIAL_INIT_LEN) { // We need at least SERIAL_INIT_LEN to count as a valid command if (config.debug > 1) printf("Invalid serial input.\n"); buf_len = 0; return 0; } sread = buf_len; // for return buf_len = 0; // reseting for the next input buf_p = &serial_buf[SERIAL_INIT_LEN]; // Serial debug if (!strncmp(serial_buf, SERIAL_INIT_DEBUG, SERIAL_INIT_LEN)) { if (config.debug) { printf("Device Debug: %s\n", buf_p); snprintf(gbuf, GBUF_SIZE, "%d,%s,%d,%s", PROTOCOL_MD_OPTIONS, MODULES_BRIDGE_ID, MODULES_BRIDGE_DEBUG, buf_p); mqtt_publish(mosq, bridge.bridge_dev->status_topic, gbuf); } return sread; } else if ((!strncmp(serial_buf, SERIAL_INIT_STATUS, SERIAL_INIT_LEN)) || (!strncmp(serial_buf, SERIAL_INIT_CONFIG, SERIAL_INIT_LEN))) { if (config.debug > 2) printf("Serial IN - Message: %s\n", serial_buf); // Get device id from buf if (utils_getString(&buf_p, id, DEVICE_ID_SIZE, ',') != DEVICE_ID_SIZE) { if (config.debug > 1) printf("Serial - Error: %d\n", ERROR_MIS_DEVICE_ID); return 0; } if (!bridge_isValid_device_id(id)) { if (config.debug > 1) printf("Serial - Error: %d\n", ERROR_DEV_INV_ID); return 0; } dev = bridge_get_device(&bridge, id); if (!dev) { dev = bridge_add_device(&bridge, id, md_id); if (!dev) { if (config.debug > 1) printf("Serial - Failed to add device.\n"); return sread; } rc = mosquitto_subscribe(mosq, NULL, dev->config_topic, config.mqtt_qos); if (rc) { fprintf(stderr, "MQTT - Subscribe ERROR: %s\n", mosquitto_strerror(rc)); run = 0; return sread; } if (config.debug > 2) printf("Subscribe topic: %s\n", bridge.bridge_dev->config_topic); if (config.debug > 2) { printf("New device:\n"); bridge_print_device(dev); } } if (!strncmp(serial_buf, SERIAL_INIT_CONFIG, SERIAL_INIT_LEN)) { // Get device id from buf if (utils_getString(&buf_p, id, DEVICE_ID_SIZE, ',') != DEVICE_ID_SIZE) { if (config.debug > 1) printf("Serial - Error: %d\n", ERROR_MIS_DEVICE_ID); return 0; } if (!bridge_isValid_device_id(id)) { if (config.debug > 1) printf("Serial - Error: %d\n", ERROR_DEV_INV_ID); return 0; } device_config_to_mqtt(mosq, sd, dev, id, buf_p); } else { device_status_to_mqtt(mosq, sd, dev, buf_p); } } else { if (config.debug > 1) printf("Unknown serial data.\n"); } return sread; } else if (buf_len == SERIAL_MAX_BUF) { if (config.debug > 1) printf("Serial buffer full.\n"); buf_len = 0; } else { if (config.debug > 1) printf("Serial chunked.\n"); } return 0; }
int serial_in(int sd, struct mosquitto *mosq, char *md_id) { static char serial_buf[SERIAL_MAX_BUF]; static int buf_len = 0; char *buf_p; char id[DEVICE_ID_SIZE + 1]; struct device *dev; int rc, sread; if (buf_len) buf_p = &serial_buf[buf_len - 1]; else buf_p = &serial_buf[0]; sread = serialport_read_until(sd, buf_p, eolchar, SERIAL_MAX_BUF - buf_len, config.serial.timeout); if (sread == -1) { fprintf(stderr, "Serial - Read Error.\n"); return -1; } if (sread == 0) return 0; buf_len += sread; if (serial_buf[buf_len - 1] == eolchar) { serial_buf[buf_len - 1] = 0; //replace eolchar buf_len--; // eolchar was counted, decreasing 1 if (config.debug > 3) printf("Serial - size:%d, serial_buf:%s\n", buf_len, serial_buf); if (buf_len < SERIAL_INIT_LEN) { // We need at least SERIAL_INIT_LEN to count as a valid command if (config.debug > 1) printf("Invalid serial input.\n"); buf_len = 0; return 0; } sread = buf_len; // for return buf_len = 0; // reseting for the next input buf_p = &serial_buf[SERIAL_INIT_LEN]; // Serial debug if (!strncmp(serial_buf, SERIAL_INIT_DEBUG, SERIAL_INIT_LEN)) { if (config.debug) printf("Debug: %s\n", buf_p); return sread; } else if (!strncmp(serial_buf, SERIAL_INIT_MSG, SERIAL_INIT_LEN)) { if (config.debug > 2) printf("Serial - message: %s\n", serial_buf); if (getString(&buf_p, id, DEVICE_ID_SIZE, ',') != DEVICE_ID_SIZE) { if (config.debug > 1) printf("Serial - Invalid data.\n"); return 0; } if (!device_isValid_id(id)) { if (config.debug > 1) printf("Serial - Invalid device id.\n"); return 0; } dev = device_get(&bridge, id); if (!dev) { rc = device_load(&bridge, config.devices_folder, id); if (rc == -1) { run = 0; return sread; } if (rc) { rc = device_add_dev(&bridge, id, md_id); if (rc == -1) { run = 0; return sread; } if (rc) { if (config.debug > 2) printf("Serial - Failed to add device.\n"); return sread; } } dev = device_get(&bridge, id); if (config.debug > 1) { printf("New device:\n"); device_print_device(dev); } } else dev->alive = ALIVE_CNT; bridge_message(mosq, sd, dev, buf_p); } else { if (config.debug > 1) printf("Unknown serial data.\n"); } return sread; } else if (buf_len == SERIAL_MAX_BUF) { if (config.debug > 1) printf("Serial buffer full.\n"); buf_len = 0; } else { if (config.debug > 1) printf("Serial chunked.\n"); } return 0; }