//функция поиска и подключения устройства void FindDevice(const char* devID) { ID = devID; strcpy(bufwr, ID); String port = "\\\\.\\COM"; int i = 1; while ((!connected) && (i < 257)) { OpenPort(port + IntToStr(i)); if(COMport != INVALID_HANDLE_VALUE) { ResumeThread(writer); Sleep(1000); } i++; } if (COMport == INVALID_HANDLE_VALUE) { Form1->Info->Lines->Add("Устройство не найдено!!!"); } }
int CSerialPort::InitPort(CString strComName) { hSerialPort = OpenPort(strComName, CBR_9600,NOPARITY,8, ONESTOPBIT); if(hSerialPort==NULL) { //MessageBox(NULL, "打开指定串口失败,请重新选择串口。","失败", MB_OK|MB_ICONWARNING); return -1; } CString cmd = "AT+CSCA?\r"; char ans[128] ; WritePort(cmd.GetBuffer(0),strlen(cmd)); Sleep(ShortSleepTime); ReadPort(ans,128); CString ansStr = ans; int cou; if((cou=ansStr.Find("+86")) != -1) { m_SmsCenterNum = ansStr.Mid(cou+1,13); } else { return -2; } return 0; }
Comm::Comm(LPCWSTR Port,bool *state) { this->state = state; open = OpenPort(Port); if (open) { std::cout << "open comport success" << std::endl; if (setupdcb(38420)) //38240是波特率 printf("setupDCB success\n"); if (setuptimeout(0, 0, 0, 0, 0)) printf("setuptimeout success\n"); SetCommMask(GethComm(), EV_RXCHAR); //当有字符在inbuf中时产生这个事件 //清除串口的所有操作 PurgeComm(GethComm(), PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT); // 在读写串口之前,还要用PurgeComm()函数清空缓冲区 //PURGE_TXABORT 中断所有写操作并立即返回,即使写操作还没有完成。 //PURGE_RXABORT 中断所有读操作并立即返回,即使读操作还没有完成。 //PURGE_TXCLEAR 清除输出缓冲区 //PURGE_RXCLEAR 清除输入缓冲区 } else std::cout << "cannot open the com port" << std::endl; }
int main(int argc, char **argv) { Args args(argc, argv, "PORT BAUD"); const DeviceConfig config = ParsePortArgs(args); args.ExpectEnd(); InitialiseIOThread(); NullDataHandler handler; std::unique_ptr<Port> port(OpenPort(config, handler)); if (!port) { fprintf(stderr, "Failed to open COM port\n"); return EXIT_FAILURE; } ConsoleOperationEnvironment env; if (!port->WaitConnected(env)) { fprintf(stderr, "Failed to connect the port\n"); return EXIT_FAILURE; } RunUI(*port, env); DeinitialiseIOThread(); return EXIT_SUCCESS; }
BOOL CPort::Open(const char* pszFileName, BOOL fIsSocket) { RIL_LOG_VERBOSE("CPort::Open() - Enter fIsSocket=[%d]\r\n", fIsSocket); BOOL fRet = FALSE; if (NULL == pszFileName) { RIL_LOG_CRITICAL("CPort::Open() - pszFileName is NULL!\r\n"); return FALSE; } if (!m_fIsPortOpen) { if (NULL == m_pFile) { m_pFile = new CFile(); } if (fIsSocket) { fRet = OpenSocket(pszFileName); } else { fRet = OpenPort(pszFileName); } } else { RIL_LOG_CRITICAL("CPort::Open() - Port is already open!\r\n"); } RIL_LOG_VERBOSE("CPort::Open() - Exit\r\n"); return fRet; }
int main(int argc, char **argv) { Args args(argc, argv, "PORT BAUD [NAME=VALUE] [NAME] ..."); const DeviceConfig config = ParsePortArgs(args); Port *port = OpenPort(config, *(Port::Handler *)NULL); if (port == NULL) { fprintf(stderr, "Failed to open COM port\n"); return EXIT_FAILURE; } VegaDevice device(*port); ConsoleOperationEnvironment env; while (!args.IsEmpty()) { const char *p = args.GetNext(); char *q = strdup(p); char *v = strchr(q, '='); if (v == NULL) { if (!device.RequestSetting(q, env)) printf("Error\n"); } else { *v++ = 0; if (!device.SendSetting(q, atoi(v), env)) printf("Error\n"); } free(q); } delete port; return EXIT_SUCCESS; }
int main(int argc, char **argv) { Args args(argc, argv, "PORT BAUD"); const DeviceConfig config = ParsePortArgs(args); args.ExpectEnd(); InitialiseIOThread(); MyHandler handler; Port *port = OpenPort(config, handler); if (port == NULL) { fprintf(stderr, "Failed to open COM port\n"); return EXIT_FAILURE; } if (!port->StartRxThread()) { delete port; fprintf(stderr, "Failed to start the port thread\n"); return EXIT_FAILURE; } while (true) Sleep(10000); delete port; DeinitialiseIOThread(); return EXIT_SUCCESS; }
static bool devInitOne(DeviceDescriptor &device, const DeviceConfig &config, DeviceDescriptor *&nmeaout) { if (config.port_type == DeviceConfig::INTERNAL) { #ifdef ANDROID if (is_simulator()) return true; device.internal_gps = InternalGPS::create(Java::GetEnv(), native_view, device.GetIndex()); return device.internal_gps != NULL; #else return false; #endif } const struct DeviceRegister *Driver = devGetDriver(config.driver_name); if (Driver == NULL) return false; Port *Com = OpenPort(config, device); if (Com == NULL) return false; if (!device.Open(Com, Driver)) { delete Com; return false; } if (nmeaout == NULL && (Driver->Flags & (1l << dfNmeaOut))) nmeaout = &device; return true; }
// Haiku : 0 = /dev/ports/usb0 .. 3 = /dev/ports/usb3 CCPCBooster::CCPCBooster(std::string comNumber): _COMPortNumber(comNumber), _currentState(PortFailed), _currentError(ErrOK) { OpenPort(); }
int main(int argc, char **argv) { Args args(argc, argv, "PORT BAUD"); const DeviceConfig config = ParsePortArgs(args); args.ExpectEnd(); InitialiseIOThread(); Port *port = OpenPort(config, nullptr, *(DataHandler *)nullptr); if (port == NULL) { fprintf(stderr, "Failed to open COM port\n"); return EXIT_FAILURE; } ConsoleOperationEnvironment env; if (!port->WaitConnected(env)) { delete port; DeinitialiseIOThread(); fprintf(stderr, "Failed to connect the port\n"); return EXIT_FAILURE; } FlarmDevice flarm(*port); RunUI(flarm, env); delete port; DeinitialiseIOThread(); return EXIT_SUCCESS; }
int SerialClass::Write(const void *WriteBuffer, unsigned short Length) { if (m_commHandle == INVALID_COMMS_HANDLE) OpenPort(); int ret = CommSend(m_commHandle, WriteBuffer, Length); CsDebug(5, (5, "SerialClass::Write(h=%d): len=%d, ret=%d", m_commHandle, Length, ret)); return COMMSERIAL_SUCCESS; }
//--------------------------------------------------------------------------- __fastcall CTA5Serial::CTA5Serial(int nPort) { m_bInitOK=OpenPort(nPort); m_dX[0]=0.0; m_dX[1]=0.0; m_dY[0]=0.0; m_dY[1]=0.0; }
int main(int argc, char **argv) { Connection con; PortConnection port; const char *name = TIMING_NAME; const char *other, *now; struct sigaction sa; sa.sa_handler= SIG_IGN; sa.sa_flags=SA_NOCLDWAIT; /* this old code produced a warning struct sigaction sa = { SIG_IGN, 0, 0, SA_NOCLDWAIT };*/ x = time(0); sigaction (SIGCHLD, &sa, 0); { char buf[1024]; FILE *x; x = fopen ("modulus.hex", "r"); if (! x) { perror ("modulus.hex"); exit (2); } fgets (buf, 1024, x); fclose (x); LHex2Long (buf, &n); } /*************** Globales Port eröffnen ***************/ if (!(port=OpenPort(name))) { fprintf(stderr,"TIMING_DAEMON: Kann das Dämon-Port \"%s\" nicht erzeugen: %s\n",name,NET_ErrorText()); exit(20); } /******************* Hauptschleife **********************/ while (1) { /************** Auf Verbindung auf dem Port warten ****************/ if (!(con=WaitAtPort(port))) { fprintf(stderr,"TIMING_DAEMON: WaitAtPort ging schief: %s\n",NET_ErrorText()); exit(20); } other = PeerName(port); now = Now(); fprintf (stderr, "Connect from %s: %s\n", other, now); fflush (stderr); x += time(0); handle_connection (con, other, now); DisConnect (con); } return 0; }
/******************************************************************** Declaration: CommPort constructor without parameters Call: Input: Returns: *********************************************************************/ CommPort::CommPort() { m_sComPort = new TCHAR[50]; SetBufferSizeVar(1200); //printf ("CommPort constructor 0 start.\n"); m_BitRate = br9600; sprintf(m_sComPort, "%s", "COM1"); OpenPort(); }
int main(int argc, char **argv) { Args args(argc, argv, "PORT BAUD"); const DeviceConfig config = ParsePortArgs(args); args.ExpectEnd(); InitialiseIOThread(); MyHandler handler; Port *port = OpenPort(config, handler); if (port == NULL) { fprintf(stderr, "Failed to open COM port\n"); return EXIT_FAILURE; } ConsoleOperationEnvironment env; if (!port->WaitConnected(env)) { delete port; DeinitialiseIOThread(); fprintf(stderr, "Failed to connect the port\n"); return EXIT_FAILURE; } if (!port->StartRxThread()) { delete port; DeinitialiseIOThread(); fprintf(stderr, "Failed to start the port thread\n"); return EXIT_FAILURE; } char stamp[6] = ""; char line[1024]; while (fgets(line, sizeof(line), stdin) != NULL) { if (memcmp(line, "$GP", 3) == 0 && (memcmp(line + 3, "GGA", 3) == 0 || memcmp(line + 3, "RMC", 3) == 0) && line[6] == ',' && strncmp(stamp, line + 7, sizeof(stamp)) != 0) { /* the time stamp has changed - sleep for one second */ Sleep(1000); strncpy(stamp, line + 7, sizeof(stamp)); } if (!port->FullWriteString(line, env, 1000)) { fprintf(stderr, "Failed to write to port\n"); delete port; return EXIT_FAILURE; } } delete port; DeinitialiseIOThread(); return EXIT_SUCCESS; }
// port - serial device name // speed - eg 9600 // data_bits - typically 8 // parity - 'n', 'o', 'e', 'm', 's' // stop_bits - 1 or 2); int SerialClass::OpenPort(const char* port, unsigned long speed, unsigned int data_bits, char parity, unsigned int stop_bits) { strncpy(m_port, port, MAX_PORTNAME_LENGTH); m_speed = speed; m_data_bits = data_bits; m_parity = parity; m_stop_bits = stop_bits; // open the port return OpenPort(); }
/******************************************************************** Declaration: CommPort constructor without parameters Call: Input: Returns: *********************************************************************/ CommPort::CommPort() { m_sComPort = new TCHAR[50]; SetBufferSizeVar(1200); printf ("CommPort constructor MAIN start.\n"); m_BitRate = br9600; m_lGenRecBytes = 0; m_lGenSenBytes = 0; sprintf(m_sComPort, "%s", "COM1"); OpenPort(); }
void net_init( char *ip, int32_t remotePort, int32_t localPort ) { printf("Connecting to IP : %s , remote port %d , local port :%d\n", ip, remotePort,localPort); // Initialize SDL_net InitSDL_Net(); OpenPort( localPort ); SetIPAndPort( ip, remotePort ); CreatePacket( 512 ); }
void SerialMonitor::ReOpenPort(void) { bool go = true; if (serialPort.isOpen()) { go = ClosePort(); } if (go) { //connect (&serialPort, SIGNAL(readyRead()), this, SLOT(ReadSerialPort())); OpenPort(); } }
// --- когда нажали на кнопку открытия порта ----------------------------------- void MainWindow::on_tryToConnect_clicked() { // заставить выбрать один из портов if(ui->com1rbt->isChecked()==false && ui->com2rbt->isChecked()==false) { logstr = tr("] <font color=red>вы не выбрали порт</font>"); string2log(logstr); return; } // заставить настроить порт if(ui->comboBox_2->currentIndex()==0 || ui->comboBox_3->currentIndex()==0 || ui->comboBox_4->currentIndex()==0 || ui->comboBox_5->currentIndex()==0) { logstr = tr("] <font color=red>необходимо сначала настроить порт</font>"); string2log(logstr); return; } // если порт уже открыт if(portAlreadyChoosen) { logstr = tr("] <font color=red>порт уже открыт</font>"); string2log(logstr); return; } // смотря какой порт выбран if(ui->com1rbt->isChecked()==true) portstr = "COM1"; else portstr = "COM2"; // попытаться открыть его workPort = OpenPort(portstr); attmpt = true; // попытка установления соединения состоялась portAlreadyChoosen = true; // порт выбрали disableSettingsChange(); if(workPort == INVALID_HANDLE_VALUE) { logstr = tr("] <font color=red>возможно, порт отключён или занят</font>"); string2log(logstr); portAlreadyChoosen = false; return; } else { ui->label->hide(); ui->label_2->show(); ui->groupBox->setEnabled(true); ui->listenBtn->setEnabled(true); emit curPortHandle(workPort); } }
int main(int argc, char **argv) { Args args(argc, argv, "PORT BAUD"); const DeviceConfig config = ParsePortArgs(args); args.ExpectEnd(); InitialiseIOThread(); Port *port = OpenPort(config, nullptr, *(DataHandler *)nullptr); if (port == NULL) { delete port; fprintf(stderr, "Failed to open COM port\n"); return EXIT_FAILURE; } ConsoleOperationEnvironment env; if (!port->WaitConnected(env)) { delete port; DeinitialiseIOThread(); fprintf(stderr, "Failed to connect the port\n"); return EXIT_FAILURE; } char buffer[4096]; while (true) { switch (port->WaitRead(env, 60000)) { case Port::WaitResult::READY: break; case Port::WaitResult::TIMEOUT: continue; case Port::WaitResult::FAILED: delete port; return EXIT_FAILURE; case Port::WaitResult::CANCELLED: delete port; return EXIT_SUCCESS; } int nbytes = port->Read(buffer, sizeof(buffer)); if (nbytes < 0) break; fwrite((const void *)buffer, 1, nbytes, stdout); } delete port; DeinitialiseIOThread(); return EXIT_SUCCESS; }
bool DeviceDescriptor::DoOpen(OperationEnvironment &env) { assert(config.IsAvailable()); if (config.port_type == DeviceConfig::PortType::INTERNAL) return OpenInternalSensors(); if (config.port_type == DeviceConfig::PortType::DROIDSOAR_V2) return OpenDroidSoarV2(); if (config.port_type == DeviceConfig::PortType::I2CPRESSURESENSOR) return OpenI2Cbaro(); if (config.port_type == DeviceConfig::PortType::NUNCHUCK) return OpenNunchuck(); if (config.port_type == DeviceConfig::PortType::IOIOVOLTAGE) return OpenVoltage(); if (config.port_type == DeviceConfig::PortType::ADCAIRSPEED) return OpenAdcAirspeed(); reopen_clock.Update(); Port *port = OpenPort(config, *this); if (port == NULL) { TCHAR name_buffer[64]; const TCHAR *name = config.GetPortName(name_buffer, 64); StaticString<256> msg; msg.Format(_T("%s: %s."), _("Unable to open port"), name); env.SetErrorMessage(msg); return false; } while (port->GetState() == PortState::LIMBO) { env.Sleep(200); if (env.IsCancelled() || port->GetState() == PortState::FAILED) { delete port; return false; } } if (!Open(*port, env)) { delete port; return false; } return true; }
int main(int argc, char* argv[]) { long status; unsigned long cardType; unsigned long cardSN; BYTE userID; status = OpenPort(1, 9600); if (!status) { status = LinkRW(); if (status) { ClosePort(); fprintf(stderr, "Connect Fail\n"); return -1; } fprintf(stderr, "Connect Succeed\n"); //beepOn(); //card polling while (1) { status = GetCardType(&cardType); if (!status) { delayMS(5); if (cardType == 4) { //Mifare 1 status = mfGetCardSnr(&cardSN); if (status) { status = mfTransKey(); if (status) { status = SelectCard(cardSN); if (!status) { fprintf(stderr, "Activate Succeed\n"); userID = getUserID(cardSN); fprintf(stdout, "%x", userID); HaltCard(); //delayMS(3000); break; } } } } } } } else { fprintf(stderr, "Connect Fail\n"); return -1; } ClosePort(); return 0; }
bool NcrComPort::SendData(const char *data) { if (hPort == 0) { if (OpenPort() == -1) return false; } DWORD byteswritten; bool retVal = WriteFile(hPort, data, 1, &byteswritten, NULL); return retVal; }
PORTHANDLE BeginJob(HPERIPHERAL hPeripheral,LPTSTR lpszPortName, LPTSTR lpszJobName) { int hPort; PSPCB pSPCB; TRACE0(TEXT("--BeginJob\r\n")); hPort = FindHandle(lpszPortName); if (!hPort) { TRACE0(TEXT("--BeginJob: Bad parameter\r\n")); return(QP_BEGIN_JOB_FAIL); } pSPCB = &SPCBTable[hPort]; if (pSPCB->DeviceState.bJobPresent) { TRACE1(TEXT("--BeginJob: Prior job (%s)\r\n"),pSPCB->DeviceState.szJobName); return(QP_BEGIN_JOB_FAIL); } if (!EnterCritSem0(BEGIN_JOB_TIMEOUT)) { return(QP_BEGIN_JOB_FAIL); } // open the port if (OpenPort(hPeripheral,PORT_OWN_QP,pSPCB)) { TRACE0(TEXT("--BeginJob: OpenPort failed\r\n")); return(QP_BEGIN_JOB_FAIL); } LeaveCritSem0(); if ( lpszJobName ) { _tcsncpy(pSPCB->DeviceState.szJobName,lpszJobName,sizeof(pSPCB->DeviceState.szJobName)); pSPCB->DeviceState.szJobName[sizeof(pSPCB->DeviceState.szJobName) - 1] = '\0'; } else pSPCB->DeviceState.szJobName[0] = '\0'; pSPCB->DeviceState.bJobPresent = TRUE; pSPCB->DeviceState.nJobPage = 0; return(hPort); }
bool DeviceDescriptor::DoOpen(OperationEnvironment &env) { assert(config.IsAvailable()); if (config.port_type == DeviceConfig::PortType::INTERNAL) return OpenInternalSensors(); if (config.port_type == DeviceConfig::PortType::DROIDSOAR_V2) return OpenDroidSoarV2(); if (config.port_type == DeviceConfig::PortType::I2CPRESSURESENSOR) return OpenI2Cbaro(); if (config.port_type == DeviceConfig::PortType::NUNCHUCK) return OpenNunchuck(); if (config.port_type == DeviceConfig::PortType::IOIOVOLTAGE) return OpenVoltage(); reopen_clock.Update(); Port *port = OpenPort(config, port_listener, *this); if (port == nullptr) { TCHAR name_buffer[64]; const TCHAR *name = config.GetPortName(name_buffer, 64); StaticString<256> msg; msg.Format(_T("%s: %s."), _("Unable to open port"), name); env.SetErrorMessage(msg); return false; } DumpPort *dump_port = new DumpPort(port); dump_port->Disable(); if (!port->WaitConnected(env) || !OpenOnPort(dump_port, env)) { if (!env.IsCancelled()) ++n_failures; delete dump_port; return false; } ResetFailureCounter(); return true; }
/******************************************************************** Declaration: CommPort constructor with 2 parameters Call: Input: Returns: *********************************************************************/ CommPort::CommPort(const int ComPortNumber, BitRate brBitRate) { SetBufferSizeVar(1200); m_BitRate = brBitRate; //printf ("CommPort constructor X X start.\n"); if (ComPortNumber <= 0) { CommPort(); // if error - call default. } else { m_sComPort = new TCHAR[50]; sprintf(m_sComPort, "COM%d:", ComPortNumber); OpenPort(); } }
STDMETHODIMP CMicroFlash::Print(int iCopies) { HRESULT r; char endLine [] = "\r\n"; DWORD dwBytesWritten; char *pcPrintBuf; int iLineCount, n; // Assume failure r = S_FALSE; pcPrintBuf = NULL; iLineCount = 0; if(!OpenPort()) goto Exit; // Add formfeed to data m_strData.Append (TEXT("\x0C")); // Convert to char data n = m_strData.Length (); pcPrintBuf = new char [n + 1]; wcstombs (pcPrintBuf, m_strData, n); pcPrintBuf [n] = 0; // Wakeup the printer for(iLineCount = 0; iLineCount < 10; iLineCount++) WriteFile(m_hComPort, endLine, strlen(endLine), &dwBytesWritten, NULL); Sleep(500); // Print the buffer for(iLineCount = 0; iLineCount < iCopies; iLineCount++) if(!WriteFile(m_hComPort, pcPrintBuf, strlen(pcPrintBuf), &dwBytesWritten, NULL)) goto Exit; m_strData.Empty (); r = S_OK; Exit: ClosePort (); delete [] pcPrintBuf; return r; }
STDMETHODIMP CComBus::Start(void) { // TODO: Add your implementation code here m_ErrCode = 0; if( !OpenPort( (LPTSTR)(m_port->m_str), m_baudrate ) ) { m_ErrCode = GetErrCode(); return E_FAIL; } if( !CreateThread() ) { m_ErrCode = GetErrCode(); return E_FAIL; } ::Sleep(1000); return S_OK; }
int main(int argc, char **argv) { Args args(argc, argv, "DRIVER PORT BAUD"); Emulator *emulator = LoadEmulator(args); const DeviceConfig config = ParsePortArgs(args); args.ExpectEnd(); InitialiseIOThread(); Port *port = OpenPort(config, *emulator->handler); if (port == NULL) { delete emulator; fprintf(stderr, "Failed to open COM port\n"); return EXIT_FAILURE; } emulator->port = port; ConsoleOperationEnvironment env; emulator->env = &env; if (!port->WaitConnected(env)) { delete port; delete emulator; DeinitialiseIOThread(); fprintf(stderr, "Failed to connect the port\n"); return EXIT_FAILURE; } if (!port->StartRxThread()) { delete port; delete emulator; DeinitialiseIOThread(); fprintf(stderr, "Failed to start the port thread\n"); return EXIT_FAILURE; } while (port->GetState() != PortState::FAILED) Sleep(1000); delete port; delete emulator; DeinitialiseIOThread(); return EXIT_SUCCESS; }