Python ESP32 蓝牙通信:使用固定类实现简单通信
以下是一个使用 Python 编写的 ESP32 带蓝牙功能的固定类的示例:\n\npython\nimport bluetooth\nimport time\n\nclass ESP32Bluetooth:\n def __init__(self):\n self.server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n self.client_sock = None\n self.client_info = None\n\n def advertise_service(self, name, uuid):\n self.server_sock.bind(("", bluetooth.PORT_ANY))\n self.server_sock.listen(1)\n\n bluetooth.advertise_service(self.server_sock, name,\n service_id=uuid,\n service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],\n profiles=[bluetooth.SERIAL_PORT_PROFILE])\n\n def wait_for_connection(self):\n print("Waiting for connection...")\n self.client_sock, self.client_info = self.server_sock.accept()\n print("Connected to", self.client_info)\n\n def receive_data(self):\n data = self.client_sock.recv(1024)\n return data.decode("utf-8")\n\n def send_data(self, data):\n self.client_sock.send(data.encode("utf-8"))\n\n def close_connection(self):\n self.client_sock.close()\n self.server_sock.close()\n\n# 使用示例\nesp32 = ESP32Bluetooth()\nesp32.advertise_service("ESP32", bluetooth.UUID("00001101-0000-1000-8000-00805F9B34FB"))\nesp32.wait_for_connection()\n\nwhile True:\n data = esp32.receive_data()\n print("Received:", data)\n\n if data == "exit":\n break\n\n response = input("Enter response: ")\n esp32.send_data(response)\n\nesp32.close_connection()\n\n\n在上述示例中,我们首先创建了一个ESP32Bluetooth类,该类封装了与 ESP32 蓝牙通信相关的方法。在__init__方法中,我们初始化了一个服务器套接字和客户端套接字。advertise_service方法用于在蓝牙上广播服务。wait_for_connection方法等待客户端的连接请求并接受连接。receive_data方法用于接收从 ESP32 发送过来的数据,send_data方法用于向 ESP32 发送数据。close_connection方法用于关闭连接。\n\n在使用示例中,我们创建了一个ESP32Bluetooth实例,并通过advertise_service方法广播了一个名为"ESP32"的服务。然后使用wait_for_connection方法等待客户端的连接。在一个循环中,我们不断接收从 ESP32 发送过来的数据,并打印出来。如果接收到的数据是"exit",则退出循环。否则,我们输入一个响应并通过send_data方法将响应发送给 ESP32。最后,我们通过close_connection方法关闭连接。\n\n请注意,这只是一个简单的示例,实际使用时可能需要根据具体需求进行修改和完善。
原文地址: https://www.cveoy.top/t/topic/pQdC 著作权归作者所有。请勿转载和采集!