-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
592 lines (537 loc) · 29.3 KB
/
main.py
File metadata and controls
592 lines (537 loc) · 29.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
import os
# import struct
# import jnius
import logging
import threading
import random
from jnius import autoclass, cast, java_method
from threading import Thread
from kivy.utils import platform
from kivy.clock import Clock, mainthread
from kivy.metrics import dp
from kivy.config import Config
from kivy.lang import Builder
from kivymd.theming import ThemeManager
from kivy.storage.jsonstore import JsonStore
from kivymd.uix.button import MDFlatButton
from kivymd.uix.dialog import MDDialog
from screens import *
import atexit
import time
from bluetooth_helpers import FakeDevice, CustomBluetoothDevice
from device_connection_dialog import DeviceConnectionDialog, DialogContent
logging.basicConfig(level=logging.DEBUG)
# Developer Mode:
# Config.set('kivy', 'log_level', 'debug')
# Needed for Python code to communicate with Android operating system, sensors, etc.
if platform == 'android':
from android import mActivity
from android.permissions import Permission, request_permissions, check_permission
from android.broadcast import BroadcastReceiver
BluetoothManager = autoclass('android.bluetooth.BluetoothManager')
BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter')
BluetoothDevice = autoclass('android.bluetooth.BluetoothDevice')
BluetoothSocket = autoclass('android.bluetooth.BluetoothSocket')
# Probably only need PythonActivity?
Activity = autoclass('android.app.Activity')
PythonActivity = autoclass('org.kivy.android.PythonActivity')
Intent = autoclass('android.content.Intent')
Context = autoclass('android.content.Context')
IntentFilter = autoclass('android.content.IntentFilter')
Manifest = autoclass('android.Manifest')
PackageManager = autoclass('android.content.pm.PackageManager')
UUID = autoclass('java.util.UUID')
Settings = autoclass('android.provider.Settings')
if platform == 'linux':
from kivy.core.window import Window
Window.size = (dp(450), dp(800))
class MainApp(MDApp):
theme_cls = ThemeManager()
available_devices = ListProperty()
paired_devices = ListProperty()
loaded_devices = ListProperty()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.bluetooth_manager = None
self.bluetooth_adapter = None
self.permissions = [Permission.BLUETOOTH,
Permission.BLUETOOTH_ADMIN,
Permission.BLUETOOTH_CONNECT,
Permission.BLUETOOTH_SCAN] if platform == 'android' else []
self.broadcast_receiver = self._get_broadcast_receiver() if platform == 'android' else None
self.saved_data = None
self.theme_cls.theme_style = 'Dark'
self.theme_cls.primary_palette = 'BlueGray'
self.theme_cls.primary_hue = '400'
# 'M3' breaks MDSwitch. widget_style=ios looks good but also acts funky
# self.theme_cls.material_style = 'M3'
# In the Kivy language files, use import statements to load the Python classes that
# correspond to any widget instantiated or defined by a Kivy rule.
Builder.load_file('device_controller.kv')
Builder.load_file('device_connection_dialog.kv')
Builder.load_file('device_info_list_item.kv')
Builder.load_file('palettes_screen.kv')
Builder.load_file('configure_leds_screen.kv')
Builder.load_file('device_info_screen.kv')
Builder.load_file('find_devices_screen.kv')
Builder.load_file('animations_list.kv')
Builder.load_file('drawers.kv')
Builder.load_file('favorites_bar.kv')
Builder.load_file('ctrl_widgets.kv')
def build(self):
"""Kivy built-in method that must return the root widget of the App's widget tree."""
start_time = time.time()
Clock.schedule_once(self.request_bluetooth_permissions)
Clock.schedule_once(self.load_saved_data)
self.root_screen = RootScreen()
end_time = time.time()
startup_time = end_time - start_time
logging.debug(f'`{self.__class__.__name__}.{func_name()}`\n'
f'\tAPP STARTUP TIME: {startup_time:.4f}')
return self.root_screen
def on_start(self, *args):
"""Kivy built-in method that is called when the application is starting. Perform any
additional initialization here."""
logging.debug(f'`{self.__class__.__name__}.{func_name()}` was called with {args}')
def on_resume(self, *args):
"""Kivy built-in method that is called when the application is resumed after being paused or
stopped. You can register listeners or start services here."""
logging.debug(f'`{self.__class__.__name__}.{func_name()}` was called with {args}')
def on_pause(self, *args):
"""Kivy built-in method that is called when the application is paused (e.g., when the home
button is pressed).You can save application state or perform any necessary cleanup here."""
logging.debug(f'`{self.__class__.__name__}.{func_name()}` was called with {args}')
# if platform == 'android':
# close_thread = threading.Thread(target=self.close_sockets)
# close_thread.start()
return True
def on_stop(self, *args):
"""Kivy built-in method that is called when the application is stopped (e.g., when the app
# is closed) but it doesn't appear to ever get called."""
logging.debug(f'`{self.__class__.__name__}.{func_name()}` was called with {args}')
if platform == 'android':
close_thread = threading.Thread(target=self.close_sockets)
close_thread.start()
def _get_broadcast_receiver(self):
"""Called from MDApp.__init__ if we're on Android.
App needs to receive Android system broadcasts about changes to the BluetoothAdapter or
a BluetoothDevice's connection state. This registers a callback to be called when certain
system broadcasts are sent by the Android system."""
logging.debug(f'`{self.__class__.__name__}.{func_name()}`')
actions = [BluetoothDevice.ACTION_ACL_CONNECTED,
BluetoothDevice.ACTION_ACL_DISCONNECTED,
BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED,
BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED,
BluetoothAdapter.ACTION_STATE_CHANGED,
]
# Not sure where instantiating a BroadcastReceiver with these arguments is documented...
# thanks ChatGPT :)
br = BroadcastReceiver(self.on_broadcast_received, actions)
br.start()
return br
def on_broadcast_received(self, context, intent):
"""A broadcast we subscribed to has been received by the BroadcastReceiver. The 'broadcast'
is an Intent object.
If Bluetooth (BluetoothAdapter) has been turned on, get previously paired devices. If it's
been turned off, close any open BluetoothSockets that we're responsible for.
If a BluetoothDevice (the ESP32) has been connected, add a DeviceController to the
ControllersScreen. If it's been disconnected, close the BluetoothSocket.
"""
logging.debug(f'`{self.__class__.__name__}.{func_name()}` called with context, intent: '
f'{context, intent}')
try:
logging.debug(f'\tGetting action...')
action = intent.getAction()
except Exception as e:
logging.debug(f'\tException occurred trying to read device or action from intent: {e}')
else:
logging.debug(f'\tSuccessfully got action: {action}')
try:
if action == BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED:
state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, -1)
if state == BluetoothAdapter.STATE_CONNECTED:
logging.debug(f'\tBluetoothAdapter connected state')
elif state == BluetoothAdapter.STATE_DISCONNECTED:
logging.debug(f'\tBluetoothAdapter disconnected state')
self.close_sockets()
elif action == BluetoothAdapter.ACTION_STATE_CHANGED:
state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.STATE_OFF)
if state == BluetoothAdapter.STATE_ON:
logging.debug(f'\tBluetooth enabled broadcast received, getting paired devices...')
self.get_paired_devices()
elif state == BluetoothAdapter.STATE_OFF:
logging.debug(f'\tBluetooth disabled broadcast received...')
except Exception as e:
logging.debug(f'\tException occurred reading a BluetoothAdapter broadcast: {e}')
else:
logging.debug(f'\tSuccessfully read a BluetoothAdapter broadcast.')
try:
if action == BluetoothDevice.ACTION_ACL_DISCONNECTED:
device = cast(BluetoothDevice, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE))
logging.debug(f'\t{device.getName(), device.getAddress()} disconnected')
# If this device is saved / connected, need to get the CustomBluetoothDevice
# instance to get the BluetoothSocket and close it. Here `device` is an
# Android BluetoothDevice - it does not hold a reference to the BluetoothSocket.
self.close_socket(device.getAddress())
controllers_screen = self.root_screen.screen_manager.get_screen('controllers')
controllers_screen.update_controller_connection_status(device.getAddress(), False)
elif action == BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED:
device = cast(BluetoothDevice, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE))
logging.debug(f'\t{device.getName(), device.getAddress()} disconnect requested')
elif action == BluetoothDevice.ACTION_ACL_CONNECTED:
device = cast(BluetoothDevice, intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE))
logging.debug(f'\t{device.getName(), device.getAddress()} connected')
controllers_screen = self.root_screen.screen_manager.get_screen('controllers')
controllers_screen.update_controller_connection_status(device.getAddress(), True)
except Exception as e:
logging.debug(f'\tException occurred reading a BluetoothDevice broadcast: {e}')
else:
logging.debug(f'\tSuccessfully read a BluetoothDevice broadcast.')
def request_bluetooth_permissions(self, *args):
"""Entry point to requesting Bluetooth permissions when App is started for the first time,
or forming Bluetooth connection to previously connected ESP32's."""
logging.debug(f'`{self.__class__.__name__}.{func_name()}` was called with {args}')
if platform == 'android':
logging.debug(f'Requesting Bluetooth Permissions')
try:
logging.debug(f'Attempting checking permissions as objects...')
if not all(check_permission(permission) for permission in self.permissions):
bluetooth_dialog = MDDialog(
title='Allow Bluetooth access?',
text='This app is meant to connect to an ESP32 or other microcontroller via'
'Bluetooth. Without Bluetooth permissions it will not function.',
buttons=[MDFlatButton(text='OK',
on_release=lambda x:
(request_permissions(self.permissions,
self.request_bluetooth_permissions_callback),
bluetooth_dialog.dismiss())
)
]
)
bluetooth_dialog.open()
else:
self.get_bluetooth_adapter()
except Exception as e:
logging.debug(f'Exception occured: {e}')
else:
logging.debug(f'No exception occurred while checking permissions.'
f'Did pop-up launch?')
def close_sockets(self, *args):
logging.warning(f'`{self.__class__.__name__}.{func_name()}` was called with {args}')
for device in self.loaded_devices:
if device.bluetooth_socket:
device.bluetooth_socket.close()
def close_socket(self, address):
logging.debug(f'`{self.__class__.__name__}.{func_name()}` was called with address {address}')
for device in self.loaded_devices:
if device.getAddress() == address and device.bluetooth_socket:
logging.debug(f'Found saved device with matching address,'
f'closing BluetoothSocket...')
device.bluetooth_socket.close()
break
@mainthread
def request_bluetooth_permissions_callback(self, *args):
logging.debug(f'`{self.__class__.__name__}.{func_name()}` was called with {args}')
# Needs @mainthread because this callback is executed outside of the main thread,
# but creates a pop-up window (GUI instructions must be within the main thread).
if not all(check_permission(permission) for permission in self.permissions):
bluetooth_dialog = MDDialog(
title='App is unstable',
text='Without Bluetooth permissions this app will likely crash. To enable later, '
'give this app "Nearby devices" permission in your app settings.',
buttons=[MDFlatButton(text='Dismiss',
on_release=lambda x: bluetooth_dialog.dismiss()
),
MDFlatButton(text='Allow Bluetooth',
on_release=lambda x:
(request_permissions(self.permissions,
self.request_bluetooth_permissions_callback),
bluetooth_dialog.dismiss())
)
]
)
bluetooth_dialog.open()
else:
self.get_bluetooth_adapter()
def get_bluetooth_adapter(self, *args):
logging.debug(f'`{self.__class__.__name__}.{func_name()}` was called with {args}')
context = cast('android.content.Context', mActivity)
self.bluetooth_manager = context.getSystemService(context.BLUETOOTH_SERVICE)
self.bluetooth_adapter = self.bluetooth_manager.getAdapter()
if self.bluetooth_adapter:
logging.debug(f'Successfully got BluetoothAdapter')
else:
logging.debug(f'BluetoothAdapter not found.')
def get_paired_devices(self, *args):
"""Called when we receive an Android system broadcast indicating BluetoothAdapter is on.
We registered for that broadcast before getting the BluetoothAdapter and/or turning it on
with enable_bluetooth so this should get called on every App start up. Also called with
FindDevicesScreen's 'refresh' button.
Updating App.paired_devices will trigger FindDevicesScreen.on_paired_devices (tied together
on .kv side)."""
logging.debug(f'`{self.__class__.__name__}.{func_name()}` was called with {args}')
if platform == 'android':
if self.bluetooth_adapter is None:
no_bluetooth_dialog = MDDialog(
title='Sorry!',
text='This device does not appear to have Bluetooth capabilities.'
)
no_bluetooth_dialog.open()
elif not self.bluetooth_adapter.isEnabled():
logging.debug(f'Bluetooth is disabled...')
self.enable_bluetooth()
else:
logging.debug(f'Bluetooth is enabled...')
try:
paired_devices = self.bluetooth_adapter.getBondedDevices().toArray()
saved_device_addresses = {device.getAddress() for device in self.loaded_devices}
# The paired_devices list is for making new connections so don't show saved_devices.
self.paired_devices = [CustomBluetoothDevice(bluetooth_device=device)
for device in paired_devices
if not device.getAddress() in saved_device_addresses]
except Exception as e:
logging.debug(f'Exception occured: {e}')
else:
logging.debug(f'Paired Devices: {self.paired_devices}')
if platform == 'linux':
new_devices = [FakeDevice() for _ in range(10)]
self.paired_devices[:] = new_devices
def enable_bluetooth(self, *args):
logging.debug(f'`{self.__class__.__name__}.{func_name()}` was called with {args}')
enable_bluetooth = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
try:
logging.debug(f'Enabling Bluetooth with PythonActivity.mActivity.startActivity')
activity = PythonActivity.mActivity
activity.startActivity(enable_bluetooth)
except Exception as e:
logging.debug(f'Enabling Bluetooth with PythonActivity.mActivity.startActivity failed. '
f'Exception: {e}')
else:
logging.debug(f'Successfully enabled Bluetooth with '
f'PythonActivity.mActivity.startActivity')
def open_bluetooth_settings(self, *args):
logging.debug(f'`{self.__class__.__name__}.{func_name()}` was called with {args}')
# Called from FindDevicesScreen PairedDevicesHeader's info button
# Both of these work:
# try:
# logging.debug(f'Open Bluetooth Settings attempt number one')
# intent = Intent(Intent.ACTION_MAIN)
# intent.setClassName('com.android.settings', 'com.android.settings.Settings$BluetoothSettingsActivity')
# activity = PythonActivity.mActivity
# activity.startActivity(intent)
# except Exception as e:
# logging.debug(f'Exception on attempt number one. Exception: {e}')
# else:
# logging.debug(f'Success on attempt number one')
try:
logging.debug(f'Open Bluetooth Settings attempt number two')
open_bluetooth_settings = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
activity = PythonActivity.mActivity
activity.startActivity(open_bluetooth_settings)
except Exception as e:
logging.debug(f'Exception on attempt number two. Exception: {e}')
else:
logging.debug(f'Success on attempt number two')
def connect_as_client(self, device, button):
"""Called by clicking a paired Bluetooth device in FindDevicesScreen, or 'Retry?' button
in DeviceConnectionDialog."""
logging.debug(
f'`{self.__class__.__name__}.{func_name()} called with args: {device, button}`')
if platform == 'android':
self._connect_as_client_android(device, button)
if platform == 'linux':
self._connect_as_client_linux(device, button)
def _connect_as_client_android(self, device, button=None):
logging.debug(
f'`{self.__class__.__name__}.{func_name()} called with args: {device, button}`')
dcd = DeviceConnectionDialog(
type='custom',
content_cls=DialogContent(),
)
dcd.content_cls.label.text = 'Connecting to... ' + device.name
dcd.content_cls.dialog = dcd # back-reference to parent
dcd.open()
# Must use separate thread for connecting to Bluetooth device to keep GUI functional.
t = Thread(target=self._connect_BluetoothSocket, args=[device, dcd])
t.start()
def _connect_BluetoothSocket(self, device, dcd):
"""
Create and open the android.bluetooth.BluetoothSocket connection to the ESP32.
BluetoothSocket.connect() is a blocking call that stops the main Kivy thread from executing
and pauses the GUI; execute this function in a separate thread to avoid this problem.
Conversely, Kivy GUI (graphics) instructions cannot be changed from outside main Kivy
thread. Use kivy.clock @mainthread decorator on the MDDialog methods that are initiated here
to keep graphics instructions in the main thread.
UUID for
Bluetooth Classic Serial Port Profile (SPP) 00001101-0000-1000-8000-00805F9B34FB
Generic Attribute Profile (GATT) 00001801-0000-1000-8000-00805F9B34FB
Generic Access Profile (GAP) 00001800-0000-1000-8000-00805F9B34FB
...
"""
logging.debug(f'`{self.__class__.__name__}.{func_name()} called with args: {device}`')
try:
logging.debug(f'Creating BluetoothSocket')
esp32_UUID = '00001101-0000-1000-8000-00805F9B34FB'
device.bluetooth_socket = device.createRfcommSocketToServiceRecord(
UUID.fromString(esp32_UUID))
device.bluetooth_socket.connect()
device.recv_stream = device.bluetooth_socket.getInputStream()
device.send_stream = device.bluetooth_socket.getOutputStream()
except Exception as e:
logging.debug(f'Failed to open socket in MainApp._connect_BluetoothSocket.'
f'Exception {e}')
# NOTE: @mainthread needed on DeviceConnectionDialog methods to avoid error.
dcd.content_cls.update_failure(device)
else:
logging.debug(f'Successfully opened socket')
# NOTE: @mainthread needed on DeviceConnectionDialog methods to avoid error.
dcd.content_cls.update_success(device)
self._add_new_connected_device(device)
@mainthread
def _add_new_connected_device(self, device):
# Needs @mainthread because calling function is outside of main thread.
self.save_device(device)
self.root_screen.screen_manager.current = 'controllers'
def _connect_as_client_linux(self, device, button):
logging.debug(
f'`{self.__class__.__name__}.{func_name()} called with args: {device, button}`')
dcd = DeviceConnectionDialog(
type='custom',
content_cls=DialogContent(),
)
dcd.content_cls.label.text = 'Connecting to...' + device.name
dcd.content_cls.dialog = dcd # back-reference to parent
dcd.open()
# TODO: Check existing connection (really for android)
if random.choice([0, 1]):
dcd.content_cls.update_success(device)
self.save_device(device)
else:
dcd.content_cls.update_failure(device)
def _reconnect_as_client_linux(self):
logging.debug(f'`{self.__class__.__name__}.{func_name()}`')
for device in self.loaded_devices:
if random.choice([0, 1, 2, 3, 4]):
# Green status
device.connected_status()
else:
# Red Status
device.disconnected_status()
def load_saved_data(self, *args):
logging.debug(f'`{self.__class__.__name__}.{func_name()} called with args: {args}`')
if platform == 'android':
internal_storage_dir = self.user_data_dir
filename = internal_storage_dir + '/saved_data.json'
logging.debug(f'\tLoading saved data on Android...')
logging.debug(f'\tCurrent working directory: {internal_storage_dir},'
f'\tFilename: {filename}')
self.saved_data = JsonStore(filename)
loaded_devices = []
for mac_address in self.saved_data.keys():
logging.debug(f'\tKey: {mac_address}\n'
f'\tValue: {self.saved_data[mac_address]}')
if self.bluetooth_adapter and \
self.bluetooth_adapter.checkBluetoothAddress(str(mac_address)):
bluetooth_device = self.bluetooth_adapter.getRemoteDevice(str(mac_address))
# TODO: doesn't this need other attributes?
custom_bluetooth_device = CustomBluetoothDevice(
bluetooth_device=bluetooth_device,
name=self.saved_data[mac_address]['Name'],
address=self.saved_data[mac_address]['Address'],
nickname=self.saved_data[mac_address]['Nickname'],
favorites=self.saved_data[mac_address]['Favorites'] # check dis
)
logging.debug(f'CustomBluetoothDevice.bluetooth_device: {bluetooth_device}')
loaded_devices.append(custom_bluetooth_device)
# Just change the property once.
self.loaded_devices[:] = loaded_devices
logging.debug(f'\tDone loading saved data on Android with BluetoothAdapter: '
f'{self.bluetooth_adapter}')
logging.debug(f'\tLoaded Devices: {self.loaded_devices}')
if platform == 'linux':
internal_storage_dir = self.user_data_dir
filename = os.path.join(internal_storage_dir, 'saved_data.json')
logging.debug(f'Loading saved data on Linux.')
logging.debug(f'\tCurrent working directory: {internal_storage_dir},'
f'\tFilename: {filename}')
# Create a JsonStore instance with the specified filepath
self.saved_data = JsonStore(filename)
loaded_devices = []
for key in self.saved_data.keys():
logging.debug(f'Key: {key}\n'
f'Value: {self.saved_data[key]}')
device_info = self.saved_data[key]
saved_fake_device = FakeDevice(device_info)
loaded_devices.append(saved_fake_device)
# Just change the property once.
self.loaded_devices[:] = loaded_devices
def clear_saved_data(self, *args):
logging.debug(f'`{self.__class__.__name__}.{func_name()} called with args: {args}`')
self.saved_data.clear()
self.load_saved_data()
def save_device(self, device):
logging.debug(f'`{self.__class__.__name__}.{func_name()}` called with device {device}')
# Save to database.
device_info = device.get_device_info()
# make UUIDs strings to save them
uuids = [uuid.toString() for uuid in device_info['UUIDs']]
device_info['UUIDs'] = uuids
mac_address = device_info['Address']
self.saved_data[mac_address] = device_info
# If device was renamed, overwrite it. This does not trigger on_loaded_devices calls.
for i, saved_device in enumerate(self.loaded_devices):
logging.debug(f'\t`Saved device: {device} was renamed.')
if saved_device.getAddress() == device.getAddress():
self.loaded_devices[i] = device
return
# Update paired and saved device lists.
self.loaded_devices.append(device)
paired_addresses = {device.getAddress() for device in self.paired_devices}
for i, device in enumerate(self.paired_devices):
if device.getAddress() in paired_addresses:
del self.paired_devices[i]
break
def save_device_favorite(self, device, fav_idx, commands_dict):
logging.debug(f'`{self.__class__.__name__}.{func_name()}')
device_info = device.get_device_info()
favorites = device_info['Favorites']
print(favorites.items())
for mode, command in commands_dict.items():
print(mode, command)
favorites[fav_idx][mode] = command.as_dict()
print(favorites.items())
self.save_device(device)
def forget_device(self, device):
logging.debug(f'`{self.__class__.__name__}.{func_name()} called with: {device}`')
# Delete from database, close BluetoothSocket, move back to paired_devices.
device_info = device.get_device_info()
mac_address = device_info['Address']
try:
self.saved_data.delete(mac_address)
except KeyError as e:
logging.debug(f'No device with address {mac_address} found in saved data.')
except Exception as e:
logging.debug(f'Exception occured while trying to delete '
f'{mac_address} from saved data.')
for i, device in enumerate(self.loaded_devices):
if device_info['Address'] == mac_address:
if platform == 'android':
self.paired_devices.append(self.loaded_devices[i])
self.close_socket(mac_address)
del self.loaded_devices[i]
break
def show_saved_data(self, *args):
logging.debug(f'`{self.__class__.__name__}.{func_name()} called with args: {args}`')
for key in self.saved_data.keys():
logging.debug(f'\tKey: {key}'
f'\tDevice: {self.saved_data[key]}')
if __name__ == '__main__':
app = MainApp()
# Kivy's on_stop method does not get called. Need to shut down the app gracefully.
if platform == 'android':
atexit.register(app.close_sockets)
# close_thread = threading.Thread(target=app.close_sockets)
# close_thread.start()
app.run()
logging.debug(f'MainApp.run() has ended. Shutting down...')