Пример #1
0
int main(int argc, char *argv[])
{
	int ret;

	if (argc != 4) {
		printf("Usage: %s addr idx count\n", argv[0]);
		return 1;
	}

	int addr = atoi(argv[1]);
	int idx = atoi(argv[2]);
	int count = atoi(argv[3]);
	uint16_t values[256];

	ret = openSerial("/dev/ttyUSB0", 38400, 'N', 8, 1);
	if (ret) {
		perror("Cannot open serial");
		return ret;
	}

	ret = mbReadReg(addr, idx, count, values);
	if (ret != count) {
		perror("Cannot read register");
		return ret;
	}

	printf("Reading %i regs at %i from %i (%02x):\n", count, idx, addr, addr);
	for (int i=0; i<count; ++i)
		printf("%02x[%3i]=%04x (%i)\n", addr, idx+i, values[i], values[i]);

	closeSerial();
	return 0;
}
Пример #2
0
void CSerialPortReader::handleTimeout()
{
    if (!mSerial.isOpen())
    {
        openSerial();
    }
}
Пример #3
0
int main(void)
{
    joystick = initializeJoystick();
    serialPort = openSerial();
    
    printf("Joystick's file descriptor: %d\n\r", joystick.fd);
    printf("Serial port's file descriptor: %d\n\r", serialPort.fd);
    
    // Launch threads
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_t tids[4];
    
    pthread_create(&tids[0], &attr, joystickUpdater, NULL);
    pthread_create(&tids[1], &attr, serialReader, NULL);
    pthread_create(&tids[2], &attr, serialWriter, NULL);
    pthread_create(&tids[3], &attr, terminalWriter, NULL);
    
    for (int i = 0; i < 4; i++)
    {
        pthread_join(tids[i], NULL);
    }
    
    // Never reached because the threads run forever
    terminateJoystick(&joystick);
    closeSerial(&serialPort);
    
    return 0;
}
Пример #4
0
int main(int argc, char *argv[]){
	int fd;
	int ret;
	mic_type_t mt;
	
	if(argc < 2){
		printf("usage:%s 0/1\n",argv[0]);
		return -1;
	}
	mt = (mic_type_t) atoi(argv[1]);
	
	fd = openSerial();
	if (fd < 0){
		perror("Can't open "COM_DEV);
	}
	serial_init(fd, BAUDRATE);
	
	switch(mt){
	case PSTN_MIC:
		ret = write(fd, pstn_mic, 10);
		printf("Set PSTN MIC success %d\n", ret);
		break;
	case APC_MIC:
		ret = write(fd, apc_mic, 10);
		printf("Set APC MIC success %d\n", ret);
		break;
	default:
		printf("Mic type error\n");
		break;
	};
	
	close(fd);
	return 0;
}
Пример #5
0
void _mobileTest(void)
{
    int fd;
    INIT_DOT;
	INIT_ERROR;

    SUCC_DOT("Mobile Device Open");
    if((fd=openSerial("/dev/ttyS00", B9600, 0))<0) {
    	ADD_ERROR("Mobile Device Access Error (ECODE=%d)",errno);
        CLOSE_DOT;
        return;
    }

    SUCC_DOT("ATI"); if(_gsmtest(fd,"ATI\r\n", 4)) {ADD_ERROR("%s","Additional identifacation information");}
	SUCC_DOT("AT^SCID"); if(_gsmtest(fd,"AT^SCID\r\n", 9)) {ADD_ERROR("%s", "SIM card identifcation number");}
	SUCC_DOT("AT+CPIN?"); if(_gsmtest(fd,"AT+CPIN?\r\n", 10)) {ADD_ERROR("%s", "SIM PIN authentication");}
	SUCC_DOT("AT+CPIN2?"); if(_gsmtest(fd,"AT+CPIN2?\r\n", 11)) {ADD_ERROR("%s", "SIM PIN2 authentication");}
	SUCC_DOT("AT+CIMI"); if(_gsmtest(fd,"AT+CIMI\r\n", 9)) {ADD_ERROR("%s", "Request international mobile subscriber identity");}
	SUCC_DOT("AT+CCLK?"); if(_gsmtest(fd,"AT+CCLK?\r\n", 10)) {ADD_ERROR("%s", "Real Time Clock");}
	SUCC_DOT("AT+COPS?"); if(_gsmtest(fd,"AT+COPS?\r\n", 10)) {ADD_ERROR("%s", "Operator selection");}
	SUCC_DOT("AT+CREG?"); if(_gsmtest(fd,"AT+CREG?\r\n", 10)) {ADD_ERROR("%s", "Network registration");}
	SUCC_DOT("AT+CSQ"); if(_gsmtest(fd,"AT+CSQ\r\n", 8)) {ADD_ERROR("%s", "Signal quality");}
	SUCC_DOT("AT^SBV"); if(_gsmtest(fd,"AT^SBV\r\n", 8)) {ADD_ERROR("%s", "Monitoring power supply");}
	SUCC_DOT("GSM Module Voltage"); _gsmpowertest(fd,"AT^SBV\r\n", 8);
	SUCC_DOT("AT^MONI"); if(_gsmtest(fd,"AT^MONI\r\n", 9)) {ADD_ERROR("%s", "Monitor idle mode and dedicated mode");}
	SUCC_DOT("AT^MONP"); if(_gsmtest(fd,"AT^MONP\r\n", 9)) {ADD_ERROR("%s", "Monitor neighbour cells");}
	SUCC_DOT("AT^SMONC"); if(_gsmtest(fd,"AT^SMONC\r\n", 10)) {ADD_ERROR("%s", "Cell Monitoring");}
	SUCC_DOT("AT^SMONG"); if(_gsmtest(fd,"AT^SMONG\r\n", 10)) {ADD_ERROR("%s", "GPRS Monitor");}

    CLOSE_DOT;
    close(fd);
}
Пример #6
0
//打开串口并初始化设置  
int init_serial(char* device)
{
    if (openSerial(device) < 0) {
        perror("open error");
        return -1;
    }
    defaultConfigWithFd();
    return 0;
}
Пример #7
0
int main(int argc, char *argv[])
// arg1: serial device file
// arg2: optional timeout in seconds, default 60
// arg3: optional 'nolog' to carry on when filesystem full
{
    int commfd = 0;
	int option;                             // command line processing
	int baud = 9600;
	char * cp;
	char table[128];
	int flags = CS8 | CLOCAL | CREAD;
	
    char * serialName = SERIALNAME;
	
	memset(table, 0, 128);
	// Command line arguments
	
	init_table(table);
	opterr = 0;
	while ((option = getopt(argc, argv, "b:dVcs:?")) != -1) {
		DEBUG fprintf(stderr, "Option %c ", option);
		switch (option) {
			case 'b': baud = atoi(optarg); break;
			case 'c': flags |= CRTSCTS; break;
			case '?': usage(); exit(1);
			case 's': serialName = optarg; break;
			case 'd': debug++; break;
			case 'V': printf("Version: %s\n", VERSION); exit(0);
		}
	}
	
	// Open serial port
#ifdef DEBUGCOMMS
	commfd = 0;
#else
	if ((commfd = openSerial(serialName, baud, 0, flags, 1)) < 0) {
		fprintf(stderr, "ERROR 7seg Failed to open %s at %d: %s", serialName, baud, strerror(errno));
		exit(1);
	}
	
#endif
	DEBUG2 fprintf(stderr, "Serial port %s open ...", serialName);
	
	// Send data
	while (optind < argc) {		// remainder of command line must be bytes
		for (cp = argv[optind]; *cp; cp++) {
				DEBUG fprintf(stderr, "'%c' [%02x] ", *cp, table[*cp]);
			sendSerial(commfd, table[*cp]);
		}
		optind++;
	}
	DEBUG fprintf(stderr, "\n");
	
	closeSerial(commfd);
	
	return 0;
}
Пример #8
0
int main(int argc, char **argv)
{
	char *file;
	serial_t *serial;
	int count;
	char buf[128];
	char line[128];
	int linePos = 0;

	if(argc < 2) {
		fprintf(stderr, "Usage: %s tty\n", argv[0]);
		exit(1);
	}

	file = argv[1];

	if((serial = openSerial(file)) == NULL)
		exit(1);

	time_t lastTime = 0, currentTime;
	while(1) {
		time(&currentTime);
		if(currentTime >= lastTime + 60) {
			if(write(serial->fd, "D\n", 2) < 2) {
				perror("write()");
				closeSerial(serial);
				exit(1);
			}
			lastTime = currentTime;
		}
		fd_set rfds, wfds;
		FD_ZERO(&rfds);
		FD_ZERO(&wfds);
		FD_SET(serial->fd, &rfds);
		if((count = select(serial->fd+1, &rfds, NULL, NULL, NULL)) < 0) {
			perror("select()");
			closeSerial(serial);
			exit(1);
		//} else if(count == 0) {
		//	printf("Nothing.\n");
		}
		if((count = read(serial->fd, buf, sizeof(buf))) > 0) {
			int i = 0;
			while(linePos < sizeof(line)-1 && i < count) {
				line[linePos++] = buf[i++];
				if(line[linePos-1] == '\n') {
				}
			}
			write(1, buf, count);
		}
	}

	closeSerial(serial);

	exit(0);
}
Пример #9
0
Lidar::Lidar(Conf c){
  configuration = c;
  safeLength = configuration.data["pathfinding"]["lidar"]["safe_length"];
  rayMax = configuration.data["pathfinding"]["lidar"]["ray_maximum"];
  sweepAngle = configuration.data["pathfinding"]["lidar"]["sweep_angle"];
  threadContinue = true;
  pathfinding_serial_thread = thread([this]{
      openSerial();
      while(threadContinue){
        readAllInQueue();
      }
    });
}
Пример #10
0
// Entry point
int main(int argc, char *argv[])
{
    int serial;

    if ((serial = openSerial(argc, argv)) == -1) {
        fprintf(stderr, "Cannot open serial device: %s", argv[1]);
    } else {
        fprintf(stderr, "Serial port opened\n");
    }

    mainLoop(serial);

    return 0;
}
Пример #11
0
CSerialPortReader::CSerialPortReader(const CSerialPortConfig& config)
    : mSerial(this) //TODO: test it
    , mConfig(config)
    , mAlertConfig("serial_port", mConfig.mAlertCoef)
{
    mSerial.setPortName(config.mSerialPort);
    mSerial.setBaudRate(config.mBaudRate);
    const int TIMER_DEFAULT_INTERVAL = 5000;
    mTimer.setInterval(TIMER_DEFAULT_INTERVAL);
    openSerial();

    connect(&mTimer, SIGNAL(timeout()), this, SLOT(handleTimeout()));
    mTimer.start();
}
Пример #12
0
/* 主函数 */
int main(int argc, char *argv[])
{
    char tmp[1024] = "test uart!\r\n";
    char gpsbuf[1024];
    int len;
    int fd, i;
    gps_info_t stGpsInfo;
    int wrbufindex = 0;

    /* 打开串口 */
    fd = openSerial("/dev/ttySP0");
    if(0 > fd)
    {
        DEBUG_MSG("D:open uart error!\r\n");
        return -1;
    }
    write(fd, tmp, 16);
    /* */
    while(1)
    {
        len = read(fd, tmp, 0x01);
        for(i=0; i<len; i++)
        {
            //printf("%c", tmp[i]);
            if('\n' == tmp[i])
            {
                gpsbuf[wrbufindex] = '\n';
                wrbufindex++;
                if(1024 > wrbufindex)
                {
                    gpsbuf[wrbufindex] = '\0';
                    if(0 == gps_get_rmc(&stGpsInfo, gpsbuf))
                    {
                        print_gps_info(&stGpsInfo);
                    }
                }
                wrbufindex = 0;
            }
            else
            {
                gpsbuf[wrbufindex] = tmp[i];
                wrbufindex++;
                if(1024 <= wrbufindex)
                {
                    wrbufindex = 0;
                }
            }
        }
    }
}
Пример #13
0
void MiniBeeV2::begin(long baud_rate) {

	configXBee();
	delay(1000);

	openSerial(baud_rate);
// 	delay(200);

	readXBeeSerial();
	// allow some delay before sending data
// 	delay(500);

	sendSerialNumber();

	status = WAITFORHOST;
}
Пример #14
0
//Initialize
void init(){
	//Clear buffer
	unsigned char inBuff[BUFFER_MAX];
	int fd = openSerial();
	int receivedBytes;
	while( (receivedBytes = read(fd,inBuff,BUFFER_MAX)) ){
		if(receivedBytes && DEBUG) printf("Emptied buffer of %d bytes\n",receivedBytes);
	}
	clearString((char*)inBuff);
	usleep(100000);
	
	//Send wake up command to Arduino
	char buffHost[8] = ":wakeup:";
	int sentBytes = write(fd,buffHost,sizeof(buffHost));
	if(DEBUG) printf("%d bytes sent\n",sentBytes);
	usleep(100000);
	
	close(fd);
}
// Initialize Camera and Sensors
void initDevices(void) {
	struct pxacam_setting camset;
	
	// Backboard uart init
	fdBackBoard = openSerial();

	// 3-axis sensor init 
	fdThreeAxis = open("/dev/MMA_ADC", O_RDONLY);
	ASSERT(fdThreeAxis);

	ioctl(fdThreeAxis,MMA_VIN_ON, 0);
	ioctl(fdThreeAxis,MMA_SLEEP_MODE_ON, 0);
	ioctl(fdThreeAxis,MMA_SENS_60G, 0);

	// infrared sensor init
	fdInfra = open("/dev/FOUR_ADC", O_NOCTTY);
	ASSERT(fdInfra);

	// Camera init
	fdCamera = camera_open(NULL,0);
	ASSERT(fdCamera);

	memset(&camset,0,sizeof(camset));
	camset.mode = CAM_MODE_VIDEO;
	camset.format = pxavid_ycbcr422;

	camset.width = 320;
	camset.height = 240;

	camera_config(fdCamera,&camset);
	camera_start(fdCamera);

	fdOverlay2 = overlay2_open(NULL,pxavid_ycbcr422,NULL, 320, 240, 0 , 0);

	overlay2_getbuf(fdOverlay2, &vidbuf_overlay);
	len_vidbuf = vidbuf_overlay.width * vidbuf_overlay.height;

	cImg.width=camset.width*2;
	cImg.height=camset.height;

	// init finish
	printf("Initializing Device Finished\n");	
}
Пример #16
0
Файл: mw.c Проект: coder03/ldd
main(){
	int fd;
	struct termios *oldser,*newser,*oldter,*newter;
	oldser=(struct termios *)malloc(sizeof(struct termios));
	newser=(struct termios *)malloc(sizeof(struct termios));
	oldter=(struct termios *)malloc(sizeof(struct termios));
	newter=(struct termios *)malloc(sizeof(struct termios));
	fd=openSerial("/dev/ttyS1");
	setSerial(fd,oldser,newser);
	/* next stop echo and buffering for stdin */
 	tcgetattr(0,oldter);
 	tcgetattr(0,newter); /* get working stdtio */
 	newter->c_lflag &= ~(ICANON | ECHO);
 	tcsetattr(0,TCSANOW,newter);
	writeToSerial(fd,'x');
   	tcsetattr(fd,TCSANOW,oldser); /* restore old serial setings */
	close(fd);
   	tcsetattr(0,TCSANOW,oldter); /* restore old tty setings */
	exit(0);
}
Пример #17
0
// Initialize Camera and Sensors
void initDevices(void) {
	struct pxacam_setting camset;
	
	printf("-----Initializing Device Started-----\n");	
	
	// Backboard uart init
	fdBackBoard = openSerial();
	printf("Initializing BackBoard complete!\n");	
		
	// 적외선 센서 init
	fdInfra = open("/dev/FOUR_ADC", O_NOCTTY);
		
		
	// Camera init
	fdCamera = camera_open(NULL,0);
	ASSERT(fdCamera);

	system("echo b > /proc/invert/tb"); //LCD DriverIC top-bottom invert ctrl

	memset(&camset,0,sizeof(camset));
	camset.mode = CAM_MODE_VIDEO;
	camset.format = pxavid_ycbcr422;

	
	camset.width = MAX_X;
	camset.height = MAX_Y;

	camera_config(fdCamera,&camset);
	camera_start(fdCamera);

	fdOverlay2 = overlay2_open(NULL,pxavid_ycbcr422,NULL, MAX_X, MAX_Y, 0 , 0);

	overlay2_getbuf(fdOverlay2, &vidbuf_overlay);
	len_vidbuf = vidbuf_overlay.width * vidbuf_overlay.height;

	printf("Initializing Camera complete!\n");	
	
	// init finish
	printf("-----Initializing Device Finished-----\n");	
}
Пример #18
0
void openSerialAtDefaultSpeed(unsigned char serialPortIndex) {
    openSerial(serialPortIndex, DEFAULT_SERIAL_SPEED);
}
Пример #19
0
int main(int argc, char **argv)
{
	in_port_t port = DEFAULT_PORT;
	long baud = DEFAULT_BAUD;
	char dv3000tty[MAXPATHLEN] = DEFAULT_TTY;
	
	fd_set fds;
	int serialFd;
	int sockFd;
	int topFd;
	
	int c;

#ifdef __CYGWIN__
	int commnum;
#endif
	
	char reset = 0;
	char daemon = 0;

	setvbuf(stdout, NULL, _IOLBF, 0);
	setvbuf(stderr, NULL, _IOLBF, 0);

#ifdef __CYGWIN__
	while ((c = getopt(argc, argv, "dp:s:c:vxrh")) != -1) {
#else
	while ((c = getopt(argc, argv, "dp:s:i:vxrh")) != -1) {
#endif
		switch (c) {
			case 'd':
				daemon = 1;
				break;
			case 'p':
				errno = 0;
				port = strtol(optarg, NULL, 10);
				if(errno != 0 || port == 0) {
					fprintf(stderr, "Invalid port number: %s\n", optarg);
					usage();
				}
				break;
			case 's':
				errno = 0;
				baud = strtol(optarg, NULL, 10);
				if(errno != 0 || baud == 0) {
					fprintf(stderr, "Invalid baud rate: %s\n", optarg);
					usage();
				}
				break;
#ifdef __CYGWIN__
			case 'c':
				commnum = strtol(optarg, NULL, 10);
				sprintf(dv3000tty,"/dev/ttyS%d",commnum - 1);
				break;
#else
			case 'i':
				strncpy(dv3000tty, optarg, sizeof(dv3000tty));
				break;
#endif
			case 'v':
				fprintf(stdout, "AMBEserver: version " DV3000_VERSION "\n");
				return 0;
			case 'x':
				debug = 1;
				break;
			case 'r':
				reset = 1;
				break;
			case 'h':
			default:
				usage();
				break;
		}
	}
	
	if (strlen(dv3000tty) < 1) {
		fprintf(stderr, "An input tty filename (-i /dev/ttyXXX) must be set.\n");
		return 1;
	}

	if (daemon) {
		pid_t pid = fork();

		if (pid < 0) {
			fprintf(stderr, "AMBEserver: error in fork(), exiting\n");
			exit(1);
		}

		// If this is the parent, exit
		if (pid > 0)
			exit(0);

		// We are the child from here onwards
		setsid();

		umask(0);
	}

	fprintf(stdout, "AMBEserver: Starting...\n");

	serialFd = openSerial(dv3000tty, baud);
	if (serialFd < 0)
		exit(1);

	fprintf(stdout, "AMBEserver: Opened serial port %s at %ld bps.\n", dv3000tty, baud);
	
	if(initDV3K(serialFd, reset) == 0) {
		fprintf(stderr, "AMBEserver: Could not initialize the DV3K!\n");
		exit(1);
	}
	
	sockFd = openSocket(port);
	if (sockFd < 0)
		exit(1);

	fprintf(stdout, "AMBEserver: Listening for connections on UDP port %d.\n", port);
		
	topFd = (sockFd > serialFd ? sockFd : serialFd ) + 1;

	for (;;) {
		FD_ZERO(&fds);
		FD_SET(sockFd, &fds);
		FD_SET(serialFd, &fds);

		if (select(topFd, &fds, NULL, NULL, NULL) < 0) {
			fprintf(stderr, "AMBEserver: error from select: %s\n", strerror(errno));
			exit(1);
		}
		
		if(FD_ISSET(sockFd, &fds))
			if (!processSocket(sockFd, serialFd))
				exit(1);

		if(FD_ISSET(serialFd, &fds))
			if (!processSerial(sockFd, serialFd))
				exit(1);
	}

	exit(0);
}
Пример #20
0
//Main program
int main(void) {
	int receivedBytes;//, sentBytes;
	//unsigned char outBuff[BUFFER_MAX];
	unsigned char inBuff[BUFFER_MAX];
	//Reserve memory
	char* cmd = malloc((BUFFER_MAX+1) * sizeof(char));
	char* par = malloc((BUFFER_MAX+1) * sizeof(char));
	struct commandStructure command;
	
	//Threads variables
	pthread_t logThread;
	pthread_t emailThread;
	//pthread_t debugThread;
	pthread_t webcamThread;
	pthread_t emailPhotoThread;
	
	//Empty buffers
	init();
	
	// Open serial file descriptor
	int fd = openSerial();
		
	//Loop to scan
	while(1){
		receivedBytes = read(fd,inBuff,BUFFER_MAX);
		if(receivedBytes > 0){						// Data found!
			
			if(DEBUG){ 
				printf("\nPayload size: %d\n",receivedBytes);
				int i;
				for(i=0;i<receivedBytes;i++){
					printf("%c",inBuff[i]);
				}
				printf("\n");
			}

			getCmd(inBuff,cmd);
			getPar(inBuff,par);
			int pars = parseParameters(par);
			
			if(!validCommand(cmd)){
				printf("Invalid Command: %s\n\n",cmd);
				continue;
			}else{	
				//printf("Command: %s\n",cmd);
				//int i = 0;
				//printf("Parameters found: %d\n",pars);
				//for(i=0;i<pars;i++) printf("Parameter %d - %s\n",i,PARAMETERS[i]);			
			}
			
			if(compareText(cmd,"Debug")){ //thread is detached so resources can be recycled.
				command.cmd = cmd;
				command.par[0] = PARAMETERS[0];
				
				time_t now = time(NULL);
				printf("%s - %s",PARAMETERS[0],ctime(&now));

				/*
				//=======Call debugFunc in thread======
				int rc;
				pthread_attr_t attr;
				pthread_attr_init(&attr);
				pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
				
				if((rc = pthread_create(&debugThread,&attr,debugFunc,&command))){
					fprintf(stderr,"Error: Could not create thread: %d\n",rc);
				}
				
				pthread_attr_destroy(&attr);
				*/
			}

			if(compareText(cmd,"Log")){
				if(pars < 1){
					printf("Error: No message sent\n");
					continue;
				}
				command.cmd = cmd;
				command.par[0] = PARAMETERS[0];

				//=======Call logFunc in thread======
				int rc;
				pthread_attr_t attr;
				pthread_attr_init(&attr);
				pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
				
				if((rc = pthread_create(&logThread,&attr,logFunc,&command))){
					fprintf(stderr,"Error: Could not create thread: %d\n",rc);
				}
				
				pthread_attr_destroy(&attr);
			}
			
			if(compareText(cmd,"Email")){
				if(pars < 3){  //Need at least the email address and a subject
					printf("Error: Need 3 parameters: address, subject and message\n");
					continue;
				}
				
				command.cmd = cmd;
				command.par[0] = PARAMETERS[0];
				command.par[1] = PARAMETERS[1];
				command.par[2] = PARAMETERS[2];
				
				//=======Call logFunc in thread======
				int rc;
				pthread_attr_t attr;
				pthread_attr_init(&attr);
				pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
				
				if((rc = pthread_create(&emailThread,&attr,emailFunc,&command))){
					fprintf(stderr,"Error: Could not create thread: %d\n",rc);
				}
				
				pthread_attr_destroy(&attr);
			}
			
			if(compareText(cmd,"Webcam")){
				command.cmd = cmd;
				command.par[0] = PARAMETERS[0];

				//=======Call debugFunc in thread======
				int rc;
				pthread_attr_t attr;
				pthread_attr_init(&attr);
				pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
				
				if((rc = pthread_create(&webcamThread,&attr,webcamFunc,&command))){
					fprintf(stderr,"Error: Could not create webcam thread: %d\n",rc);
				}
				
				pthread_attr_destroy(&attr);				
			}

			if(compareText(cmd,"EmailPhoto")){
				command.cmd = cmd;
				command.par[0] = PARAMETERS[0];
				command.par[1] = PARAMETERS[1];
				command.par[2] = PARAMETERS[2];

				//=======Call debugFunc in thread======
				int rc;
				pthread_attr_t attr;
				pthread_attr_init(&attr);
				pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
				
				if((rc = pthread_create(&emailPhotoThread,&attr,emailPhotoFunc,&command))){
					fprintf(stderr,"Error: Could not create emailPhoto thread: %d\n",rc);
				}
				
				pthread_attr_destroy(&attr);
			}
			
		}else if(receivedBytes == 0){				//No data yet! go back to loop
			continue;					
		}else if(receivedBytes < 0){				//Error reading, exit.
			printf("Error reading from file!\n");
			perror("Error: " );
			close(fd);
			return -1;
		}
		usleep(UDOONEO_POLL_DELAY);	// poll time approx 50mS (faster crashes the app)
	}

	//Free reserved memory
	free((void*)cmd);
	free((void*)par);

	//Close serial's file descriptor
	close(fd);	
}
Пример #21
0
 int main() {
  CvPoint pt1,pt2;
  CvRect regt;
  CvPoint cir_center;
  CvPoint frame_center;
  CvPoint A,B,C,D;
  CvPoint temp;
  double angle,spinsize;
  int cir_radius=1; 
  int frame_width=160, frame_height=120;
  unsigned char sendBuf;
  int serial;
  serial = openSerial("/dev/ttyACM0");
  if (serial == -1)
  serial = openSerial("/dev/ttyACM1");
  if (serial == -1)
  serial = openSerial("/dev/ttyACM2"); 
  if (serial == -1)
  serial = openSerial("/dev/ttyACM3");	
  if (serial == -1)
  serial = openSerial("/dev/ttyACM4");	
  if (serial == -1)
  serial = openSerial("/dev/ttyACM5");
  if (serial == -1)
  serial = openSerial("/dev/ttyACM6"); 
  if (serial == -1)
  serial = openSerial("/dev/ttyACM7");	
  if (serial == -1)
  serial = openSerial("/dev/ttyACM8");	
if( serial == -1 ) {
return -1;
}
   //CvCapture* capture = cvCaptureFromCAM( CV_CAP_ANY );
   CvCapture* capture = cvCaptureFromCAM( 0 );
   if ( !capture ) {
     fprintf(stderr, "ERROR: capture is NULL \n" );
     getchar();
     return -1;
   }
  cvSetCaptureProperty(capture,CV_CAP_PROP_FRAME_WIDTH,frame_width);// 120x160 
  cvSetCaptureProperty(capture,CV_CAP_PROP_FRAME_HEIGHT,frame_height);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FPS,10);
//  cvSetCaptureProperty(capture,CV_CAP_PROP_POS_FRAMES,5);  
 // Create a window in which the captured images will be presented
   cvNamedWindow( "mywindow", CV_WINDOW_AUTOSIZE );
   // Show the image captured from the camera in the window and repeat
   while ( 1 ) {
     // Get one frame
     IplImage* frame = cvQueryFrame( capture );
     if ( !frame ) {
       fprintf( stderr, "ERROR: frame is null...\n" );
       getchar();
       break;
     }
     int modfheight, modfwidth;

     modfheight = frame->height;
     modfwidth = frame->width;
     // create modified frame with 1/4th the original size
     IplImage* modframe = cvCreateImage(cvSize((int)(modfwidth/4),(int)(modfheight/4)),frame->depth,frame->nChannels); //cvCreateImage(size of frame, depth, noofchannels)
     cvResize(frame, modframe,CV_INTER_LINEAR);
     // create HSV(Hue, Saturation, Value) frame
     IplImage* hsvframe = cvCreateImage(cvGetSize(modframe),8, 3);
     cvCvtColor(modframe, hsvframe, CV_BGR2HSV); //cvCvtColor(input frame,outputframe,method)
     // create a frame within threshold.
     IplImage* threshframe = cvCreateImage(cvGetSize(hsvframe),8,1);
     cvInRangeS(hsvframe,cvScalar(10, 180, 130),cvScalar(40, 240, 245),threshframe); //cvInRangeS(input frame, cvScalar(min range),cvScalar(max range),output frame)
     // created dilated image
     IplImage* dilframe = cvCreateImage(cvGetSize(threshframe),8,1);
     cvDilate(threshframe,dilframe,NULL,2); //cvDilate(input frame, output frame, mask, number of times to dilate)

     CBlobResult blobs;
     blobs = CBlobResult(dilframe,NULL,0); // CBlobresult(inputframe, mask, threshold) Will filter all white parts of image
     blobs.Filter(blobs,B_EXCLUDE,CBlobGetArea(),B_LESS,50);//blobs.Filter(input, cond, criteria, cond, const) Filter all images whose area is less than 50 pixels
     CBlob biggestblob;
     blobs.GetNthBlob(CBlobGetArea(),0,biggestblob); //GetNthBlob(criteria, number, output) Get only the largest blob based on CblobGetArea()
     // get 4 points to define the rectangle
     pt1.x = biggestblob.MinX()*4;
     pt1.y = biggestblob.MinY()*4;
     pt2.x = biggestblob.MaxX()*4;
     pt2.y = biggestblob.MaxY()*4;
     cir_center.x=(pt1.x+pt2.x)/2;
     cir_center.y=(pt1.y+pt2.y)/2;
     frame_center.x=frame_width/2;
     frame_center.y=frame_height/2;
     A.x=frame_center.x-4;
     A.y=frame_center.y;
     B.x=frame_center.x+4;
     B.y=frame_center.y;
     C.y=frame_center.y-4;
     C.x=frame_center.x;
     D.y=frame_center.y+4;
     D.x=frame_center.x;
     cvRectangle(frame,pt1,pt2,cvScalar(255,0,0),1,8,0); // draw rectangle around the biggest blob
     cvCircle( frame, cir_center, cir_radius, cvScalar(0,255,255), 1, 8, 0 ); // center point of the rectangle
     cvLine(frame, A, B,cvScalar(255,0,255),2,8,0);
     cvLine(frame, C, D,cvScalar(255,0,255),2,8,0);
     if (cir_center.x!=0&&cir_center.y!=0){
     spinsize=sqrt((cir_center.x-frame_center.x)*(cir_center.x-frame_center.x) +(cir_center.y-frame_center.y)*(cir_center.y-frame_center.y));
     angle = atan2((double)cir_center.y-frame_center.y,(double)cir_center.x-frame_center.x);
     //printf("%f, %f \n",angle*180/3.1416,spinsize/10);
     temp.x=(int)(frame_center.x+spinsize/5*cos(angle+3.1416/4));
     temp.y=(int)(frame_center.y+spinsize/5*sin(angle+3.1415/4));
     cvLine(frame, temp, frame_center,cvScalar(0,255,0),1,8,0);	

     temp.x=(int)(frame_center.x+spinsize/5*cos(angle-3.1416/4));
     temp.y=(int)(frame_center.y+spinsize/5*sin(angle-3.1415/4));
     cvLine(frame, temp, frame_center,cvScalar(0,255,0),1,8,0);	
	
     cvLine(frame, cir_center, frame_center,cvScalar(0,255,0),1,8,0);
     sendBuf=88;
     write(serial, &sendBuf,1);
     sendBuf=cir_center.x;
     write(serial, &sendBuf,1);
     sendBuf=89;
     write(serial, &sendBuf,1);
     sendBuf=cir_center.y;
     write(serial, &sendBuf,1);
    
    //printf("%d %d %f\n",cir_center.x,cir_center.y, angle*180/3.1415);
     //sendvalue(serial, angle*180/3.1416);
     //cvCircle( frame, frame_center, cir_radius, cvScalar(0,255,255), 2, 8, 0 );
}

     cvShowImage( "mywindow", frame); // show output image
     // Do not release the frame!
     //If ESC key pressed, Key=0x10001B under OpenCV 0.9.7(linux version),
     //remove higher bits using AND operator
     if ( (cvWaitKey(10) & 255) == 27 ) break;
   }
   // Release the capture device housekeeping
   cvReleaseCapture( &capture );
   cvDestroyWindow( "mywindow" );
   return 0;
 }
Пример #22
0
void openSerialAtDefaultSpeed(unsigned char serialPortIndex) {
    openSerial(serialPortIndex, 0);
}
Пример #23
0
int
main (int argc, char **argv)
{

  int c;
  extern char *optarg;
  extern int optind, opterr, optopt;
  dsd_opts opts;
  dsd_state state;
  char versionstr[25];
  mbe_printVersion (versionstr);

  printf ("Digital Speech Decoder 1.7.0-dev (build:%s)\n", GIT_TAG);
  printf ("mbelib version %s\n", versionstr);

  initOpts (&opts);
  initState (&state);

  exitflag = 0;
  signal (SIGINT, sigfun);

  while ((c = getopt (argc, argv, "hep:qstv:z:i:o:d:g:nw:B:C:R:f:m:u:x:A:S:M:rl")) != -1)
    {
      opterr = 0;
      switch (c)
        {
        case 'h':
          usage ();
          exit (0);
        case 'e':
          opts.errorbars = 1;
          opts.datascope = 0;
          break;
        case 'p':
          if (optarg[0] == 'e')
            {
              opts.p25enc = 1;
            }
          else if (optarg[0] == 'l')
            {
              opts.p25lc = 1;
            }
          else if (optarg[0] == 's')
            {
              opts.p25status = 1;
            }
          else if (optarg[0] == 't')
            {
              opts.p25tg = 1;
            }
          else if (optarg[0] == 'u')
            {
        	  opts.unmute_encrypted_p25 = 1;
            }
          break;
        case 'q':
          opts.errorbars = 0;
          opts.verbose = 0;
          break;
        case 's':
          opts.errorbars = 0;
          opts.p25enc = 0;
          opts.p25lc = 0;
          opts.p25status = 0;
          opts.p25tg = 0;
          opts.datascope = 1;
          opts.symboltiming = 0;
          break;
        case 't':
          opts.symboltiming = 1;
          opts.errorbars = 1;
          opts.datascope = 0;
          break;
        case 'v':
          sscanf (optarg, "%d", &opts.verbose);
          break;
        case 'z':
          sscanf (optarg, "%d", &opts.scoperate);
          opts.errorbars = 0;
          opts.p25enc = 0;
          opts.p25lc = 0;
          opts.p25status = 0;
          opts.p25tg = 0;
          opts.datascope = 1;
          opts.symboltiming = 0;
          printf ("Setting datascope frame rate to %i frame per second.\n", opts.scoperate);
          break;
        case 'i':
          strncpy(opts.audio_in_dev, optarg, 1023);
          opts.audio_in_dev[1023] = '\0';
          break;
        case 'o':
          strncpy(opts.audio_out_dev, optarg, 1023);
          opts.audio_out_dev[1023] = '\0';
          break;
        case 'd':
          strncpy(opts.mbe_out_dir, optarg, 1023);
          opts.mbe_out_dir[1023] = '\0';
          printf ("Writing mbe data files to directory %s\n", opts.mbe_out_dir);
          break;
        case 'g':
          sscanf (optarg, "%f", &opts.audio_gain);
          if (opts.audio_gain < (float) 0 )
            {
              printf ("Disabling audio out gain setting\n");
            }
          else if (opts.audio_gain == (float) 0)
            {
              opts.audio_gain = (float) 0;
              printf ("Enabling audio out auto-gain\n");
            }
          else
            {
              printf ("Setting audio out gain to %f\n", opts.audio_gain);
              state.aout_gain = opts.audio_gain;
            }
          break;
        case 'n':
          opts.audio_out = 0;
          printf ("Disabling audio output to soundcard.\n");
          break;
        case 'w':
          strncpy(opts.wav_out_file, optarg, 1023);
          opts.wav_out_file[1023] = '\0';
          printf ("Writing audio to file %s\n", opts.wav_out_file);
          openWavOutFile (&opts, &state);
          break;
        case 'B':
          sscanf (optarg, "%d", &opts.serial_baud);
          break;
        case 'C':
          strncpy(opts.serial_dev, optarg, 1023);
          opts.serial_dev[1023] = '\0';
          break;
        case 'R':
          sscanf (optarg, "%d", &opts.resume);
          printf ("Enabling scan resume after %i TDULC frames\n", opts.resume);
          break;
        case 'f':
          if (optarg[0] == 'a')
            {
              opts.frame_dstar = 1;
              opts.frame_x2tdma = 1;
              opts.frame_p25p1 = 1;
              opts.frame_nxdn48 = 0;
              opts.frame_nxdn96 = 1;
              opts.frame_dmr = 1;
              opts.frame_provoice = 0;
            }
          else if (optarg[0] == 'd')
            {
              opts.frame_dstar = 1;
              opts.frame_x2tdma = 0;
              opts.frame_p25p1 = 0;
              opts.frame_nxdn48 = 0;
              opts.frame_nxdn96 = 0;
              opts.frame_dmr = 0;
              opts.frame_provoice = 0;
              printf ("Decoding only D-STAR frames.\n");
            }
          else if (optarg[0] == 'x')
            {
              opts.frame_dstar = 0;
              opts.frame_x2tdma = 1;
              opts.frame_p25p1 = 0;
              opts.frame_nxdn48 = 0;
              opts.frame_nxdn96 = 0;
              opts.frame_dmr = 0;
              opts.frame_provoice = 0;
              printf ("Decoding only X2-TDMA frames.\n");
            }
          else if (optarg[0] == 'p')
            {
              opts.frame_dstar = 0;
              opts.frame_x2tdma = 0;
              opts.frame_p25p1 = 0;
              opts.frame_nxdn48 = 0;
              opts.frame_nxdn96 = 0;
              opts.frame_dmr = 0;
              opts.frame_provoice = 1;
              state.samplesPerSymbol = 5;
              state.symbolCenter = 2;
              opts.mod_c4fm = 0;
              opts.mod_qpsk = 0;
              opts.mod_gfsk = 1;
              state.rf_mod = 2;
              printf ("Setting symbol rate to 9600 / second\n");
              printf ("Enabling only GFSK modulation optimizations.\n");
              printf ("Decoding only ProVoice frames.\n");
            }
          else if (optarg[0] == '1')
            {
              opts.frame_dstar = 0;
              opts.frame_x2tdma = 0;
              opts.frame_p25p1 = 1;
              opts.frame_nxdn48 = 0;
              opts.frame_nxdn96 = 0;
              opts.frame_dmr = 0;
              opts.frame_provoice = 0;
              printf ("Decoding only P25 Phase 1 frames.\n");
            }
          else if (optarg[0] == 'i')
            {
              opts.frame_dstar = 0;
              opts.frame_x2tdma = 0;
              opts.frame_p25p1 = 0;
              opts.frame_nxdn48 = 1;
              opts.frame_nxdn96 = 0;
              opts.frame_dmr = 0;
              opts.frame_provoice = 0;
              state.samplesPerSymbol = 20;
              state.symbolCenter = 10;
              opts.mod_c4fm = 0;
              opts.mod_qpsk = 0;
              opts.mod_gfsk = 1;
              state.rf_mod = 2;
              printf ("Setting symbol rate to 2400 / second\n");
              printf ("Enabling only GFSK modulation optimizations.\n");
              printf ("Decoding only NXDN 4800 baud frames.\n");
            }
          else if (optarg[0] == 'n')
            {
              opts.frame_dstar = 0;
              opts.frame_x2tdma = 0;
              opts.frame_p25p1 = 0;
              opts.frame_nxdn48 = 0;
              opts.frame_nxdn96 = 1;
              opts.frame_dmr = 0;
              opts.frame_provoice = 0;
              opts.mod_c4fm = 0;
              opts.mod_qpsk = 0;
              opts.mod_gfsk = 1;
              state.rf_mod = 2;
              printf ("Enabling only GFSK modulation optimizations.\n");
              printf ("Decoding only NXDN 9600 baud frames.\n");
            }
          else if (optarg[0] == 'r')
            {
              opts.frame_dstar = 0;
              opts.frame_x2tdma = 0;
              opts.frame_p25p1 = 0;
              opts.frame_nxdn48 = 0;
              opts.frame_nxdn96 = 0;
              opts.frame_dmr = 1;
              opts.frame_provoice = 0;
              printf ("Decoding only DMR/MOTOTRBO frames.\n");
            }
          break;
        case 'm':
          if (optarg[0] == 'a')
            {
              opts.mod_c4fm = 1;
              opts.mod_qpsk = 1;
              opts.mod_gfsk = 1;
              state.rf_mod = 0;
            }
          else if (optarg[0] == 'c')
            {
              opts.mod_c4fm = 1;
              opts.mod_qpsk = 0;
              opts.mod_gfsk = 0;
              state.rf_mod = 0;
              printf ("Enabling only C4FM modulation optimizations.\n");
            }
          else if (optarg[0] == 'g')
            {
              opts.mod_c4fm = 0;
              opts.mod_qpsk = 0;
              opts.mod_gfsk = 1;
              state.rf_mod = 2;
              printf ("Enabling only GFSK modulation optimizations.\n");
            }
          else if (optarg[0] == 'q')
            {
              opts.mod_c4fm = 0;
              opts.mod_qpsk = 1;
              opts.mod_gfsk = 0;
              state.rf_mod = 1;
              printf ("Enabling only QPSK modulation optimizations.\n");
            }
          break;
        case 'u':
          sscanf (optarg, "%i", &opts.uvquality);
          if (opts.uvquality < 1)
            {
              opts.uvquality = 1;
            }
          else if (opts.uvquality > 64)
            {
              opts.uvquality = 64;
            }
          printf ("Setting unvoice speech quality to %i waves per band.\n", opts.uvquality);
          break;
        case 'x':
          if (optarg[0] == 'x')
            {
              opts.inverted_x2tdma = 0;
              printf ("Expecting non-inverted X2-TDMA signals.\n");
            }
          else if (optarg[0] == 'r')
            {
              opts.inverted_dmr = 1;
              printf ("Expecting inverted DMR/MOTOTRBO signals.\n");
            }
          break;
        case 'A':
          sscanf (optarg, "%i", &opts.mod_threshold);
          printf ("Setting C4FM/QPSK auto detection threshold to %i\n", opts.mod_threshold);
          break;
        case 'S':
          sscanf (optarg, "%i", &opts.ssize);
          if (opts.ssize > 128)
            {
              opts.ssize = 128;
            }
          else if (opts.ssize < 1)
            {
              opts.ssize = 1;
            }
          printf ("Setting QPSK symbol buffer to %i\n", opts.ssize);
          break;
        case 'M':
          sscanf (optarg, "%i", &opts.msize);
          if (opts.msize > 1024)
            {
              opts.msize = 1024;
            }
          else if (opts.msize < 1)
            {
              opts.msize = 1;
            }
          printf ("Setting QPSK Min/Max buffer to %i\n", opts.msize);
          break;
        case 'r':
          opts.playfiles = 1;
          opts.errorbars = 0;
          opts.datascope = 0;
          state.optind = optind;
          break;
        case 'l':
          opts.use_cosine_filter = 0;
          break;
        default:
          usage ();
          exit (0);
        }
    }


  if (opts.resume > 0)
    {
      openSerial (&opts, &state);
    }

  if (opts.playfiles == 1)
    {
      opts.split = 1;
      opts.playoffset = 0;
      opts.delay = 0;
      if(strlen(opts.wav_out_file) > 0) {
        openWavOutFile (&opts, &state);
      }
      else {
        openAudioOutDevice (&opts, 8000);
      }
    }
  else if (strcmp (opts.audio_in_dev, opts.audio_out_dev) != 0)
    {
      opts.split = 1;
      opts.playoffset = 0;
      opts.delay = 0;
      if(strlen(opts.wav_out_file) > 0) {
        openWavOutFile (&opts, &state);
      }
      else {
        openAudioOutDevice (&opts, 8000);
      }
      openAudioInDevice (&opts);
    }
  else
    {
      opts.split = 0;
      opts.playoffset = 25;     // 38
      opts.delay = 0;
      openAudioInDevice (&opts);
      opts.audio_out_fd = opts.audio_in_fd;
    }

  if (opts.playfiles == 1)
    {
      playMbeFiles (&opts, &state, argc, argv);
    }
  else
    {
      liveScanner (&opts, &state);
    }
  cleanupAndExit (&opts, &state);
  return (0);
}