main.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from kivy.app import App
  2. from kivy.uix.widget import Widget
  3. from kivy.uix.button import Button
  4. from kivy.uix.gridlayout import GridLayout
  5. from kivy.uix.label import Label
  6. from kivy.uix.textinput import TextInput
  7. from kivy.clock import Clock
  8. import asyncio
  9. from bleak import BleakClient,BleakScanner
  10. import json
  11. STM32_UUID = "00001101-0000-1000-8000-00805F9B34FB"
  12. class MainWidget(Widget):
  13. def __init__(self, **kwargs):
  14. super().__init__(**kwargs)
  15. self.size = (1600,800)
  16. self.last_flag = False
  17. self.flag = False
  18. self.scanning = Label(text="Scanning...",font_size=100,top=self.top,center_x = self.center_x)
  19. def update(self, dt):
  20. if self.flag and (not self.last_flag):
  21. self.connect()
  22. self.last_flag = self.flag
  23. def start(self):
  24. self.add_widget(self.scanning)
  25. # def start_scan(self, dt):
  26. # asyncio.run(self.scan)
  27. async def scan(self):
  28. self.devices = await BleakScanner.discover()
  29. self.flag = True
  30. def connect(self):
  31. self.remove_widget(self.scanning)
  32. self.grid00 = GridLayout(cols=1,rows=2,width=self.width,height=self.height / 4,top=self.top)
  33. self.add_widget(self.grid00)
  34. grid01 = GridLayout(cols=2,rows=1,width=self.grid00.width,height=self.grid00.height / 2)
  35. self.grid00.add_widget(grid01)
  36. grid01.add_widget(Label(text="Device Name:",width=self.grid00.width / 2,height=self.grid00.height / 2,font_size=50))
  37. deviceName = "HC-06"
  38. grid01.add_widget(TextInput(text=deviceName,width=self.grid00.width / 2,height=self.grid00.height / 2,font_size=40))
  39. connect_button = Button(text="Connect",width=self.grid00.width,height=self.grid00.height / 2,center_x=self.grid00.center_x,font_size=40)
  40. self.grid00.add_widget(connect_button)
  41. if connect_button.state == "down":
  42. self.clear_widgets(self.grid00)
  43. class STI2021A(App):
  44. def __init__(self):
  45. super().__init__()
  46. self.main_widget = MainWidget()
  47. def build(self):
  48. self.main_widget.start()
  49. Clock.schedule_interval(self.main_widget.update, 1)
  50. return self.main_widget
  51. async def scan(self):
  52. await self.main_widget.scan()
  53. async def main(app):
  54. await asyncio.gather(app.async_run("asyncio"), app.scan())
  55. if __name__ == "__main__":
  56. app = STI2021A()
  57. asyncio.run(main(app))