树莓派连接蓝牙遥控,控制播放音乐

发布时间 2023-08-18 09:25:47作者: cn_gzb

采用的树莓派zerow,根据按键切换音乐

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# [NEW] Device EC:22:05:15:24:0D RMT-EC220515240D

import time
from bluepy.btle import *
from binascii import hexlify
import struct
from Music import *


class NotifyDelegate(DefaultDelegate):
    def __init__(self, params):
        DefaultDelegate.__init__(self)
        self.out = 0

    def handleNotification(self, cHandle, data):
        # print("Notification from Handle: 0x" + format(cHandle, '02X'))
        # print(hexlify(data))
        self.out = hexlify(data)


def Test():
    addr = "EC:22:05:15:24:0D"
    conn = Peripheral(addr)
    ND = NotifyDelegate(conn)
    conn.withDelegate(ND)
    services = conn.getServices()
    for svc in services:
        print("[+] Service: ", svc.uuid)
        characteristics = svc.getCharacteristics()
        for charac in characteristics:
            print("    Characteristic: ", charac.uuid)
            print("        Properties: ", charac.propertiesToString())
        print("*" * 100)

    service_uuid = UUID("0000fff0-0000-1000-8000-00805f9b34fb")
    c_service = conn.getServiceByUUID(service_uuid)
    characteristics = c_service.getCharacteristics()
    notify_char = characteristics[0]
    hEcg = notify_char.getHandle()
    for descriptor in conn.getDescriptors(hEcg, c_service.hndEnd):
        if descriptor.uuid == 0x2902:
            print(f'Client Characteristic Configuration found at handle 0x{format(descriptor.handle, "02X")}')
            hEcgCCC = descriptor.handle
    conn.writeCharacteristic(hEcgCCC, bytes([1, 0]))
    tmp_data = conn.readCharacteristic(0x06)
    print(tmp_data)
    MP3 = ['11.wav', '22.wav', '33.wav', '44.wav', '55.wav', '66.wav']
    while True:
        if conn.waitForNotifications(1.0):
            resp = ND.out
            resp = str(resp)
            print(resp)
            if '01' in resp:
                play('tools/' + MP3[0])
            if '02' in resp:
                play('tools/' + MP3[1])
            if '04' in resp:
                play('tools/' + MP3[2])
            if '08' in resp:
                play('tools/' + MP3[3])
            if '10' in resp:
                play('tools/' + MP3[4])
            if '20' in resp:
                play('tools/' + MP3[5])
            continue
        time.sleep(0.01)
    conn.disconnect()


if __name__ == '__main__':
    Test()