Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
630 lines (542 loc) · 29.2 KB
/
Copy pathmain.py
File metadata and controls
630 lines (542 loc) · 29.2 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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
# WeatherFlow PiConsole: Raspberry Pi Python console for WeatherFlow Tempest
# and Smart Home Weather stations.
# Copyright (C) 2018-2025 Peter Davis
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
# ==============================================================================
# DEFINE GOBAL VARIABLES
# ==============================================================================
SHUTDOWN = 0
REBOOT = 0
# ==============================================================================
# SET KIVY_LOG_MODE TO MIXED
# ==============================================================================
# Import required modules
import os
# Set KIVY_LOG_MODE environment variable
os.environ['KIVY_LOG_MODE'] = 'MIXED'
# ==============================================================================
# CREATE OR UPDATE wfpiconsole.ini FILE
# ==============================================================================
# Import required modules
from lib import config as config_file
from pathlib import Path
# Create or update config file if required
if not Path('wfpiconsole.ini').is_file():
config_file.create()
else:
config_file.update()
# ==============================================================================
# INITIALISE KIVY GRAPHICS WINDOW BASED ON CURRENT HARDWARE TYPE
# ==============================================================================
# Import required modules
import configparser
# Load wfpiconsole.ini config file
config = configparser.ConfigParser()
config.read('wfpiconsole.ini')
# Initialise Kivy backend based on current hardware
if config['System']['Hardware'] != 'Other':
os.environ['SDL_VIDEO_ALLOW_SCREENSAVER'] = '1'
os.environ['KIVY_GRAPHICS'] = 'gles'
os.environ['KIVY_WINDOW'] = 'sdl2'
# ==============================================================================
# INITIALISE KIVY WINDOW PROPERTIES BASED ON OPTIONS SET IN wfpiconsole.ini
# ==============================================================================
# Import required modules
from kivy.config import Config as kivyconfig # type: ignore
# Generate default wfpiconsole Kivy config file. Config file is always
# regenerated to ensure changes to the default file are always copied across
defaultconfig = configparser.ConfigParser()
defaultconfig.read(os.path.expanduser('~/.kivy/') + 'config.ini')
with open(os.path.expanduser('~/.kivy/') + 'config_wfpiconsole.ini', 'w') as cfg:
defaultconfig.write(cfg)
# Load wfpiconsole Kivy configuration file
kivyconfig.read(os.path.expanduser('~/.kivy/') + 'config_wfpiconsole.ini')
# Set Kivy window properties
if int(config['Display']['Fullscreen']):
kivyconfig.set('graphics', 'fullscreen', 'auto')
else:
kivyconfig.set('graphics', 'fullscreen', '0')
kivyconfig.set('graphics', 'width', config['Display']['Width'])
kivyconfig.set('graphics', 'height', config['Display']['Height'])
if int(config['Display']['Border']):
kivyconfig.set('graphics', 'borderless', '0')
else:
kivyconfig.set('graphics', 'borderless', '1')
# ==============================================================================
# INITIALISE MOUSE SUPPORT IF OPTION SET in wfpiconsole.ini
# ==============================================================================
# Initialise mouse support if required
if int(config['Display']['Cursor']):
kivyconfig.set('graphics', 'show_cursor', '1')
if 'Pi' in config['System']['Hardware']:
kivyconfig.set('input', 'mouse', 'mouse')
kivyconfig.remove_option('input', 'mtdev_%(name)s')
else:
kivyconfig.set('graphics', 'show_cursor', '0')
if 'Pi' in config['System']['Hardware']:
kivyconfig.remove_option('input', 'mouse')
# Save wfpiconsole Kivy configuration file
kivyconfig.write()
# ==============================================================================
# IMPORT REQUIRED CORE KIVY MODULES
# ==============================================================================
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
from kivy.properties import DictProperty, NumericProperty
from kivy.core.window import Window
from kivy.factory import Factory
from kivy.logger import Logger
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.app import App
# ==============================================================================
# IMPORT REQUIRED LIBRARY MODULES
# ==============================================================================
from lib.system import system
from lib.astronomical import astro
from lib.forecast import forecast
from lib.sager import sager_forecast
from lib.status import station
from lib import settings as userSettings
from lib import properties
from lib import config
# ==============================================================================
# IMPORT REQUIRED PANELS
# ==============================================================================
from panels.temperature import TemperaturePanel, TemperatureButton # type: ignore
from panels.barometer import BarometerPanel, BarometerButton # type: ignore
from panels.lightning import LightningPanel, LightningButton # type: ignore
from panels.wind import WindSpeedPanel, WindSpeedButton # type: ignore
from panels.forecast import ForecastPanel, ForecastButton # type: ignore
from panels.forecast import SagerPanel, SagerButton # type: ignore
from panels.rainfall import RainfallPanel, RainfallButton # type: ignore
from panels.astro import SunriseSunsetPanel, SunriseSunsetButton # type: ignore
from panels.astro import MoonPhasePanel, MoonPhaseButton # type: ignore
from panels.menu import mainMenu
# ==============================================================================
# IMPORT CUSTOM USER PANELS
# ==============================================================================
if Path('user/customPanels.py').is_file():
from user.customPanels import * # type: ignore
# ==============================================================================
# IMPORT REQUIRED SYSTEM MODULES
# ==============================================================================
from runpy import run_path
import subprocess
import threading
# ==============================================================================
# IMPORT REQUIRED KIVY GRAPHICAL AND SETTINGS MODULES
# ==============================================================================
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition
from kivy.uix.settings import SettingsWithSidebar, SettingBoolean
from kivy.uix.switch import Switch
# ==============================================================================
# DEFINE 'WeatherFlowPiConsole' APP CLASS
# ==============================================================================
class wfpiconsole(App):
# Define App class dictionary properties
Sched = DictProperty([])
# Define display properties
scaleFactor = NumericProperty(1)
scaleSuffix = StringProperty('_lR.png')
# BUILD 'WeatherFlowPiConsole' APP CLASS
# --------------------------------------------------------------------------
def build(self):
# Calculate initial ScaleFactor and bind self.set_scale_factor to Window
# on_resize
self.window = Window
self.set_scale_factor(self.window, self.window.width, self.window.height)
self.window.bind(on_resize=self.set_scale_factor)
# Load Custom Panel KV file if present
if Path('user/customPanels.py').is_file():
Builder.load_file('user/customPanels.kv')
# Initialise ScreenManager
self.screen_manager = screenManager(transition=NoTransition())
self.screen_manager.add_widget(CurrentConditions())
# Start Websocket or UDP service
self.start_connection_service()
# Check for latest version
self.system = system()
Clock.schedule_once(self.system.check_version)
# Set Settings syle class
self.settings_cls = SettingsWithSidebar
# Initialise realtime clock
self.Sched.realtimeClock = Clock.schedule_interval(self.system.realtime_clock, 1.0)
# Return ScreenManager
return self.screen_manager
# DISCONNECT connection_client WHEN CLOSING APP
# --------------------------------------------------------------------------
def on_stop(self):
self.stop_connection_service()
# SET DISPLAY SCALE FACTOR BASED ON SCREEN DIMENSIONS
# --------------------------------------------------------------------------
def set_scale_factor(self, instance, x, y):
self.scaleFactor = min(x / 800, y / 480)
if self.scaleFactor > 1 or int(self.config['Display']['PanelCount']) < 6:
self.scaleSuffix = '_hR.png'
else:
self.scaleSuffix = '_lR.png'
# LOAD APP CONFIGURATION FILE
# --------------------------------------------------------------------------
def build_config(self, config):
config.optionxform = str
config.read('wfpiconsole.ini')
# BUILD 'WeatherFlowPiConsole' APP CLASS SETTINGS
# --------------------------------------------------------------------------
def build_settings(self, settings):
# Register setting types
settings.register_type('ScrollOptions', userSettings.ScrollOptions)
settings.register_type('FixedOptions', userSettings.FixedOptions)
settings.register_type('ToggleTemperature', userSettings.ToggleTemperature)
settings.register_type('ToggleHours', userSettings.ToggleHours)
settings.register_type('ToggleMinutes', userSettings.ToggleMinutes)
# Add required panels to setting screen. Remove Kivy settings panel
settings.add_json_panel('Display', self.config, data=userSettings.JSON('Display'))
settings.add_json_panel('Primary Panels', self.config, data=userSettings.JSON('Primary'))
settings.add_json_panel('Secondary Panels', self.config, data=userSettings.JSON('Secondary'))
settings.add_json_panel('Units', self.config, data=userSettings.JSON('Units'))
settings.add_json_panel('Feels Like', self.config, data=userSettings.JSON('FeelsLike'))
settings.add_json_panel('System', self.config, data=userSettings.JSON('System'))
self.use_kivy_settings = False
self.settings = settings
# OVERLOAD 'display_settings' TO OPEN SETTINGS SCREEN WITH SCREEN MANAGER
# --------------------------------------------------------------------------
def display_settings(self, settings):
self.mainMenu.dismiss(animation=False)
if not self.screen_manager.has_screen('Settings'):
self.settingsScreen = Screen(name='Settings')
self.screen_manager.add_widget(self.settingsScreen)
self.settingsScreen.add_widget(self.settings)
self.screen_manager.current = 'Settings'
return True
# OVERLOAD 'close_settings' TO CLOSE SETTINGS SCREEN WITH SCREEN MANAGER
# --------------------------------------------------------------------------
def close_settings(self, *args):
if self.screen_manager.current == 'Settings':
mainMenu().open(animation=False)
self.screen_manager.current = self.screen_manager.previous()
self.settingsScreen.remove_widget(self.settings)
return True
# OVERLOAD 'on_config_change' TO MAKE NECESSARY CHANGES TO CONFIG VALUES
# WHEN REQUIRED
# --------------------------------------------------------------------------
def on_config_change(self, config, section, key, value):
# Update current weather forecast when temperature or wind speed units
# are changed
if section == 'Units' and key in ['Temp', 'Wind']:
self.forecast.parse_forecast()
self.sager.get_forecast_text()
# Update current weather forecast, sunrise/sunset and moonrise/moonset
# times when time format changed
if section == 'Display' and key == 'TimeFormat':
self.forecast.parse_forecast()
self.astro.format_labels('Sun')
self.astro.format_labels('Moon')
# Show or hide indoor temperature when setting is changed
if section == 'Display' and key == 'IndoorTemp':
if hasattr(self, 'TemperaturePanel'):
for panel in getattr(self, 'TemperaturePanel'):
panel.set_indoor_temp_display()
# Show or hide nc_rain_icon when setting is changed
if section == 'System' and key == 'nc_rain':
if hasattr(self, 'RainfallPanel'):
for panel in getattr(self, 'RainfallPanel'):
panel.set_nc_rain_icon()
# Update "Feels Like" temperature cutoffs in wfpiconsole.ini and the
# settings screen when temperature units are changed
if section == 'Units' and key == 'Temp':
for Field in self.config['FeelsLike']:
if 'c' in value:
Temp = str(round((float(self.config['FeelsLike'][Field]) - 32) * (5 / 9)))
self.config.set('FeelsLike', Field, Temp)
elif 'f' in value:
Temp = str(round(float(self.config['FeelsLike'][Field]) * (9 / 5) + 32))
self.config.set('FeelsLike', Field, Temp)
self.config.write()
panels = self._app_settings.children[0].content.panels
for Field in self.config['FeelsLike']:
for panel in panels.values():
if panel.title == 'Feels Like':
for item in panel.children:
if isinstance(item, Factory.ToggleTemperature):
if item.title.replace(' ', '') == Field:
item.value = self.config['FeelsLike'][Field]
# Update barometer limits when pressure units are changed
if section == 'Units' and key == 'Pressure':
if hasattr(self, 'BarometerPanel'):
for panel in getattr(self, 'BarometerPanel'):
panel.set_barometer_max_min()
# Update number of panels displayed on CurrentConditions screen
if section == 'Display' and key == 'PanelCount':
self.set_scale_factor(self.window, self.window.width, self.window.height)
Clock.schedule_once(self.CurrentConditions.add_panels)
# Update primary and secondary panels displayed on CurrentConditions
# screen
if section in ['PrimaryPanels', 'SecondaryPanels']:
panel_list = ['panel_' + Num for Num in ['one', 'two', 'three', 'four', 'five', 'six']]
for ii, (panel, type) in enumerate(self.config['PrimaryPanels'].items()):
if panel == key:
old_panel = self.CurrentConditions.ids[panel_list[ii]].children[0]
self.CurrentConditions.ids[panel_list[ii]].clear_widgets()
self.CurrentConditions.ids[panel_list[ii]].add_widget(eval(type + 'Panel')())
break
if hasattr(self, old_panel.__class__.__name__):
try:
getattr(self, old_panel.__class__.__name__).remove(old_panel)
except ValueError:
Logger.warning('Unable to remove panel reference from wfpiconsole class')
# Update button layout displayed on CurrentConditions screen
if section == 'SecondaryPanels':
self.CurrentConditions.button_list = []
primary_panel_list = tuple(self.config['PrimaryPanels'].items())
secondary_panel_list = tuple(self.config['SecondaryPanels'].items())
button_list = ['button_' + Num for Num in ['one', 'two', 'three', 'four', 'five', 'six']]
button_number = 0
for button in button_list:
self.CurrentConditions.ids[button].clear_widgets()
if int(self.config['Display']['PanelCount']) == 1:
button_ids = ['button_' + number for number in ['one']]
elif int(self.config['Display']['PanelCount']) == 4:
button_ids = ['button_' + number for number in ['one', 'two', 'three', 'four']]
elif int(self.config['Display']['PanelCount']) == 6:
button_ids = ['button_' + number for number in ['one', 'two', 'three', 'four', 'five', 'six']]
for ii, button_id in enumerate(button_ids):
primary_panel = primary_panel_list[ii][1]
secondary_panel = secondary_panel_list[ii][1]
if secondary_panel and secondary_panel != 'None':
self.CurrentConditions.ids[button_ids[button_number]].add_widget(eval(secondary_panel + 'Button')())
self.CurrentConditions.button_list.append([button_ids[button_number], panel_list[ii], primary_panel, secondary_panel, 'primary'])
button_number += 1
# Change 'None' for secondary panel selection to blank in config
# file
if value == 'None':
self.config.set(section, key, '')
self.config.write()
panels = self._app_settings.children[0].content.panels
for panel in panels.values():
if panel.title == 'Secondary Panels':
for item in panel.children:
if isinstance(item, Factory.SettingOptions):
if item.title.replace(' ', '') == key:
item.value = ''
break
# Update Sager Forecast schedule
if section == 'System' and key == 'SagerInterval':
Clock.schedule_once(self.sager.schedule_forecast)
# Force rest_api services if Websocket connection is selected
if ((section == 'System' and key == 'Connection' and value == 'Websocket')
or (section == 'System' and key == 'rest_api' and self.config['System']['Connection'] == 'Websocket')):
if self.config['System']['rest_api'] == '0':
self.config.set('System', 'rest_api', '1')
self.config.write()
panels = self._app_settings.children[0].content.panels
for panel in panels.values():
if panel.title == 'System':
for item in panel.children:
if isinstance(item, SettingBoolean) and item.title == 'REST API':
for child in item.children[0].children:
for child in child.children:
if isinstance(child, Switch):
child.active = True
# Switch connection type, change between Device/Statistics API endpoint
# and swtich to showing NC rain totals
if section == 'System' and (key == 'Connection' or key == 'stats_endpoint' or key == 'nc_rain'):
self.stop_connection_service()
self.connection_thread.join()
self.start_connection_service()
# Update derived variables to reflect configuration changes
if hasattr(self, 'obsParser'):
self.obsParser.reformat_display()
# START WEBSOCKET OR UDP SERVICE
# --------------------------------------------------------------------------
def start_connection_service(self, *largs):
self.connection_thread = None
if self.config['System']['Connection'] == 'Websocket':
self.connection_thread = threading.Thread(target=run_path,
args=['service/websocket.py'],
kwargs={'run_name': '__main__'},
name='Websocket')
elif self.config['System']['Connection'] == 'UDP':
self.connection_thread = threading.Thread(target=run_path,
args=['service/udp.py'],
kwargs={'run_name': '__main__'},
name='UDP')
if self.connection_thread is not None:
self.connection_thread.start()
# STOP WEBSOCKET SERVICE
# --------------------------------------------------------------------------
def stop_connection_service(self):
if hasattr(self, 'connection_client'):
self.connection_client._keep_running = False
# EXIT CONSOLE AND SHUTDOWN SYSTEM
# --------------------------------------------------------------------------
def shutdown_system(self):
global SHUTDOWN
SHUTDOWN = 1
self.stop()
# EXIT CONSOLE AND REBOOT SYSTEM
# --------------------------------------------------------------------------
def reboot_system(self):
global REBOOT
REBOOT = 1
self.stop()
# ==============================================================================
# screenManager CLASS
# ==============================================================================
class screenManager(ScreenManager):
pass
# ==============================================================================
# CurrentConditions CLASS
# ==============================================================================
class CurrentConditions(Screen):
System = DictProperty()
Status = DictProperty()
Sager = DictProperty()
Astro = DictProperty()
Obs = DictProperty()
Met = DictProperty()
def __init__(self, **kwargs):
super(CurrentConditions, self).__init__(**kwargs)
self.app = App.get_running_app()
self.app.CurrentConditions = self
self.System = properties.System()
self.Status = properties.Status()
self.Sager = properties.Sager()
self.Astro = properties.Astro()
self.Met = properties.Met()
self.Obs = properties.Obs()
# Add display panels
self.add_panels()
# Schedule Station.getDeviceStatus to be called each second
self.app.station = station()
self.app.Sched.deviceStatus = Clock.schedule_interval(self.app.station.get_device_status, 1.0)
# Initialise sunrise, sunset, moonrise, moonset, full moon and new moon
# times
self.app.astro = astro()
self.app.astro.get_sunrise_sunset()
self.app.astro.get_moonrise_moonset()
self.app.astro.get_full_new_moon()
# # Schedule sunTransit and moonPhase functions to be called each second
self.app.Sched.sun_transit = Clock.schedule_interval(self.app.astro.sun_transit, 1.0)
self.app.Sched.moon_phase = Clock.schedule_interval(self.app.astro.moon_phase, 1.0)
# Schedule WeatherFlow weather forecast download
self.app.forecast = forecast()
self.app.Sched.metDownload = Clock.schedule_once(self.app.forecast.fetch_forecast)
# Generate Sager Weathercaster forecast
self.app.sager = sager_forecast()
self.app.Sched.sager = Clock.schedule_once(self.app.sager.fetch_forecast)
# ADD USER SELECTED PANELS TO CURRENT CONDITIONS SCREEN
# --------------------------------------------------------------------------
def add_panels(self, *args):
# Clear existing panels
if 'row_layout' in self.ids:
button_list = ['button_' + Num for Num in ['one', 'two', 'three', 'four', 'five', 'six']]
for button in button_list:
self.ids[button].clear_widgets()
self.ids['row_layout'].clear_widgets()
# Define required variables
panel_count = 0
button_count = 0
self.button_list = []
primary_panels = tuple(self.app.config['PrimaryPanels'].items())
secondary_panels = tuple(self.app.config['SecondaryPanels'].items())
if self.app.config['Display']['PanelCount'] == '1':
panel_ids = [['panel_' + number for number in ['one']]]
button_ids = ['button_' + number for number in ['one']]
elif self.app.config['Display']['PanelCount'] == '4':
panel_ids = [['panel_' + number for number in ['one', 'two']],
['panel_' + number for number in ['three', 'four']]]
button_ids = ['button_' + number for number in ['one', 'two', 'three', 'four']]
elif self.app.config['Display']['PanelCount'] == '6':
panel_ids = [['panel_' + number for number in ['one', 'two', 'three']],
['panel_' + number for number in ['four', 'five', 'six']]]
button_ids = ['button_' + number for number in ['one', 'two', 'three', 'four', 'five', 'six']]
# Add primary panels to screen and initialise required buttons
for row in range(len(panel_ids)):
row_box_layout = BoxLayout(spacing='5dp')
self.ids['row_layout'].add_widget(row_box_layout)
for panel_id in panel_ids[row]:
button_id = button_ids[button_count]
primary_panel = primary_panels[panel_count][1]
secondary_panel = secondary_panels[panel_count][1]
self.ids[panel_id] = BoxLayout()
self.ids[panel_id].add_widget(eval(primary_panel + 'Panel')())
row_box_layout.add_widget(self.ids[panel_id])
if secondary_panel:
self.ids[button_id].add_widget(eval(secondary_panel + 'Button')())
self.button_list.append([button_id, panel_id, primary_panel, secondary_panel, 'primary'])
button_count += 1
panel_count += 1
# SWITCH BETWEEN PRIMARY AND SECONDARY PANELS ON CURRENT CONDITIONS SCREEN
# --------------------------------------------------------------------------
def switchPanel(self, button_pressed, button_overide=None, *args):
# Determine ID of button that has been pressed and extract corresponding
# entry in buttonList
if button_pressed:
for id, object in self.ids.items():
if object == button_pressed.parent.parent:
break
else:
id = button_overide[0]
for ii, button_data in enumerate(self.button_list):
if button_data[0] == id:
break
# Cancel lightning_panel_timeout if scheduled and Lightning button has
# been pressed
if 'Lightning' in button_data and hasattr(self.app.Sched, 'lightning_panel_timeout'):
self.app.Sched.lightning_panel_timeout.cancel()
# Extract panel object that corresponds to the button that has been
# pressed and determine new button type required
panel_object = self.ids[button_data[1]].children
panel_number = 'Panel' + button_data[1].split('_')[1].title()
panel_type = button_data[4].title() + 'Panels'
new_button = self.app.config[panel_type][panel_number]
if panel_type == 'PrimaryPanels':
new_panel = self.app.config['SecondaryPanels'][panel_number]
elif panel_type == 'SecondaryPanels':
new_panel = self.app.config['PrimaryPanels'][panel_number]
# Destroy reference to old panel class attribute
if hasattr(self.app, new_button + 'Panel'):
try:
getattr(self.app, new_button + 'Panel').remove(panel_object[0])
except ValueError:
Logger.warning('Unable to remove panel reference from wfpiconsole class')
if button_overide:
mode = 'auto'
else:
mode = 'manual'
# Switch panel
self.ids[button_data[1]].clear_widgets()
self.ids[button_data[1]].add_widget(eval(new_panel + 'Panel')(mode))
self.ids[button_data[0]].clear_widgets()
self.ids[button_data[0]].add_widget(eval(new_button + 'Button')())
# Update button list
if button_data[4] == 'primary':
self.button_list[ii][4] = 'secondary'
elif button_data[4] == 'secondary':
self.button_list[ii][4] = 'primary'
# ==============================================================================
# RUN APP
# ==============================================================================
if __name__ == '__main__':
try:
wfpiconsole_app = wfpiconsole()
wfpiconsole_app.run()
if REBOOT:
subprocess.call('sudo shutdown -r now', shell=True)
elif SHUTDOWN:
subprocess.call('sudo shutdown -h now', shell=True)
except KeyboardInterrupt:
wfpiconsole_app.stop()
except Exception:
wfpiconsole_app.stop()
raise