int main(int argc, char *argv[]) { if (argc == 3) { try { AHRS *imu = new AHRS(std::string(argv[1]),getBaudrate(argv[2])); char *buffer = NULL; size_t bufsize; // Connect to the AHRS. imu->openDevice(); printf("Connected to %s.\n", (imu->getInfo()).c_str()); // Prompt the user for a new baudrate. printf("New speed? (baud) \n"); if (getline(&buffer, &bufsize, stdin) == -1) { fprintf(stderr, "Unable to read in new baudrate.\n"); imu->closeDevice(); return -1; } // Attempt to read in a baudrate and change to it. imu->setBaudrate(getBaudrate(buffer)); // Clean up and close resources. free(buffer); imu->closeDevice(); // Tell the user of the result. fprintf(stderr, "Changed speed successfully.\n"); exit(0); } catch (std::exception& e) { printError(e); } } printUsage(); }
int main(int argc, char *argv[]) { if (argc == 3) { try { DVL *dvl = new DVL(std::string(argv[1]),getBaudrate(argv[2])); DVL::SystemConfig config; char *buffer = NULL; size_t bufsize; // Prompt the user for a new baudrate. printf("New speed? (baud) \n"); if (getline(&buffer, &bufsize, stdin) == -1) { fprintf(stderr, "Unable to read in new baudrate.\n"); dvl->closeDevice(); return -1; } // Read in the baudrate and change the device speed. config.speed = getBaudrate(buffer); // Clean up and close resources. free(buffer); dvl->closeDevice(); // Tell the user of the result. fprintf(stderr, "Changed speed successfully.\n"); exit(0); } catch (std::exception& e) { printError(e); } } printUsage(); }
/* Open connection. * Returns 1 if ESP8266 is responding, 0 otherwise. */ bool ArduEsp8266::init(){ // init serial debugging interface if( useDebug() ){ debug.begin(115200); debug.println("init esp8266 wifi module ..."); } if( getEnablePin() >= 0 ){ pinMode( getEnablePin(), OUTPUT ); digitalWrite( getEnablePin(), HIGH ); delay(2000); } // init serial port Serial.begin( getBaudrate() ); if( isConnected() ){ // try to disable echo setEcho(false); return true; } return false; }
/* * Class: abel_serialport_SerialPort * Method: open * Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor; */ JNIEXPORT jobject JNICALL Java_abel_serialport_SerialPort_open (JNIEnv *env, jclass clazz, jstring path, jint baudrate, jint flags) { speed_t speed = getBaudrate(baudrate); if (speed == -1) { LOGE("Invalid baudrate"); return NULL; } int fd; jboolean iscopy; const char *path_utf = (*env)->GetStringUTFChars(env, path, &iscopy); fd = open(path_utf, O_RDWR | O_NOCTTY | flags); (*env)->ReleaseStringUTFChars(env, path, path_utf); if (fd == -1) { /* Throw an exception */ LOGE("Cannot open port"); /* TODO: throw an exception */ return NULL; } struct termios cfg; if (tcgetattr(fd, &cfg)) { LOGE("tcgetattr() failed"); close(fd); return NULL; } cfmakeraw(&cfg); cfsetispeed(&cfg, speed); cfsetospeed(&cfg, speed); cfg.c_cflag &= ~(HUPCL | CLOCAL); LOGD("%s cflag: %X", path_utf, cfg.c_cflag); LOGD("%s lflag: %X", path_utf, cfg.c_lflag); LOGD("%s iflag: %X", path_utf, cfg.c_iflag); LOGD("%s oflag: %X", path_utf, cfg.c_oflag); if (tcsetattr(fd, TCSANOW, &cfg)) { LOGE("tcsetattr() failed"); close(fd); /* TODO: throw an exception */ return NULL; } jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor"); jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "<init>", "()V"); jfieldID descriptorID = (*env)->GetFieldID(env, cFileDescriptor, "descriptor", "I"); jobject fileDescriptor = (*env)->NewObject(env, cFileDescriptor, iFileDescriptor); (*env)->SetIntField(env, fileDescriptor, descriptorID, (jint)fd); return fileDescriptor; }
JNIEXPORT jint JNICALL Java_firich_com_firichsdk_SerialPort_openSerialPort(JNIEnv *env, jobject instance, jstring path_, jint baudrate) { const char *path = (*env)->GetStringUTFChars(env, path_, 0); //Android Java String convert to C char* struct termios tio; memset(&tio,0,sizeof(tio)); tio.c_iflag=0; tio.c_oflag=0; tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information tio.c_lflag=0; tio.c_cc[VMIN]=1; tio.c_cc[VTIME]=5; int tty_fd=open(path, O_RDWR | O_NONBLOCK); cfsetospeed(&tio,getBaudrate(baudrate)); cfsetispeed(&tio,getBaudrate(baudrate)); tcsetattr(tty_fd,TCSANOW,&tio); return tty_fd; // C char convert to Android Java String }
int main(int argc, char *argv[]) { if (argc == 3) { try { AHRS *ahrs = new AHRS(std::string(argv[1]),getBaudrate(argv[2])); AHRS::AcqConfig config; AHRS::FilterData filters; long unsigned int i; ahrs->openDevice(); printf("Connected to %s.\n", (ahrs->getInfo()).c_str()); ahrs->sendAHRSDataFormat(); printf("AHRS Configuration data:\n"); config = ahrs->getAcqConfig(); printf("Acqusition mode: %d\n", config.poll_mode); printf("Flush Filter: %d\n", config.flush_filter); printf("Sample delay: %f\n", config.sample_delay); filters = ahrs->getFIRFilters(); printf("Number of filters: %lu\n", filters.size()); for (i=0; i < filters.size(); i++) printf("Filter #%.2lu: %f\n",i, filters[i]); printf("Mag Truth Method: %d\n", ahrs->getMagTruthMethod()); printf("Functional mode: %d\n", ahrs->getAHRSMode()); printf("Declination: %f\n", ahrs->getDeclination()); printf("UserCalNumPoints: %d\n", ahrs->getCalPoints()); printf("Mag Setting: %d\n", ahrs->getMagCalID()); printf("Accel setting: %d\n", ahrs->getAccelCalID()); printf("Mounting mode: %d\n", ahrs->getMounting()); printf("Baudrate: %d\n", ahrs->getBaudrate().baud); printf("True north? %d\n", ahrs->getTrueNorth()); printf("Big endian? %d\n", ahrs->getBigEndian()); printf("Auto sampling? %d\n", ahrs->getAutoCalibration()); printf("Mils/Degrees? %d\n", ahrs->getMils()); printf("HPR During Cal? %d\n", ahrs->getHPRCal()); ahrs->closeDevice(); exit(0); } catch (std::exception& e) { printError(e); } } printUsage(); }
/* first parse all options, and save arguments in the sessions struct * exit on any error encountered, if none present, proceed and return */ void setOptions(int argc, const char * argv[]) { int ret; bool printVersion = false; poptContext optCon = poptGetContext(NULL, argc, argv, options, 0); options[0].arg = elbowOptionsTable; while ((ret = poptGetNextOpt(optCon)) > 0) { switch (ret) { case PR_EOL: settings.eol = getEndOfLine(settings.eol); break; case PR_BAUDRATE: settings.rate = getBaudrate(settings.rate); break; case PR_VERSION: printVersion = true; break; } } /* report parsing error if present and exit */ if (ret < -1) { printf("\n%s: %s\n\n", poptStrerror(ret), poptBadOption(optCon, 0)); poptPrintHelp(optCon, stdout, 0); exit(EXIT_FAILURE); } /* print version information and exit */ if (printVersion) { printf("Elbow version %s\n", VERSION); printf("Copyright (C) %s %s\n", YEAR, AUTHOR); printf("Released under the %s license.\n", LICENSE); printf("\n%s\n", DISCLAIMER); } optCon = poptFreeContext(optCon); }
/* * Class: android_serialport_SerialPort * Method: open * Signature: (Ljava/lang/String;II)Ljava/io/FileDescriptor; */ JNIEXPORT jobject JNICALL Java_com_bw_serial_SerialPort_open (JNIEnv *env, jclass thiz, jstring path, jint baudrate, jint flags) { int fd; speed_t speed; jobject mFileDescriptor; /* Check arguments */ { speed = getBaudrate(baudrate); if (speed == -1) { /* TODO: throw an exception */ LOGE("Invalid baudrate"); return NULL; } } /* Opening device */ { jboolean iscopy; const char *path_utf = (*env)->GetStringUTFChars(env, path, &iscopy); LOGD("Opening serial port %s with flags 0x%x", path_utf, O_RDWR | flags); fd = open(path_utf, O_RDWR | flags); LOGD("open() fd = %d", fd); (*env)->ReleaseStringUTFChars(env, path, path_utf); if (fd == -1) { /* Throw an exception */ LOGE("Cannot open port"); /* TODO: throw an exception */ return NULL; } } /* Configure device */ { struct termios cfg; LOGD("Configuring serial port"); if (tcgetattr(fd, &cfg)) { LOGE("tcgetattr() failed"); close(fd); /* TODO: throw an exception */ return NULL; } cfmakeraw(&cfg); cfsetispeed(&cfg, speed); cfsetospeed(&cfg, speed); if (tcsetattr(fd, TCSANOW, &cfg)) { LOGE("tcsetattr() failed"); close(fd); /* TODO: throw an exception */ return NULL; } } /* Create a corresponding file descriptor */ { jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor"); jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "<init>", "()V"); jfieldID descriptorID = (*env)->GetFieldID(env, cFileDescriptor, "descriptor", "I"); mFileDescriptor = (*env)->NewObject(env, cFileDescriptor, iFileDescriptor); (*env)->SetIntField(env, mFileDescriptor, descriptorID, (jint)fd); } return mFileDescriptor; }
static int set_opt(int fd,int nSpeed, int nBits, char nEvent, int nStop) { struct termios newtio,oldtio; speed_t speedbt; /*保存测试现有串口参数设置,在这里如果串口号等出错,会有相关的出错信息*/ if ( tcgetattr( fd,&oldtio) != 0) { perror("SetupSerial 1"); return -1; } bzero( &newtio, sizeof( newtio ) ); /*步骤一,设置字符大小*/ newtio.c_cflag |= CLOCAL | CREAD; newtio.c_cflag &= ~CSIZE; /*设置停止位*/ switch( nBits ) { case 7: newtio.c_cflag |= CS7; break; case 8: newtio.c_cflag |= CS8; break; } /*设置奇偶校验位*/ switch( nEvent ) { case 'O': //奇数 newtio.c_cflag |= PARENB; newtio.c_cflag |= PARODD; newtio.c_iflag |= INPCK; break; case 'E': //偶数 newtio.c_iflag |= INPCK; newtio.c_cflag |= PARENB; newtio.c_cflag &= ~PARODD; break; case 'N': //无奇偶校验位 newtio.c_cflag &= ~PARENB; break; } /*设置波特率*/ speedbt = getBaudrate(nSpeed); if (speedbt < 0) { LOGD("-------------getBaudrate error %d\n", nSpeed); return -1; } cfsetispeed(&newtio, speedbt); cfsetospeed(&newtio, speedbt); #if 0 switch( nSpeed ) { case 2400: cfsetispeed(&newtio, B2400); cfsetospeed(&newtio, B2400); break; case 4800: cfsetispeed(&newtio, B4800); cfsetospeed(&newtio, B4800); break; case 9600: cfsetispeed(&newtio, B9600); cfsetospeed(&newtio, B9600); break; case 115200: cfsetispeed(&newtio, B115200); cfsetospeed(&newtio, B115200); break; case 460800: cfsetispeed(&newtio, B460800); cfsetospeed(&newtio, B460800); break; default: cfsetispeed(&newtio, B9600); cfsetospeed(&newtio, B9600); break; } #endif /*设置停止位*/ if( nStop == 1 ) newtio.c_cflag &= ~CSTOPB; else if ( nStop == 2 ) newtio.c_cflag |= CSTOPB; /*设置等待时间和最小接收字符*/ newtio.c_cc[VTIME] = 0; newtio.c_cc[VMIN] = 0; /*处理未接收字符*/ tcflush(fd,TCIFLUSH); /*激活新配置*/ if((tcsetattr(fd,TCSANOW,&newtio))!=0) { perror("com set error"); return -1; } printf("set done!\n"); return 0; }
// コンストラクタ Terminal::Terminal(QWidget *parent) : QMainWindow(parent), m_ds(this){ // 変数初期化 // GUIを作成 m_ui.setupUi(this); // GUI各部の制御クラスを作成 m_console = new TerminalConsole(m_ui.ConsoleInput, m_ui.ConsoleOutput, m_ui.ConsoleClear); m_info = new TerminalInfo(m_ui.StatusBar, m_ui.InfoIconDevice, m_ui.InfoLabelName, m_ui.InfoLabelVersion, m_ui.InfoButtonReboot, m_ui.InfoButtonConnect, m_ui.InfoButtonDisconnect); m_access = new TerminalAccess(m_ui.ProcessorInput, m_ui.ProcessorOpen, m_ui.ProcessorWrite, m_ui.ProcessorRead, m_ui.BitstreamInput, m_ui.BitstreamOpen, m_ui.BitstreamSend, m_ui.BitstreamWrite, m_ui.CoprocessorInput, m_ui.CoprocessorOpen, m_ui.CoprocessorSend, m_ui.CoprocessorWrite); m_controller = new TerminalController(this, m_ui.ControllerShow); m_logger = new TerminalLogger(m_ui.LoggerCheckUse, m_ui.LoggerGraph, m_ui.LoggerButtonAdd, m_ui.LoggerButtonRemove, m_ui.LoggerList, m_ui.LoggerSaveList, m_ui.LoggerLabel, m_ui.LoggerStart, m_ui.LoggerStop, m_ui.LoggerSave); m_pipe = new TerminalPipe(m_ui.PipeTable); m_file = new TerminalFile(m_ui.FileTree, m_ui.FileProgress); // ファイラータブのツールボックスにアイコンを設定 QFileIconProvider icon_provider; m_ui.FilerToolBox->setItemIcon(0, icon_provider.icon(QFileIconProvider::Network)); m_ui.FilerToolBox->setItemIcon(1, icon_provider.icon(QFileIconProvider::Drive)); // 非同期操作用のスレッドを作成 m_thread = new QThread(this); m_async = new TerminalAsync(&m_ds); m_async->moveToThread(m_thread); // シグナルを接続 connect(&m_ds, SIGNAL(enableConsole(bool)), m_console, SLOT(enable(bool))); connect(&m_ds, SIGNAL(enableInfo(bool, bool)), m_info, SLOT(enable(bool, bool))); connect(&m_ds, SIGNAL(enableAccess(char, bool, bool, bool, bool)), m_access, SLOT(enable(char, bool, bool, bool, bool))); connect(&m_ds, SIGNAL(enableFileTree(bool, bool, bool, bool, bool, bool)), m_file, SLOT(enable(bool, bool, bool, bool, bool, bool))); connect(&m_ds, SIGNAL(enableController(bool, bool, bool)), m_controller, SLOT(enable(bool, bool, bool))); connect(&m_ds, SIGNAL(enableLogger(bool, bool, bool)), m_logger, SLOT(enable(bool, bool, bool))); connect(m_async, SIGNAL(showWarningConst(const wchar_t *, const wchar_t *)), this, SLOT(showWarningConst(const wchar_t *, const wchar_t *)), Qt::QueuedConnection); connect(m_async, SIGNAL(sendProgress(int)), m_info, SLOT(setProgress(int)), Qt::QueuedConnection); connect(m_async, SIGNAL(setExclusiveState(bool)), &m_ds, SLOT(setExclusiveState(bool)), Qt::QueuedConnection); connect(m_console, SIGNAL(send(const QString &)), this, SLOT(transmitDebug(const QString &))); connect(m_info, SIGNAL(changeConnection(const std::wstring *, bool, bool)), this, SLOT(changeConnection(const std::wstring *, bool, bool))); connect(m_info, SIGNAL(rebootRequest(const wchar_t *)), &m_ds, SLOT(changeBootMode(const wchar_t *))); connect(m_access, SIGNAL(operation(char, std::wstring *)), m_async, SLOT(onAccessOperation(char, std::wstring *)), Qt::QueuedConnection); //connect(m_controller, SIGNAL(operation(const Controller_t &)), &m_ds, SLOT(setController(const Controller_t &))); connect(m_file, SIGNAL(updateRequest(const std::wstring &)), m_ds.m_dsDir, SLOT(updateRequest(const std::wstring &))); connect(m_file, SIGNAL(moveRequest(const std::wstring &, const std::wstring &)), m_ds.m_dsDir, SLOT(moveRequest(const std::wstring &, const std::wstring &))); connect(m_file, SIGNAL(copyRequest(const std::wstring &, const std::wstring &)), m_ds.m_dsDir, SLOT(copyRequest(const std::wstring &, const std::wstring &))); connect(m_file, SIGNAL(deleteRequest(const std::wstring &)), m_ds.m_dsDir, SLOT(deleteRequest(const std::wstring &))); connect(m_file, SIGNAL(mkdirRequest(const std::wstring &)), m_ds.m_dsDir, SLOT(mkdirRequest(const std::wstring &))); connect(m_file, SIGNAL(transfarToDevice(std::wstring *, std::wstring *)), m_async, SLOT(transfarToDevice(std::wstring *, std::wstring *)), Qt::QueuedConnection); connect(m_file, SIGNAL(transfarFromDevice(std::wstring *, std::wstring *)), m_async, SLOT(transfarFromDevice(std::wstring *, std::wstring *)), Qt::QueuedConnection); connect(m_logger, SIGNAL(sendLoggingList(char *, unsigned int)), m_async, SLOT(setLoggingList(char *, unsigned int)), Qt::QueuedConnection); connect(m_async, SIGNAL(sendLog(unsigned short *, unsigned int)), m_logger, SLOT(receiveLog(unsigned short *, unsigned int)), Qt::QueuedConnection); connect(m_async, SIGNAL(sendLoggingError()), m_logger, SLOT(receiveError()), Qt::QueuedConnection); connect(m_controller, SIGNAL(setControllerState(ControllerState_t *)), m_async, SLOT(setControllerState(ControllerState_t *)), Qt::QueuedConnection); connect(m_async, SIGNAL(requestControllerState()), m_controller, SLOT(requestControllerState()), Qt::QueuedConnection); connect(&m_ds, SIGNAL(setDebugText(QString &)), m_info, SLOT(setDebugText(QString &))); connect(&m_ds, SIGNAL(sendProgress(int)), m_info, SLOT(setProgress(int))); connect(&m_ds, SIGNAL(setLogInfo(const std::wstring &)), m_logger, SLOT(setLogInfo(const std::wstring &))); connect(&m_ds, SIGNAL(changeConnection(const std::wstring *, bool, bool)), this, SLOT(changeConnection(const std::wstring *, bool, bool))); connect(&m_ds, SIGNAL(updateWidgetsInfo()), this, SLOT(updateWidgetsInfo())); connect(m_ds.m_dsPipe, SIGNAL(clearPipe()), m_pipe, SLOT(clearPipe())); connect(m_ds.m_dsPipe, SIGNAL(addPipe(const wchar_t *, int, int, const wchar_t *)), m_pipe, SLOT(addPipe(const wchar_t *, int, int, const wchar_t *))); connect(m_ds.m_dsDir, SIGNAL(initTree(const std::wstring &)), m_file, SLOT(initTree(const std::wstring &))); connect(m_ds.m_dsDir, SIGNAL(addDrive(char, const std::wstring &, bool, unsigned long long)), m_file, SLOT(addDrive(char, const std::wstring &, bool, unsigned long long))); connect(m_ds.m_dsDir, SIGNAL(changeDriveStatus(char, unsigned long long)), m_file, SLOT(changeDriveStatus(char, unsigned long long))); connect(m_ds.m_dsDir, SIGNAL(moveToItem(const std::wstring &)), m_file, SLOT(moveToItem(const std::wstring &))); connect(m_ds.m_dsDir, SIGNAL(addItem(const std::wstring &, unsigned long long, bool, unsigned int)), m_file, SLOT(addItem(const std::wstring &, unsigned long long, bool, unsigned int))); connect(m_ds.m_dsDir, SIGNAL(moveUp()), m_file, SLOT(moveUp())); connect(m_ds.m_dsFile, SIGNAL(changeFile(std::wstring *, unsigned long long)), m_file, SLOT(changeFile(std::wstring *, unsigned long long)), Qt::QueuedConnection); // タイマーを作成 QTimer *interval = new QTimer(this); connect(interval, SIGNAL(timeout()), this, SLOT(onInterval())); connect(interval, SIGNAL(timeout()), m_logger, SLOT(update())); interval->start(PERIOD); // ウィジェットを初期状態に m_console->enable(false); m_info->enable(false, false); m_access->enable('P', false); m_access->enable('B', false); m_access->enable('C', false); m_file->enable(false); m_controller->enable(false); m_logger->enable(false); // 前回の設定の読み込み int maximized = 0; clINI setting; if (setting.Open(g_ApplicationDir.c_str(), L"setting.ini") == true){ // パスの読み込み wchar_t buf[MAX_PATH]; setting.Read(L"Path", L"Processor", buf); m_access->setPath('P', buf); setting.Read(L"Path", L"Bitstream", buf); m_access->setPath('B', buf); setting.Read(L"Path", L"Coprocessor", buf); m_access->setPath('C', buf); // 設定の読み込み int baudrate = m_info->getBaudrate(); setting.Read(L"Setting", L"Baudrate", baudrate); m_info->setBaudrate(baudrate); // ウィンドウ座標・サイズの読み込み int pos_x, pos_y, size_w, size_h; setting.Read(L"Window", L"Maximize", maximized); setting.Read(L"Window", L"PosX", pos_x); setting.Read(L"Window", L"PosY", pos_y); setting.Read(L"Window", L"SizeW", size_w); setting.Read(L"Window", L"SizeH", size_h); pos_x -= 500000; pos_y -= 500000; size_w -= 500000; size_h -= 500000; if ((abs(pos_x) <= 32767) && (abs(pos_y) <= 32767)) this->move(pos_x, pos_y); if ((abs(size_w) <= 32767) && (abs(size_h) <= 32767)) this->resize(size_w, size_h); } // 非同期操作用スレッドを開始 m_thread->start(); // タイマーの精度を高める timeBeginPeriod(1); // ウィンドウを表示 if (maximized == 0){ this->show(); }else{ this->showMaximized(); } }
/* * Class: cedric_serial_SerialPort * Method: open * Signature: (Ljava/lang/String;)V */ JNIEXPORT jobject JNICALL Java_com_erobbing_mcutool_SerialPort_open(JNIEnv *env, jobject thiz, jstring path,jint baudrate) { int fd; speed_t speed; jobject mFileDescriptor; LOGD("init native Check arguments"); /* Check arguments */ { speed = getBaudrate(baudrate); if (speed == -1) { /* TODO: throw an exception */ LOGE("Invalid baudrate"); return NULL; } } LOGD("init native Opening device!"); /* Opening device */ { jboolean iscopy; const char *path_utf = env->GetStringUTFChars(path, &iscopy); LOGD("Opening serial port %s", path_utf); // fd = open(path_utf, O_RDWR | O_DIRECT | O_SYNC); fd = open(path_utf, O_RDWR | O_NOCTTY | O_NONBLOCK | O_NDELAY); LOGD("open() fd = %d", fd); env->ReleaseStringUTFChars(path, path_utf); if (fd == -1) { /* Throw an exception */ LOGE("Cannot open port %d",baudrate); /* TODO: throw an exception */ return NULL; } } LOGD("init native Configure device!"); /* Configure device */ { struct termios cfg; if (tcgetattr(fd, &cfg)) { LOGE("Configure device tcgetattr() failed 1"); close(fd); return NULL; } cfmakeraw(&cfg); cfsetispeed(&cfg, speed); cfsetospeed(&cfg, speed); if (tcsetattr(fd, TCSANOW, &cfg)) { LOGE("Configure device tcsetattr() failed 2"); close(fd); /* TODO: throw an exception */ return NULL; } } /* Create a corresponding file descriptor */ { jclass cFileDescriptor = env->FindClass("java/io/FileDescriptor"); jmethodID iFileDescriptor = env->GetMethodID(cFileDescriptor,"<init>", "()V"); jfieldID descriptorID = env->GetFieldID(cFileDescriptor,"descriptor", "I"); mFileDescriptor = env->NewObject(cFileDescriptor,iFileDescriptor); env->SetIntField(mFileDescriptor, descriptorID, (jint) fd); } return mFileDescriptor; }
// Opens the connection to the GPS. All old messages in the queue are removed. bool GpsClient::openGps( const char *deviceIn, const uint ioSpeedIn ) { // qDebug() << "GpsClient::openGps:" << deviceIn << "," << ioSpeedIn; device = deviceIn; ioSpeedDevice = ioSpeedIn; ioSpeedTerminal = getBaudrate(ioSpeedIn); badSentences = 0; unknownsReported.clear(); if( deviceIn == (const char *) 0 || strlen(deviceIn) == 0 ) { // no valid device has been passed return false; } // reset buffer pointer datapointer = databuffer; dbsize = 0; memset( databuffer, 0, sizeof(databuffer) ); if( fd != -1 ) { // closes an existing connection before opening a new one closeGps(); sleep(2); } #ifdef BLUEZ // Define a reg. expression for a Bluetooth address like "XX:XX:XX:XX:XX:XX" QRegExp regExp("([0-9A-Fa-f]{2,2}:){5,5}[0-9A-Fa-f]{2,2}"); if( QString(deviceIn).contains(QRegExp( regExp )) ) { fd = socket( AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM ); // NON blocking io is requested! fcntl( fd, F_SETFL, O_NONBLOCK ); struct sockaddr_rc addr; memset( &addr, 0, sizeof (addr) ); addr.rc_family = AF_BLUETOOTH; // 1 is the default channel for a connection to the BT daemon addr.rc_channel = (uint8_t) 1; str2ba( deviceIn, &addr.rc_bdaddr ); if( connect( fd, (struct sockaddr *) &addr, sizeof (addr)) == -1 && errno != EINPROGRESS ) { qCritical() << "GpsClient::openGps(): BT connect error" << errno << "," << strerror(errno); close( fd ); fd = -1; last = QTime(); setShutdownFlag(true); return false; } // Stop supervision control to give the BT daemon time for connection. // The first data read will activate it again. last = QTime(); return true; } #endif // create a fifo for the nmea simulator, if device starts not with /dev/ if( strncmp( "/dev/", deviceIn, strlen("/dev/") ) != 0 ) { int ret = mkfifo( device.data(), S_IRUSR | S_IWUSR ); if( ret && errno != EEXIST ) { perror("mkfifo"); } } fd = open( device.data(), O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK ); if( fd == -1 ) { perror( "Open GPS device:" ); // Could not open the serial device. #ifdef ERROR_LOG qWarning() << "openGps: Unable to open GPS device" << device << "at transfer rate" << ioSpeedIn; #endif last.start(); // store time point for restart control return false; } if( ! isatty(fd) ) { // Fifo needs no serial initialization. // Write a notice for the user about that fact if( device.startsWith("/dev/") ) { qDebug() << "GpsClient::openGps: Device '" << deviceIn << "' is not a TTY!"; } } else { tcgetattr(fd, &oldtio); // get current options from port // copy current values into new structure for changes memcpy( &newtio, &oldtio, sizeof(newtio) ); // http://www.mkssoftware.com/docs/man5/struct_termios.5.asp // // Prepare serial port settings for raw mode. That is important // otherwise Flarm binary communication do not work! // // - no canonical input (no line oriented input) // - 8 data bits // - no parity // - no interpretation of special characters // - no hardware control // Port control modes // CS8 8 bits per byte // CLOCAL Ignore modem status lines // CREAD Enable receiver newtio.c_cflag = CS8 | CLOCAL | CREAD; // Port input modes // raw input without any special handling newtio.c_iflag = 0; // Port output modes // raw output without any special handling newtio.c_oflag = 0; // Port local modes // raw input/output without any special handling newtio.c_lflag = 0; // The values of the MIN and TIME members of the c_cc array of the termios // structure are used to determine how to process the bytes received. // // MIN represents the minimum number of bytes that should be received when // the read() function returns successfully. // // TIME is a timer of 0.1 second granularity (or as close to that value as // can be accommodated) that is used to time out bursty and short-term data // transmissions. newtio.c_cc[VMIN] = 1; newtio.c_cc[VTIME] = 0; // AP: Note, the setting of the speed must be done at last // because the manipulation of the c_iflag and c_oflag can // destroy the already assigned values! Needed me several hours // to find out that. Setting the baud rate under c_cflag seems // also to work. cfsetispeed( &newtio, ioSpeedTerminal ); // set baud rate for input cfsetospeed( &newtio, ioSpeedTerminal ); // set baud rate for output tcflush(fd, TCIOFLUSH); tcsetattr(fd, TCSANOW, &newtio); fcntl(fd, F_SETFL, FNDELAY); // NON blocking io is requested } last.start(); // store time point for supervision control return true; }