-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
369 lines (283 loc) · 9.89 KB
/
main.py
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
from portiOSEssentials import *
#######################################################
class Main_GUI:
def __init__(self, main_win, app):
# Setting window
self.win = main_win
self.app = app
# Setting fullscreen
# self.win.showFullScreen()
# Settings mouse
# self.win.setCursor(Qt.BlankCursor)
# Main loog Hz
self.mainLoopHz = 1
# Debug
self.DEBUG = True
# Check if config file exists
if not os.path.exists('config.txt'):
with open('config.txt', 'w'):
pass
# Getting config data
self.config = {}
self.setupConfig()
# ADC converter controller
self.adcController = Adafruit_ADS1x15.ADS1115(address=0x4A)
self.GAUGE_ADS_CHANNEL = 0
self.VOLUME_ADS_CHANNEL = 2
self.GAIN = 1
self.MAX_ADS_VALUE = 32752
# Setting media player
self.isConnectedDevice = False
self.BTController = BT_Control_Panel()
self.startMediaPlayer()
self.volume = 0
# GPIO setup
gp.setmode(gp.BOARD)
gp.setwarnings(False)
# Pins
self.pinsLeds = (33, 31, 29)
self.pinsPower = 26
self.pinsIRR = 32
self.pinsButtons = (40, 38, 36, 37, 35)
# Leds controller
self.ledsController = RGB_Controller(self.pinsLeds) # Pins
# IRReceive controller
self.IRR = IRReceiver(self.pinsIRR, self.IRRCallback)
# System info manager
self.systemInfo = System_info()
# Media info
self.track = None # Track info dictionary
self.songTitle = None
self.songArtist = None
self.trackDuration = None # Duration of the actual track
self.currentMusicTime = None # Music position in microseconds
self.currentMusicTimeF = None # Formated music porsition time (M:SS)
# Widgets objects
self.GUI_Central = None
self.GUI_Dashboard = None
self.GUI_Apps = None
self.GUI_Leds = None
self.GUI_Player = None
self.GUI_Settings = None
self.GUI_Maps = None
# Widget funcs setup
Central_funcs.centralSetup(self)
Dashboard_funcs.dashboardSetup(self)
Apps_funcs.appsSetup(self)
Leds_funcs.ledsSetup(self)
Player_funcs.playerSetup(self)
Settings_funcs.settingsSetup(self)
Maps_funcs.mapSetup(self)
def toggle_musicStatus(self, setStatus=None):
if self.BTController.checkConnectedDevices():
status = str(self.BTController.get_player_data('Status'))
if setStatus:
if setStatus == 'playing': status = 'paused'
elif setStatus == 'paused': status = 'playing'
name = None
icon1 = QIcon()
if status == 'playing':
name = 'play-fill'
self.BTController.playback_control('pause')
elif status == 'paused':
name = 'pause-fill'
self.BTController.playback_control('play')
icon1.addFile(u":/icons_red/Resources/Icons/png-red/{}.png".format(name), QSize(30, 30), QIcon.Normal, QIcon.Off)
# Changing central and player icon
self.GUI_Central.footerButton_2.setIcon(icon1)
self.GUI_Player.playButton.setIcon(icon1)
# The sync system updates with the slider value
def sliderSyncVolume(self):
def volThread():
s = self.GUI_Central.slider_volume.value()
self.BTController.set_local_volume(s, maxlevel=127)
t1 = threading.Thread(target=volThread)
t1.start()
def mediaDataChanged(self, _, data, __):
key = list(dict(data).keys())[0]
values = list(dict(data).values())[0]
if key == 'Status':
self.toggle_musicStatus(str(self.BTController.get_player_data('Status')))
elif key == 'Volume':
self.GUI_Central.slider_volume.setValue(int(values))
elif key == 'Track':
self.track = values
if len(self.track) == 1:
self.trackDuration = int(self.track['Duration'])
else:
self.songTitle = str(self.track['Title'])
try:
self.songArtist = str(self.track['Artist'])
except KeyError:
e = self.track['Title'].split('•')
self.songTitle = e[0].strip()
self.songArtist = e[1].strip()
# Updating labels on all pages
Dashboard_funcs.changeMusicInfo(self)
Player_funcs.changeMusicInfo(self)
def IRRCallback(self, data):
# Functions
def setVol(value):
vol = self.GUI_Central.slider_volume.value()
vol += value
if vol < 0: vol = 0
elif vol >127: vol = 127
self.GUI_Central.slider_volume.setValue(vol)
def navControls(control):
try:
if not self.GUI_Apps.navigator.started_trip: return
except AttributeError:
print('Not started trip')
return
if control == 'prev':
self.GUI_Apps.navigator.anterior_instruccion()
elif control == 'next':
self.GUI_Apps.navigator.siguiente_instruccion()
# Remote data
try: dataStr = self.GUI_Settings.remoteButtons[data]
except KeyError:
print('Remote button error!')
return
if dataStr == 'power': Leds_funcs.toggleLedPower(self)
elif dataStr == 'play': self.toggle_musicStatus()
elif dataStr == 'vol+': setVol(20)
elif dataStr == 'vol-': setVol(-20)
elif dataStr == 'prev': self.BTController.playback_control('previous')
elif dataStr == 'next': self.BTController.playback_control('next')
elif dataStr == 'func/stop': Apps_funcs.endNavigation(self)
elif dataStr == 'up': navControls('prev')
elif dataStr == 'down': navControls('next')
elif dataStr == 'eq': Central_funcs.setPage(self, 1)
elif dataStr == 'st/rept': Central_funcs.setPage(self, 4)
elif dataStr == '0': pass
elif dataStr == '1': pass
elif dataStr == '2': pass
elif dataStr == '3': pass
elif dataStr == '4': pass
elif dataStr == '5': pass
elif dataStr == '6': pass
elif dataStr == '7': pass
elif dataStr == '8': pass
elif dataStr == '9': pass
def formatDuration(self, duration):
duration = int(duration)
duration = ceil(duration / 1000)
mins = int(duration / 60)
segs = int(((duration / 60) - mins) * 60)
return str(mins) + ':' + f'{segs:02}'
def setupConfig(self):
with open('config.txt', 'r') as file:
lines = file.readlines()
if not lines: return None
header = None
for line in lines:
line = line.strip() # Removing endliners
if not line: continue # Continue for empty lines
if re.match('\[\w+\]', line): # Looking for headers
continue
if line[0] == '#': continue # Looking for comments
line = line.split('=')
try:
self.config[line[0]] = line[1]
except IndexError:
raise IOError('"config.txt" file has wrong format, ex: key=value')
return self.config
def getConfig(self, x):
try:
out = self.config[x]
except KeyError:
return None
if out == 'true': return True
elif out == 'false': return False
elif re.match('.', out):
try:
return float(out)
except ValueError:
pass
try:
return int(out)
except ValueError:
pass
return out
def setConfig(self, key, value):
print(f"[+] Set config {key} = {value}")
self.config[key] = value
with open('config.txt', 'w') as file:
lines = []
for line in self.config.items():
lines.append(f'{line[0]}={line[1]}\n')
file.writelines(lines)
def startMediaPlayer(self):
self.mediaPlayerThread = threading.Thread(target=self.mediaPlayerThreadFunc)
self.mediaPlayerThread.start()
def mediaPlayerThreadFunc(self):
try:
while 1:
time.sleep((1/self.mainLoopHz))
##################### CONNECTIONS MANAGER ###################################
try:
checkDevice = self.BTController.checkConnectedDevices()
except dbus.exceptions.DBusException:
try:
self.BTController = BT_Control_Panel()
except:
print('No BT object available')
# Check for connected devices
# Setting BT status disconnected
if self.isConnectedDevice == True and checkDevice == False:
self.isConnectedDevice = False
icon = QIcon()
icon.addFile(u":/bt_icons/Resources/Icons/bt_states/bluetooth_gray.png", QSize(), QIcon.Normal, QIcon.Off)
self.GUI_Central.bluetoothStatusButton.setIcon(icon)
continue
# Setup on new connection
if self.isConnectedDevice == False and checkDevice == True:
time.sleep(1)
self.BTController.setupInterfaces()
self.isConnectedDevice = True
# BT status icon on
icon = QIcon()
icon.addFile(u":/bt_icons/Resources/Icons/bt_states/bluetooth_blue.png", QSize(), QIcon.Normal, QIcon.Off)
self.GUI_Central.bluetoothStatusButton.setIcon(icon)
self.GUI_Central.slider_volume.setValue(self.BTController.get_volume_data())
if str(self.BTController.get_player_data('Status')) == 'playing':
self.toggle_musicStatus(setStatus='playing')
self.BTController.bus.add_signal_receiver(self.mediaDataChanged,
dbus_interface = "org.freedesktop.DBus.Properties",
signal_name = "PropertiesChanged",
)
###########################################################################
# THREAD SETUP
# Central clock
self.GUI_Central.label_clock.setText(time.strftime('%H:%M'))
# Volume
# value = self.adcController.read_adc(1, gain=self.GAIN)
# fvalue = int(value/self.MAX_ADS_VALUE*127)
# if self.volume != fvalue:
# print("[+] Set volume to ", fvalue)
# self.BTController.set_local_volume(fvalue, maxlevel=127)
# self.volume = fvalue
# When device is connected
if checkDevice:
# Music current time
if str(self.BTController.get_player_data('Status')) == 'playing':
# Formatin time
self.currentMusicTime = self.BTController.get_player_data('Position')
self.currentMusicTimeF = self.formatDuration(self.currentMusicTime)
# Dashboard player
if self.GUI_Central.appsWidget.currentIndex() == 0:
self.GUI_Dashboard.label_currentTime.setText(self.currentMusicTimeF)
self.GUI_Dashboard.slider_duration.setValue(self.currentMusicTime)
# Media player
elif self.GUI_Central.appsWidget.currentIndex() == 1:
self.GUI_Player.label_currentTime.setText(self.currentMusicTimeF)
self.GUI_Player.slider_duration.setValue(self.currentMusicTime)
except:
if self.DEBUG: print("[!] Error at media player thread")
#######################################################
if __name__ == '__main__':
app = QApplication(sys.argv)
win = QMainWindow()
main_gui = Main_GUI(win, app)
win.show()
sys.exit(app.exec_())