Gurux串行媒体用于与串行端口连接进行通信。
gurux-serial的Python项目详细描述
有关概述,请参见Gurux。
加入gurux社区或按照@Gurux进行项目更新。
使用gurux.serial组件,您可以使用串行端口连接轻松地同步或异步发送数据。
开源gxnet媒体组件,由gurux有限公司制造,是gxmedias媒体组件集的一部分,它的编程接口帮助您通过选择的连接类型实现通信。gurux媒体组件还支持以下连接类型:串行端口。
更多信息请查看Gurux。
我们正在更新gurux网页上的文档。
如果你有问题,可以在guruxForum中提问。
您可以从http://www.github.com/gurux或intall包中获取源代码:
pipinstallgurux-commonpipinstallgurux-serial
简单示例
使用前必须设置以下设置:
- 端口名
- 波特率
- 数据位
- 奇偶性
- 停止位
还可以添加侦听器来侦听以下事件。
- 错误
- 收到时
- onmediastatechange
- 合同
- onproperty已更改
此示例将数据发送到串行端口并等待答复。 使用前请更改串行端口。
importtimefromgurux_commonimportReceiveParametersfromgurux_commonimportIGXMediaListenerfromgurux_common.enums.TraceLevelimportTraceLevelfromgurux_serialimportGXSerial#pylint: disable=no-self-argumentclasssampleclient(IGXMediaListener):def__init__(self):#List available serial ports.print("Available ports:")print(str(GXSerial.getPortNames()))#Define End Of Packet char.eop='\r'#TODO: Update correct port and serial port settings.media=GXSerial("SERIAL PORT TO USE")#Start to listen events from the media.media.addListener(self)#Show all traces.media.trace=TraceLevel.VERBOSE#Set EOP for the media.media.eop=eoptry:#Open the connection.media.open()r=ReceiveParameters()r.eop=eop#Minimium amount of bytes to receive.r.count=5#Wait reply for 2 seconds.r.waitTime=2000#############################Send data synchronously.withmedia.getSynchronous():media.send("Hello world!")#Send EOPmedia.send('\r')ret=media.receive(r)ifret:print(str(r.reply.decode("ascii")))else:raiseException("Failed to receive reply from the server.")#############################Send async data.media.send("Notify from the meter!\r")#Wait 1 second to receive reply from the server.time.sleep(1)exceptExceptionasex:print(ex)media.close()media.removeListener(self)defonError(self,sender,ex):""" Represents the method that will handle the error event of a Gurux component. sender : The source of the event. ex : An Exception object that contains the event data. """print("Error has occured. "+str(ex))defonReceived(self,sender,e):"""Media component sends received data through this method. sender : The source of the event. e : Event arguments. """print("New data is received. "+str(e))defonMediaStateChange(self,sender,e):"""Media component sends notification, when its state changes. sender : The source of the event. e : Event arguments. """print("Media state changed. "+str(e))defonTrace(self,sender,e):"""Called when the Media is sending or receiving data. sender : The source of the event. e : Event arguments. """print("trace:"+str(e))defonPropertyChanged(self,sender,e):""" Event is raised when a property is changed on a component. sender : The source of the event. e : Event arguments. """print("Property {!r} has hanged.".format(str(e)))if__name__=='__main__':sampleclient()