' UTF-8'编解码器不能解码位置6中的字节0xc4:意外的数据结束

时间:2016-03-17 22:43:08

标签: python encoding utf-8 bluetooth

我在Raspberry pi 2上用Python编码。

我试图通过蓝牙同时向两台设备发送多个订单,但它无法正常工作。

根据错误消息,当我向第二个设备发送订单时,我无法解码响应。我已经尝试使用' UTF-8'但它也没有工作......

以下是错误消息:

Traceback (most recent call last):
  File "/home/pi/Desktop/Bluetooth-master/Bluetooth-master/rfcommcli.py", line 60, in <module>
    StartBTClient()
  File "/home/pi/Desktop/Bluetooth-master/Bluetooth-master/rfcommcli.py", line 54, in StartBTClient
    print('reception 2 : ', rec2.decode())
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc4 in position 6: unexpected end of data

所以,请你帮助我。

以下是代码:

import bluetooth


class BT(object):

    address_2 = ('00:04:3E:93:39:A9')
    address_1 = ('00:04:3E:6A:10:A9')

    def __init__(self):
        self.btSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

    def __exit__(self):
        self.Disconnect()

    def Connect(self, mac, port=1):
        self.btSocket.connect((mac, port))
        print('Connecter')

    def Disconnect(self):
        try:
            self.btSocket.close()
        except Exception:
            pass

    def Send(self, data):
        self.btSocket.send(data.encode())

    def Receive(self, size=1024):
        return self.btSocket.recv(size)


def StartBTClient():
    cli = BT()
    print('BT1 Connexion en cours ...')
    #cli.Discover()
    cli.Connect(cli.address_1, 0o01)

    cli2 = BT()
    print('BT2 Connexion en cours ...')
    #cli.Discover()
    cli2.Connect(cli2.address_2, 0o02)
    print('Donner un ordre ... (ordre shutter)')

    while True:
        data = input()
        if (data == 'exit'):
            break
        cli.Send("read\r")
        cli2.Send("read\r")
        rec = cli.Receive()
        rec2 = cli2.Receive()
        print('reception 1 : ', rec.decode())
        print('reception 2 : ', rec2.decode())

    cli.Disconnect()
    cli2.Disconnect()

if __name__ == '__main__':
    StartBTClient()

1 个答案:

答案 0 :(得分:0)

显然,设备#2正在响应UTF-8编码值的一些但不是全部字节。

在尝试解码之前,您需要确保已收到并汇编了邮件的所有字节。这可能涉及多次调用.recv()