且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在kivy中将android.bluetooth.socket输入流转换为python字符串?

更新时间:2022-05-10 04:31:32

我终于找到了似乎可行的解决方案.我有一个Kivy应用程序通过蓝牙与基于Arduino的设备进行通信.在Arduino上,我使用SerialCommand库接收自定义命令并做出相应的响应.在命令通过主线程发送到Arduino的同时,我还有另一个线程,该线程带有循环,该循环从我的Bluetooth套接字读取InputStream. Arduino的响应用<>括起来,当我得到正确的响应时,我提取括号之间的文本并将其发送到我的主线程中的函数.我希望这对您有帮助.

I have finally find a solution that seems to work. I have a Kivy app communicating with an Arduino based device over Bluetooth. On the Arduino I use the SerialCommand library to recieve custom commands and respond accordingly. While the commands is send to my Arduino in the main thread, I have a second thread with a loop that reads the InputStream from my Bluetooth socket. The response from Arduino is enclosed with <>, and when I get a proper response I extract the text between the brackets and send it to a function in my mainthread. I hope this is helpful for you.

from kivy.clock import mainthread
import threading
import jnius

def get_socket_stream(self, name):
    paired_devices =  self.BluetoothAdapter.getDefaultAdapter().getBondedDevices().toArray()
    socket = None
    for device in paired_devices:
        if device.getName() == name:
            socket = device.createRfcommSocketToServiceRecord(
            self.UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"))
            reader = self.InputStreamReader(socket.getInputStream(), 'US-ASCII')
            recv_stream = self.BufferedReader(reader)
            send_stream = socket.getOutputStream()
            break
    socket.connect()
    return recv_stream, send_stream

def connect(self, *args):
    device = self.config.get('bluetooth', 'bt_name')
    try:
        self.recv_stream, self.send_stream = self.get_socket_stream(device)
    except AttributeError as e:
        print e.message
        return False
    except jnius.JavaException as e:
        print e.message
        return False
    except:
        print sys.exc_info()[0]
        return False

    threading.Thread(target=self.stream_reader).start()

def stream_reader(self, *args):
    stream = ''
    while True:
        if self.stop.is_set():
            jnius.detach()
            return
        if self.recv_stream.ready():
            try:
                stream = self.recv_stream.readLine()
            except self.IOException as e:
                print "IOException: ", e.message
            except jnius.JavaException as e:
                print "JavaException: ", e.message
            except:
                print "Misc error: ", sys.exc_info()[0]

            try:
                start = stream.rindex("<") + 1
                end = stream.rindex(">", start)
                self.got_response(stream[start:end])
            except ValueError:
                pass

@mainthread
def got_response(self, response):
    do something...