Virtual serial port with Python

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.