Exemple #1
1
int main(int argc, char *argv[]) {

    QApplication app(argc, argv);    

    mainWindow *mw = new mainWindow;
    SerialPort *sp = new SerialPort;
    QString *msg = new QString(QMainWindow::tr("<p>Начало проверки модуля МС-54.011</p>"));


    mw->setWindowTitle(QMainWindow::tr("КИНД.468354.011"));
    mw->resize(1000, 500);
    mw->show();

    msg->append(QMainWindow::tr("<p>setNextLine()</p>"));
    mw->setNextLine(msg);

    QList<QSerialPortInfo> listCom =  sp->getList();
    QListIterator<QSerialPortInfo> i(listCom);
    while(i.hasNext()){
        msg->append(i.next().portName());
        mw->setNextLine(msg);
    }

    return app.exec();
 }
DWORD SerialPort::ThreadProc (LPVOID lpdwThreadParam ) {
    SerialPort *port =  (SerialPort *)lpdwThreadParam;
    HANDLE hCOM = port->get_com();
    DWORD read;
    const int buffSize = 1024;
    char buff[buffSize];
    while (true) {
        read = 0;
        bool res = ReadFile(hCOM, buff, buffSize, &read,0);
        if(!port->mTreadFlag)
        	break;
        if(res) {
            if(read > 0) {
                port->mReadError = false;
                buff[read]='\0';
                SerialPortRecieved(port, buff, read);
                port->mBytesRecivedSinceLastSend += read;
            } else {
                if(GetCommModemStatus(hCOM, &read)==0) {
                    if(port->mReadError == false)
                        SerialPortError(port, ERROR_READ_STRING);
                    port->mReadError = true;
                } else {
                    port->mReadError = false;
                }
                port->sleep(100);
            }
        } else {
            port->mReadError = true;
            SerialPortError(port, ERROR_READ_STRING);
            port->sleep(100);
        }
    }
    return 0;
}
void SerialMake::setSerialPort(SerialPort *instance)
{
    if(m_serialPort != instance)
    {
        if(m_serialPort)
        {
            SerialPort *serialPort = m_serialPort; m_serialPort = NULL;

            serialPort->setSerialMake(NULL);

            disconnect(serialPort, SIGNAL(portDestroyedOrChanged()),
                       this, SLOT(handlePortDestroyedOrChanged()));
        }

        if(instance)
        {
            m_serialPort = instance;

            m_serialPort->setSerialMake(this);

            connect(m_serialPort, SIGNAL(portDestroyedOrChanged()),
                    this, SLOT(handlePortDestroyedOrChanged()));
        }
    }
}
MM::Device* SerialManager::CreatePort(const char* portName)
{
   // check if the port already exists
   std::vector<SerialPort*>::iterator i;
   for (i=ports_.begin(); i!=ports_.end(); i++)
   {
      char name[MM::MaxStrLength];
      (*i)->GetName(name);
      if (strcmp(name, portName) == 0)
      {
          (*i)->LogMessage(("adding reference to Port " + std::string(portName)).c_str() , true);
         (*i)->AddReference();
         return *i;
      }
   }

   // no such port found, so try to create a new one
   SerialPort* pPort = new SerialPort(portName);
   //pPort->LogMessage(("created new Port " + std::string(portName)).c_str() , true);
   ports_.push_back(pPort);
   pPort->AddReference();
   //pPort->LogMessage(("adding reference to Port " + std::string(portName)).c_str() , true);
   return pPort;

}
bool MachineCommand::ExecCommand(SerialPort &sp, const char *cmd, const char *ret)
{
	char ans[5];

	do
	{
		// TODO: Check for errors in write/ReadLine in sp.
		sp.WriteLine(cmd);
		sp.ReadLine(ans, sizeof(ans));

		if (strcmp(ans, M_ANS_ERROR) == 0)
		{
			sp.WriteLine(M_DO_CR);
			sp.ReadLine(ans, sizeof(ans));
			if (strcmp(ans, M_ANS_CC) != 0)
			{
				// TODO: Set errormsg somewhere (??)
				throw MachineEvent(EVENT_MACHINE_ERROR, "Expected 'CC', recieved " + string(ans));
				return false;
			}
			else
			{
				continue;
			}
		}
	} while (strcmp(ans, ret) != 0);
	
	return true;
}
static void * thread_start(void *arg)
{
    SerialPort *port =  (SerialPort *)arg;
    int hCOM = port->getCom();

    const int buffSize = 1024;
    char buff[buffSize];
    while (port->mTreadFlag) {
        int rb = read(hCOM, buff, buffSize);
        if(rb>0) {
            port->mReadError = false;
            buff[rb]='\0';
            SerialPortRecieved(port, buff);
            port->lastCharRecieved = buff[rb-1];
        } else if(rb==0) {
            if(port->mReadError==false)
                SerialPortError(port, ERROR_READ_STRING);
            port->mReadError = true;
            usleep(50000);
        } else {
            port->mReadError = false;
            usleep(50000);
        }
    }
    port->mTreadFlag = true;
    return 0;
}
Exemple #7
0
void send_package(SerialPort& port, MessagePackage& package) try
{
	array<uint8_t, 256> a;
	auto succ = package.SerializeToArray(a.data(), a.size());
	assert(succ);

	auto s = package.ByteSize();

	cout << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> size = " << s << endl;
	cout << package.DebugString() << endl;

	printf("0x%02x ", s);
	for (size_t i = 0; i<s; ++i)
	{
		printf("0x%02x ", a[i]);
	}
	cout << endl;


	cout << ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" << endl;



	port.writebyte(static_cast<uint8_t>(s));
	port.write(a.data(), s);

	// exit(0);
}
catch(std::exception& ex)
{
	std::cerr << ex.what() << std::endl;
}
void * SerialPort::thread_start(void *arg) {
    SerialPort *port =  (SerialPort *)arg;
    int hCOM = port->get_com();

    const int buffSize = 1024;
    char buff[buffSize];
    while (true) {
        int rb = read(hCOM, buff, buffSize);
        if(!port->mTreadFlag)
        	break;
        if(rb>0) {
            port->mReadError = false;
            buff[rb]='\0';
            SerialPortRecieved(port, buff, rb);
            port->mBytesRecivedSinceLastSend += rb;
        } else if(rb==0) {
            if(port->mReadError==false)
                SerialPortError(port, ERROR_READ_STRING);
            port->mReadError = true;
            port->sleep(100);
        } else {
            port->mReadError = false;
            port->sleep(100);
        }
    }
    return 0;
}
void CheckCurrPort::run()
{
//    qDebug()<<QTime::currentTime().toString()<<"startt";
    while(true){
        msleep(1500);
        bool found=0;
        foreach (const SerialPortInfo &info, SerialPortInfo::availablePorts()){  //SerialPortInfo &info, SerialPortInfo::availablePorts())

            if(info.portName()==currPort){
                found=1;
                SerialPort testConn;//(currPort);
                testConn.setPort(currPort);
                if(testConn.open(QIODevice::ReadWrite)){
                   //???? testConn.close();
                    emit portDisconnected();
                    //closeSerialPort(1);
//                    qDebug()<<QTime::currentTime().toString()<<"opened!";
                    //return;
                } /*else {
                    qDebug()<<QTime::currentTime().toString()<<"can not open";
                }*/
                break;
            }
       }
        if(!found){
//            closeSerialPort(1);            
//             qDebug()<<QTime::currentTime().toString()<<" not found!";
             emit portDisconnected();
             //return;
        }
    }
//    qDebug()<<QTime::currentTime().toString()<<"exitttt";
}
void ChooseConnectionDlg::on_actionCreateSerialPort_triggered()
{
    SerialPort * port = sConMgr2.createSerialPort();
    port->setName(tr("New Serial Port"));
    port->setDeviceName("COM1");
    this->focusNewConn(port);
    ui->connectionNameEdit->setFocus();
}
Exemple #11
0
 void
 onResourceAcquisition(void)
 {
   setEntityState(IMC::EntityState::ESTA_BOOT, Status::CODE_INIT);
   m_uart = new SerialPort(m_args.uart_dev, m_args.uart_baud);
   m_uart->setCanonicalInput(true);
   m_uart->flush();
 }
static int prSerialPort_Close(struct VMGlobals *g, int numArgsPushed)
{
	PyrSlot* self = g->sp;
	SerialPort* port = (SerialPort*)getSerialPort(self);
	if (port == 0) return errFailed;
	port->stop();
	return errNone;
}
/// <summary>
/// Entry point for the application
/// </summary>
/// <param name="hInstance">handle to the application instance</param>
/// <param name="hPrevInstance">always 0</param>
/// <param name="lpCmdLine">command line arguments</param>
/// <param name="nCmdShow">whether to display minimized, maximized, or normally</param>
/// <returns>status</returns>
int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow)
{
	port1.connect(L"\\\\.\\COM17");
	port2.connect2(L"\\\\.\\COM21"); //neu

	CSkeletonBasics application;
    application.Run(hInstance, nCmdShow);
}
void BluetoothSinkPlugin::newConnection(string, QDBusUnixFileDescriptor fd, QVariantMap)
{
	SerialPort *bluetoothDev = new SerialPort();
	bluetoothDev->setDescriptor(fd.fileDescriptor());
	auto client = amb::make_shared(new amb::AmbRemoteServer(bluetoothDev, routingEngine));
	client->disconnected = [this, client]() {
		removeOne(&clients, client);
	};

	clients.push_back(client);
}
Exemple #15
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTextCodec *c = QTextCodec::codecForName("UTF-8");
    QTextCodec::setCodecForCStrings(c);
    QTextCodec::setCodecForLocale(c);
    QTextCodec::setCodecForTr(c);
    SerialPort w;
    w.show();
    
    return a.exec();
}
int main()
{
	Dualshock3 joystick;
	joystick.connect();
	
	int err=serialPort.connect("//dev//ttyACM0");
	
	send_command('n', 0);

	while( 1 ) 	/* infinite loop */
	{

		joystick.getData();
		
		if (joystick.button[16]){
			serialPort.disconnect();
			close( joy_fd );
			system("sixad --stop &");
			exit(0);
		}
		
		joystick.getData();
		
		// Detect conflits and process input
		if (joystick.axis[12] != 0 && joystick.axis[13] != 0){
			// Rumbleeeeeee
			send_command('n', 0);
		}else if (joystick.axis[12] == 0 && joystick.axis[13] != 0){
			//input_processing(FWD, joystick.axis[13]);
			cout << "frente" << endl;
			send_command('f', joystick.axis[12]/547);
		}else if(joystick.axis[12] != 0 && joystick.axis[13] == 0){
			//input_processing(BCK, joystick.axis[12]);
			send_command('b', joystick.axis[13]/547);
		}else{
			send_command('n', 0);
		}
		
		joystick.getData();
		
		if (joystick.axis[0] > 0){
			send_command('r', joystick.axis[0]);
		}else if(joystick.axis[0] < 0){
			send_command('l', abs(joystick.axis[0]));
		}else{
			send_command('l', 0);
		}
	}

	serialPort.disconnect();
	close( joy_fd );	/* too bad we never get here */
	return 0;
}
Exemple #17
0
void send(Field& packet)
{
	try
	{
		SerialPort port;
		port.write(packet);
	}
	catch (AlphaException& e)
	{
		cout << "Error: " << e.what() << endl;
		throw;
	}
}
int MachineCommand::ExecCommandInt(SerialPort &sp, const char *cmd)
{
	char ans[5];
	int i;
	// TODO: Check for errors in write/ReadLine in sp.
	sp.WriteLine(cmd);
	sp.ReadLine(ans, sizeof(ans));
	if(EOF == sscanf_s(ans, "%d", &i))
	{
		return -1;
	}
	
	return i;
}
int serial() {
    printf("Starting test serial\n");
    SerialPort serialPort;
    std::thread th([&] {
        serialPort.start("/dev/cu.usbmodem1411", 230400);
    });
    //usleep(100000);
    uint8_t msg[1024] = {0};
    int size;
    printf("try to send simulator start\n");
    serialPort.write_some((char *) msg, size);
    //usleep(10000000);
    serialPort.stop();
    return 0;
}
static int prSerialPort_Cleanup(struct VMGlobals *g, int numArgsPushed)
{
	PyrSlot* self = g->sp;
	SerialPort* port = (SerialPort*)getSerialPort(self);

	if (port == 0) return errFailed;

	port->cleanup();

	post("SerialPort Cleanup\n");

	delete port;
	SetNil(slotRawObject(self)->slots+0);
	return errNone;
}
Exemple #21
0
int main()
{
	VideoCapture webcam(3);
	Mat frame;

	webcam.set(CV_CAP_PROP_FRAME_WIDTH, height);
	webcam.set(CV_CAP_PROP_FRAME_HEIGHT, width);

	if (serialPort.connect("//dev//ttymxc3")==0) {
		cout << "Can't open serial port" << endl;
		return -1;
	}
	while(true)
	{
		timer.reset();
		webcam.read(frame);
		cv::blur( frame, frame, Size(4,4) );
		imshow("Blured",frame);

		Mat frame_can = Mat::zeros( frame.size(), CV_8UC3 );
		cv::Canny( frame, frame_can, 50, 200, 3 );
		detect_lines(frame_can, frame, "Canny");

		waitKey(5);

		cout << "Timer: "  << timer.elapsed() << endl;

	}
	return 0;
}
static int prSerialPort_Next(struct VMGlobals *g, int numArgsPushed)
{
	PyrSlot* self = g->sp;
	SerialPort* port = (SerialPort*)getSerialPort(self);
//	printf( "port %i", port );
	if (port == 0) return errFailed;

	uint8_t byte;
	if (port->get(&byte)) {
		SetInt(self, byte);
	} else {
		SetNil(self);
	}

	return errNone;
}
Exemple #23
0
      void
      onResourceAcquisition(void)
      {
        setEntityState(IMC::EntityState::ESTA_BOOT, Status::CODE_INIT);

        try
        {
          m_uart = new SerialPort(m_args.uart_dev, m_args.uart_baud);
          m_uart->setCanonicalInput(true);
          m_uart->flush();
        }
        catch (std::runtime_error& e)
        {
          throw RestartNeeded(e.what(), 30);
        }
      }
Exemple #24
0
		virtual int onReadable(SerialPort& sp){
			char buf[100];
			int len = sp.read(buf, sizeof(buf));
			buf[len] = 0;
			InfoLog("Receive data from matrix len = "<<len);
			return 0;
		}
bool send_request(std::string request)
{
#if(DEBUG_MODE)
    ROS_INFO("DEBUG MODE request to serial port:\n %s",request.c_str());
#endif
#if(SERIAL_ON)
    if(lsc.isOpen())
    {
        lsc.writeData(request.c_str(),request.length());
        usleep(15000);
    }
    else
        return false;
#endif
    return true;
}
Exemple #26
0
      bool
      sendCommand(const char* cmd, const char* reply)
      {
        char bfr[128];

        m_uart->writeString(cmd);

        if (Poll::poll(*m_uart, 1.0))
        {
          m_uart->readString(bfr, sizeof(bfr));
          if (std::strcmp(bfr, reply) == 0)
            return true;
        }

        return false;
      }
Exemple #27
0
      void
      onMain(void)
      {
        char bfr[32];

        while (!stopping())
        {
          consumeMessages();

          if (m_wdog.overflow())
          {
            setEntityState(IMC::EntityState::ESTA_ERROR, Status::CODE_COM_ERROR);
            throw RestartNeeded(DTR(Status::getString(CODE_COM_ERROR)), 5);
          }

          if (!Poll::poll(*m_uart, 1.0))
            continue;

          size_t rv = m_uart->readString(bfr, sizeof(bfr));

          if (rv == 0)
            throw RestartNeeded(DTR("I/O error"), 5);

          if (std::sscanf(bfr, "%f", &m_sspeed.value) != 1)
            continue;

          if ((m_sspeed.value < c_min_speed) || (m_sspeed.value > c_max_speed))
            m_sspeed.value = -1;

          m_wdog.reset();
          dispatch(m_sspeed);
        }
      }
BOOL InitHardware(void)
{
	/// Fill DCB structure with settings
	DCB dcb;
	memset(&dcb, 0, sizeof(dcb));

	dcb.BaudRate = CBR_115200;
	dcb.ByteSize = 8;
	dcb.Parity = NOPARITY;
	dcb.StopBits = ONESTOPBIT;

	/// Open port and check if failed
	BOOL retval = g_cSerialPort.open(dcb, _T("COM3"));
	if (!retval)
	{
		return FALSE;
	}

	/// Assign serial port to Modbus class.
	retval = g_cModbus.setSerialPort(&g_cSerialPort);
	if (!retval)
	{
		return FALSE;
	}

	return TRUE;
}
Exemple #29
0
void SendData( const void *buf, size_t bytesToWrite )
{
    if ( gDebug )
    {
        DumpMem( "Send", 0, buf, bytesToWrite );
    }
    gSerialPort.Write( buf, bytesToWrite );

} // SendData
static int prSerialPort_RXErrors(struct VMGlobals *g, int numArgsPushed)
{
	PyrSlot* self = g->sp;
	SerialPort* port = (SerialPort*)getSerialPort(self);
	if (port == 0) return errFailed;
	SetInt(self, port->rxErrors());
	return errNone;
}