您如何通过蓝牙和Python处理和接收串行数据?
我正在尝试制作一个简单的Python服务器,该服务器通过蓝牙将数据访问为explained here.
我的server.py文件在发送文本“ temp”时发送一个随机数,它是:
#!/usr/bin/env pythonimport osimport globimport timeimport randomfrom bluetooth import *def read_temp(): return random.random()server_sock=BluetoothSocket( RFCOMM )server_sock.bind(("",PORT_ANY))server_sock.Listen(1)port = server_sock.getsockname()[1]uuID = "94f39d29-7d6d-437d-973b-fba39e49d4ee"advertise_service( server_sock, "TestServer", service_ID = uuID, service_classes = [ uuID, SERIAL_PORT_CLASS ], profiles = [ SERIAL_PORT_PROfile ], # protocols = [ OBEX_UUID ] )while True: print "Waiting for connection on RFCOMM channel %d" % port clIEnt_sock, clIEnt_info = server_sock.accept() print "Accepted connection from ", clIEnt_info try: data = clIEnt_sock.recv(1024) if len(data) == 0: break print "received [%s]" % data if data == 'temp': data = str(read_temp())+'!' clIEnt_sock.send(data) else: data = 'WTF!' clIEnt_sock.send(data) print "sending [%s]" % data except IOError: pass except KeyboardInterrupt: print "disconnected" clIEnt_sock.close() server_sock.close() print "all done" break
当我第一次运行它时,我得到了错误:
bluetooth.btcommon.BluetoothError: (2, 'No such file or directory')
可以通过启用兼容模式并通过编辑文件/lib/systemd/system/bluetooth.service并更改行来加载串行配置文件来修复Googled showed
ExecStart=/usr/lib/bluetooth/bluetoothd
至:
ExecStart=/usr/lib/bluetooth/bluetoothd -C
然后运行sudo sdptool add SP.
现在python server.py似乎可以正常运行,并且我可以将运行它的机器与我的AndroID手机配对.但是,似乎无法接收任何数据.
我曾经尝试使用蓝牙终端仿真应用程序,例如BlueTerm,BT Simple Terminal和Arduino BT,但是当我连接到服务器时,输入文本并按Enter,则server.py没有响应.它最初将报告“ Accepted connection …”并且已接收到空字符串,但此后将什么也没有接收到.
由于没有报告任何明显的错误,所以我不确定如何诊断问题.如何确定问题是否出在我的Python代码中?还是服务器上的蓝牙配置?还是我的AndroID手机?
解决方法:
正确的代码是:
#!/usr/bin/env python"""A simple test server that returns a random number when sent the text "temp" via Bluetooth serial."""import osimport globimport timeimport randomfrom bluetooth import *server_sock = BluetoothSocket( RFCOMM )server_sock.bind(("",PORT_ANY))server_sock.Listen(1)port = server_sock.getsockname()[1]uuID = "94f39d29-7d6d-437d-973b-fba39e49d4ee"advertise_service( server_sock, "TestServer", service_ID = uuID, service_classes = [ uuID, SERIAL_PORT_CLASS ], profiles = [ SERIAL_PORT_PROfile ], # protocols = [ OBEX_UUID ] )print "Waiting for connection on RFCOMM channel %d" % portclIEnt_sock, clIEnt_info = server_sock.accept()print "Accepted connection from ", clIEnt_infowhile True: try: req = clIEnt_sock.recv(1024) if len(req) == 0: break print "received [%s]" % req data = None if req in ('temp', '*temp'): data = str(random.random())+'!' else: pass if data: print "sending [%s]" % data clIEnt_sock.send(data) except IOError: pass except KeyboardInterrupt: print "disconnected" clIEnt_sock.close() server_sock.close() print "all done" break
总结 以上是内存溢出为你收集整理的android-使用Python通过蓝牙串行进行通信全部内容,希望文章能够帮你解决android-使用Python通过蓝牙串行进行通信所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)