In Linux debugging serial program, but the following hardware is not in place, so, think of their own simulation of a serial port for use. Try the following code:
#!/usr/bin/env python#Coding=utf-8ImportPtyImportOSImportSelectdefmkpty ():#Open a new TTYMaster1, slave =pty.openpty () slaveName1=os.ttyname (slave) master2, slave=pty.openpty () slaveName2=os.ttyname (slave)Print '\nslave device names:', slaveName1, SlaveName2returnMaster1, Master2if __name__=="__main__": Master1, Master2=Mkpty () whileTrue:#rl=read list, wait until ready to reading #wl=write list, wait until ready to writing #el=exception list, wait for an "exceptional condition" #timeout = 1sRL, wl, el = Select.select ([Master1, Master2], [], [], 1) forDeviceinchRl:data= Os.read (device, 128) Print "read%d data."%len (data)ifdevice = =Master1:os.write (master2, data)Else: Os.write (Master1, data)
Pty is the meaning of fake serial port, but it supports all operation of hardware serial port. So ...
The other one, simulates the data that colleagues send through the serial port. All data written to master is automatically sent to slave. So, we can get the data we want on the slave side.
#!/usr/bin/env python#Coding=utf-8ImportPtyImportOSImport TimeImportArrayImportRandomdefmkpty ():#Make pair of pseudo TTYMaster, slave =pty.openpty () slavename=os.ttyname (slave)Print '\nslave device names:', SlavenamereturnMasterif __name__=="__main__": Master=mkpty () buf= Array.array ('B', [0] * 7) buf[0]= 0x00buf[1] = 0x02buf[2] = 0x8abuf[3] = 0x2dbuf[4] = 0xc5buf[5] = 0x3fbuf[6] = 0x00 whileTrue:ifBUF[1] < 40: buf[1] = buf[1] + 1Else: buf[1] = 1Buf[0]= Buf[0] + 1ifBuf[0] = = 255: buf[0]=0#buf[5] = Random.randint (40,50)BUF[2] = Random.randint (0,250) buf[6] = (buf[0]+buf[1]+buf[2]+buf[3]+buf[4]+buf[5])%256os.write (Master, buf)#Print bufTime.sleep (0.02)
Virtual serial port with Python