Quantcast
Viewing all articles
Browse latest Browse all 1241

Python • Re: Kivy, Bleak and async troubles [SOLVED]

Thank you memjr.
You have made me browse through the issues (again), which inspired me to other approaches and searches.

Seems that the coroutines just need some time to breath, so the solution was not obvious to me, but no more than actually just inserting some "await asyncio.sleep()" statements. So it took me 9 days and a litres of coffee to find out that the solution is doing nothing for a while Image may be NSFW.
Clik here to view.
:lol:
.

If it can be helpful to someone, here is the working code, I also added some error catching today:

Code:

import asyncioimport bleakfrom kivy.app import Appfrom time import sleepfrom kivy.uix.label import Labelfrom kivy.uix.boxlayout import BoxLayoutfrom kivy.uix.button import Buttonfrom kivy.logger import Loggerimport logginglogging.Logger.manager.root = LoggerUART_SERVICE_UUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"UART_RX_CHAR_UUID = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"UART_TX_CHAR_UUID = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"remote_device = '28:CD:C1:04:FA:7B'data = b'toggle\r\n'class RemoteControlApp(App):    def __init__(self):        super().__init__()        self.label = None        self.running = True        self.flag = False        self.device = bleak.BleakClient(remote_device, use_cached_services=False)    def send_command(self, button):        print("Button pushed")        self.flag = True          def on_stop(self):        self.running = False        def build(self):        self.boxlayout = BoxLayout(orientation= 'vertical', padding="20px")        self.button = Button(text = 'Send Message', font_size="36dp")        self.button.bind(on_press = self.send_command)        self.boxlayout.add_widget(self.button)        self.label = Label(font_size="36dp", text="Wait for device to connect...")        self.boxlayout.add_widget(self.label)        return self.boxlayout    async def connect_and_send(self):        while True:            try:                self.device = bleak.BleakClient(remote_device, use_cached_services=False)                self.label.text = "Connecting to device..."                client = self.device                await client.connect()            except bleak.exc.BleakDeviceNotFoundError:                self.label.text = "Can't connect to device\nRetrying..."                self.flag = False                await asyncio.sleep(3)                            while True:                if not self.device.is_connected:                    self.label.text = "Connection lost...\nTrying to reconnect..."                    await asyncio.sleep(2)                    break                if not self.running:                    break                if self.flag == True:                                         try:                        client = self.device                        print("Connected...", client)                        self.label.text = "Message sent!"                                                             nus = client.services.get_service(UART_SERVICE_UUID)                        rx_char = nus.get_characteristic(UART_RX_CHAR_UUID)                        await client.write_gatt_char(rx_char, data, response=False)                        print("sent:", data)                                           self.flag = False                        await asyncio.sleep(1.5)                    except bleak.exc.BleakError:                        self.label.text = "Error sending message\nRESTART PROGRAM."                        self.flag = False                        break                    except OSError:                        print("Something went wrong")                        self.label.text = "Something went wrong\nRESTART PROGRAM."                        self.flag = False                        break                else:                    self.label.text="Remote device connected"                    await asyncio.sleep(.2)                  async def main(app):    await asyncio.gather(app.async_run("asyncio"), app.connect_and_send())if __name__ == "__main__":    Logger.setLevel(logging.DEBUG)    # app running on one thread with two async coroutines    app = RemoteControlApp()    asyncio.run(main(app))

Statistics: Posted by kheylen25 — Sun Jan 07, 2024 6:23 pm



Viewing all articles
Browse latest Browse all 1241

Trending Articles