-
Notifications
You must be signed in to change notification settings - Fork 0
/
hu.py
executable file
·1789 lines (1415 loc) · 46.6 KB
/
hu.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
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#
# A car's headunit.
# Venema, S.R.G.
# 2018-03-17
# License: MIT
#
# HEADUNIT is the main script in a constellation of micro-services.
# This script acts as a watchdog and serves some basic system functions.
#
# The microservices are either started via init.d or via this script.
#
# ARGUMENTS:
#? --resume
#? --source resume|source name
#? --subsource
#
#********************************************************************************
# CONFIGURATION and SETTINGS
#
# configuration.json Main configuration file (json)
# dSettings.json Operational settings (json)
#
# Operational source settings, to continue playback (pickled):
#
# fm.p
# media /<uuid>.p
# /<uuid>_dirs.txt
# locmus/<mountpoint>.p
# /<mountpoint>_dirs.txt
# smb /<ip_mountpoint>.p 172_16_8_11_music.p
# /<ip_mountpoint>_dirs.txt 172_16_8_11_music_dirs.txt
#
# ?:
# stream, line, bt
#
#********************************************************************************
# LOGGING and CONSOLE output
#
# All output is channeled through the Python logger, in order to both be displayed
# on the console and written to the syslog or a logfile.
#
# When given the -b ("background") argument all output is written to the syslog,
# otherwise it's written to the console.
#
# The logfile writer is currently not used.
#
# Please don't use the print() function. Instead use the printer() function. Or:
# - logger.info(message, extra={'tag': tag}) # or any other desired log level
#
# Default log level can be overridden via command line parameters. Default:
# > Log level INFO or higher is sent to the console.
# > Log level DEBUG or higher is sent to the log file.
#
# Output sent to the file is cleansed of any ANSI formatting.
#
#********************************************************************************
# DBUS
#
# This script listens to a number of DBus sources.
# This script also emits signals on com.arctura.hu #TODO
#********************************************************************************
# PLUGINS
#
# Originally these were started via threading or multiprocessing, but in either
# case messed up the later introduced queing worker threads. For now we'll
# manually start the plugins
#
# Try: gobject.spawn_async
#
#********************************************************************************
# MODULES
#
# Automatically loaded:
#
# ./sources/* Source plugins
# ./plugin_control/* Controller plugins } NOT ANY MORE, SEE: ISSUES, PLUGINS
# ./plugin_other/* Other plugins }
#
# ./hu_utils.py Misc. handy functions
# ./hu_volume.py Volume control
# ./hu_....py
import sys
import os
from modules.hu_utils import *
from version import __version__ # Version
from logging import getLogger # Logging
import time # temporary / debugging:
import json # load json source configuration
import inspect # dynamic module loading
from Queue import Queue # queuing
import threading # multithreading
import subprocess # multithreading
# dbus
import dbus.service
import dbus.exceptions
# main loop
import gobject
from dbus.mainloop.glib import DBusGMainLoop
# support modules
from modules.hu_msg import MqPubSubFwdController
from modules.hu_pulseaudio import *
from modules.hu_volume import *
from modules.hu_settings import *
from modules.hu_mpd import *
#********************************************************************************
# Third party and others...
#
from slugify import slugify
# *******************************************************************************
# Global variables and constants
#
DESCRIPTION = "Headunit"
LOG_TAG = 'HEDUNT'
LOGGER_NAME = 'hedunt'
DEFAULT_CONFIG_FILE = '/etc/configuration.json'
CONFIG_FILE_DEFAULT = '/mnt/PIHU_APP/defender-headunit/config/configuration.json'
DEFAULT_LOG_LEVEL = LL_INFO
DEFAULT_PORT_SUB = 5560
DEFAULT_PORT_PUB = 5559
SUBSCRIPTIONS = ['/events/']
logger = None # logging
args = None # command line arguments
messaging = None # mq messaging
configuration = None # configuration
sc_sources = None # source controller
mpdc = None # mpd controller
# SEMI-CONSTANTS (set at startup)
SOURCE = None
SOURCE_SUB = None
#OLD AND REMOVE:
PID_FILE = "hu"
ENV_SOURCE = os.getenv('HU_SOURCE')
Sources = None #Temp.. REMOVE
disp = None # REMOVE
hu_details = { 'track':None, 'random':'off', 'repeat':True, 'att':False }
arMpcPlaylistDirs = [ ] #TODO: should probably not be global...
#def volume_att_toggle():
# hudispdata = {}
# hudispdata['att'] = '1'
# disp.dispdata(hudispdata)
# return None
# ********************************************************************************
# Output wrapper
#
def printer( message, level=LL_INFO, continuation=False, tag=LOG_TAG ):
logger.log(level, message, extra={'tag': tag})
def queue(q, item, sfx=None):
#printer('Blocking Queue Size before: {0}'.format(qBlock.qsize()))
try:
if q == 'prio':
qPrio.put(item, False)
elif q == 'blocking':
qBlock.put(item, False)
elif q == 'async':
qAsync.put(item, False)
except queue.Full:
printer('Queue is full.. ignoring button press.')
return None
# play sfx, if successfully added to queue and sfx defined
if sfx:
pa_sfx(sfx)
#printer('Blocking Queue Size after: {0}'.format(qBlock.qsize()))
return 0
# todo: rename? put in hu_settings?
def save_current_position(timeelapsed):
global Sources
global mpdc
currSrc = Sources.getComposite()
# create filename
source_name = currSrc["name"]
if not 'subsource' in currSrc:
print "TODO: resume not (YET) supported for this source, sorry."
print currSrc
return None
if 'filename_save' in currSrc:
source_key = currSrc["filename_save"][0] #eg "mountpoint"
if source_key in currSrc["subsource"]:
source_key_value = slugify( currSrc["subsource"][source_key] )
else:
printer("Error creating savefile, source_key ({0}) doesn't exist".format(source_key))
source_key_value = "untitled"
else:
printer('Error: "filename_save" not defined in configuration, not saving.',level=LL_ERROR)
return None
# get time into track
#timeelapsed = status['time']
# get track name
currSong = mpdc.mpc_get_currentsong()
current_file = currSong['file']
"""print currSong
{'album': 'Exodus', 'composer': 'Andy Hunter/Tedd T.', 'title': 'Go', 'track': '1', 'duration': '411.480',
'artist': 'Andy Hunter', 'pos': '0', 'last-modified': '2013-10-12T15:53:13Z', 'albumartist': 'Andy Hunter',
'file': 'PIHU_SMB/music/electric/Andy Hunter/Andy Hunter - 2002 - Exodus/01 - Andy Hunter - Go.mp3',
'time': '411', 'date': '2002', 'genre': 'Electronic/Dance', 'id': '44365'}
"""
# put it together
dSave = {'file': current_file, 'time': timeelapsed}
# save file
printer('Saving playlist position for: {0}: {1}'.format(source_name,source_key_value))
#print(' ... file: {0}, time: {1}'.format(current_file,timeelapsed))
# create path, if it doesn't exist yet..
pckl_path = os.path.join('/mnt/PIHU_CONFIG',source_name)
if not os.path.exists(pckl_path):
os.makedirs(pckl_path)
# pickle file will be created by dump, if it doesn't exist yet
pckl_file = os.path.join(pckl_path,source_key_value + ".p")
pickle.dump( dSave, open( pckl_file, "wb" ) )
def load_current_resume():
global Sources
global mpdc
currSrc = Sources.getComposite()
# create filename
source_name = currSrc["name"]
if not 'subsource' in currSrc:
print "TODO: resume not (YET) supported for this source, sorry."
print currSrc
return None
if 'filename_save' in currSrc:
source_key = currSrc["filename_save"][0] #eg "mountpoint"
if source_key in currSrc["subsource"]:
source_key_value = slugify( currSrc["subsource"][source_key] )
else:
printer("Error creating savefile, source_key ({0}) doesn't exist".format(source_key))
source_key_value = "untitled"
else:
printer('Error: "filename_save" not defined in configuration, not saving.',level=LL_ERROR)
return None
# load file
printer('Loading playlist position for: {0}: {1}'.format(source_name,source_key_value))
# check if there's a save file..
pckl_file = os.path.join('/mnt/PIHU_CONFIG',source_name,source_key_value + ".p")
if not os.path.exists(pckl_file):
printer('ERROR: Save file not found',level=LL_WARNING)
return None
else:
dLoad = pickle.load( open( pckl_file, "rb" ) )
return dLoad
def dispatcher(path, command, arguments):
print("[MQ] Received Path: {0}; Command: {1}; Parameters: {2}".format(path,command,arguments))
handler_function = 'handle_path_' + path[0]
if handler_function in globals():
globals()[handler_function](path, command, arguments)
else:
print("No handler for: {0}".format(handler_function))
# Handler for path: /system/
def handle_path_system(path,cmd,args):
base_path = 'system'
# remove base path
del path[0]
def put_reboot(**kwargs):
print("Rebooting!")
return True
def put_halt(**kwargs):
print("Halting!")
return True
if path:
function_to_call = cmd + '_' + '_'.join(path)
else:
# called without sub-paths
function_to_call = cmd + '_' + base_path
if function_to_call in locals():
ret = locals()[function_to_call](args)
printer('Executed {0} function {1} with result status: {2}'.format(base_path,function_to_call,ret))
else:
printer('Function {0} does not exist'.format(function_to_call))
# ********************************************************************************
# euuhh.
def idle_msg_receiver():
global messaging
msg = messaging.receive_async()
if msg:
print "Received message: {0}".format(msg)
parsed_msg = messaging.parse_message(msg)
dispatcher(parsed_msg['path'],parsed_msg['cmd'],parsed_msg['args'])
return True
# ********************************************************************************
# Callback functions
#
# - Remote control
# - MPD events
# - Timer
# - UDisk add/remove drive
#
def cb_remote_btn_press2 ( func ):
print "cb_remote_btn_press2 {0}".format(func)
#
#def seek_next():
# Sources.sourceSeekNext()
#global dSettings
#if dSettings['source'] == 1 or dSettings['source'] == 2 or dSettings['source'] == 5 or dSettings['source'] == 6:
# mpc_next_track()
#elif dSettings['source'] == 3:
# bt_next()
#fm_next ofzoiets
"""
def seek_prev():
global dSettings
if dSettings['source'] == 1 or dSettings['source'] == 2 or dSettings['source'] == 5 or dSettings['source'] == 6:
mpc_prev_track()
elif dSettings['source'] == 3:
bt_prev()
"""
# Handle button press
def cb_remote_btn_press ( func ):
queue_func = {'command':func}
if func == 'SHUFFLE':
printer('\033[95m[BUTTON] Shuffle\033[00m')
queue('blocking',queue_func)
elif func == 'SOURCE':
printer('\033[95m[BUTTON] Next source\033[00m')
queue('blocking',queue_func,'button_feedback')
elif func == 'ATT':
printer(colorize('[BUTTON] ATT','light_magenta'))
queue('prio',queue_func,'button_feedback')
elif func == 'VOL_UP':
printer(colorize('VOL_UP','light_magenta'),tag='button')
queue('prio',queue_func,'button_feedback')
elif func == 'VOL_DOWN':
print('\033[95m[BUTTON] VOL_DOWN\033[00m')
queue('prio',queue_func,'button_feedback')
elif func == 'SEEK_NEXT':
print('\033[95m[BUTTON] Seek/Next\033[00m')
queue('blocking',queue_func,'button_feedback')
elif func == 'SEEK_PREV':
print('\033[95m[BUTTON] Seek/Prev.\033[00m')
queue('blocking',queue_func,'button_feedback')
elif func == 'DIR_NEXT':
print('\033[95m[BUTTON] Next directory\033[00m')
queue('blocking',queue_func)
elif func == 'DIR_PREV':
print('\033[95m[BUTTON] Prev directory\033[00m')
queue('blocking',queue_func)
elif func == 'UPDATE_LOCAL':
print('\033[95m[BUTTON] Updating local MPD database\033[00m')
queue('async',queue_func,'button_feedback')
elif func == 'OFF':
print('\033[95m[BUTTON] Shutting down\033[00m')
queue('prio',queue_func,'button_feedback')
else:
print('Unknown button function')
pa_sfx('error')
def cb_mpd_event( event ):
global settings
global mpdc
#def mpc_save_pos_for_label ( label, pcklPath ):
"""
def save_pos_for_label ( label, pcklPath ):
oMpdClient.command_list_ok_begin()
oMpdClient.status()
results = oMpdClient.command_list_end()
songid = None
testje = None
current_song_listdick = None
# Dictionary in List
try:
for r in results:
songid = r['songid']
timeelapsed = r['time']
current_song_listdick = oMpdClient.playlistid(songid)
except:
print(' ... Error, key not found!')
print results
#print("DEBUG: current song details")
debugging = oMpdClient.currentsong()
try:
#print debugging
testje = debugging['file']
#print testje
except:
print(' ... Error, key not found!')
print debugging
if testje == None:
print('DEBUG: BREAK BREAK')
return 1
if songid == None:
current_file=testje
else:
for f in current_song_listdick:
current_file = f['file']
dSavePosition = {'file': current_file, 'time': timeelapsed}
print(' ... file: {0}, time: {1}'.format(current_file,timeelapsed))
#if os.path.isfile(pickle_file):
pickle_file = pcklPath + "/mp_" + label + ".p"
pickle.dump( dSavePosition, open( pickle_file, "wb" ) )
"""
printer('DBUS event received: {0}'.format(event), tag='MPD')
# anything related to the player
if event == "player":
printer('Detected MPD event: player. Retrieving MPD state.')
# first let's determine the state:
status = mpdc.mpc_get_status()
#print "STATUS: {0}.".format(status)
#print "STATE : {0}.".format(status['state'])
"""status:
{'songid': '14000', 'playlistlength': '7382', 'playlist': '8', 'repeat': '1', 'consume': '0', 'mixrampdb': '0.000000',
'random': '1', 'state': 'play', 'elapsed': '0.000', 'volume': '100', 'single': '0', 'nextsong': '806', 'time': '0:239',
'duration': '239.020', 'song': '6545', 'audio': '44100:24:2', 'bitrate': '0', 'nextsongid': '8261'}
"""
if 'state' in status:
if status['state'] == 'stop':
print ' > MPD playback has stopped.. ignoring this'
elif status['state'] == 'pause':
print ' > MPD playback has been paused.. ignoring this'
elif status['state'] == 'play':
printer(' > MPD playback is playing, saving to file. (SEEK/NEXT/PREV)')
# one of the following possible things have happened:
# - prev track, next track, seek track
#
# Save position
#
timeelapsed = status['time']
save_current_position(timeelapsed)
""" PROBLEMS AHEAD
LCD DISPLAY
#hu_details
mpcSong = mpdc.mpc_get_currentsong()
#mpcStatus = mpdc.mpc_get_status()
mpcTrackTotal = mpdc.mpc_get_trackcount()
if 'artist' in mpcSong:
artist = mpcSong['artist']
else:
artist = None
if 'title' in mpcSong:
title = mpcSong['title']
else:
title = None
if 'track' in mpcSong:
track = mpcSong['track']
else:
track = None
file = os.path.basename(mpcSong['file'])
#disp.lcd_play( artist, title, file, track, mpcTrackTotal )
"""
elif event == "update":
printer(" ... database update started or finished (no action)", tag='MPD')
elif event == "database":
printer(" ... database updated with new music #TODO", tag='MPD')
# let's determine what has changed
""" TODO: UNCOMMENT THIS
#IF we're already playing local music: Continue playing without interruption
# and add new tracks to the playlist
# Source 2 = locmus
if dSettings['source'] == 2:
print(' ...... source is already playing, trying seamless update...')
# 1. "crop" playlist (remove everything, except playing track)
call(["mpc", "-q" , "crop"])
yMpdClient = MPDClient()
yMpdClient.connect("localhost", 6600)
# 2. songid is not unique, get the full filename
current_song = yMpdClient.currentsong()
curr_file = current_song['file']
print(' ...... currently playing file: {0}'.format(curr_file))
# 3. reload local music playlist
mpc_populate_playlist(sLocalMusicMPD)
# 4. find position of song that we are playing, skipping the first position (pos 0) in the playlist, because that's where the currently playing song is
delpos = '0'
for s in yMpdClient.playlistinfo('1:'):
if s['file'] == curr_file:
print(' ...... song found at position {0}'.format(s['pos']))
delpos = s['pos']
if delpos != '0':
print(' ...... moving currently playing track back in place')
yMpdClient.delete(delpos)
yMpdClient.move(0,int(delpos)-1)
else:
print(' ...... ERROR: something went wrong')
pa_sfx('error')
yMpdClient.close()
#IF we were not playing local music: Try to switch to local music, but check if the source is OK.
else:
#We cannot check if there's any NEW tracks, but let's check if there's anything to play..
locmus_check()
# Source 2 = locmus
#if arSourceAvailable[2] == 1:
if Sources.getAvailable('name','locmus')
dSettings['source'] = 2
source_play()
else:
print('[LOCMUS] Update requested, but no music available for playing... Doing nothing.')
"""
elif event == "playlist":
priner(" ... playlist changed (no action)", tag='MPD')
#elif event == "media_removed":
#elif event == "media_ready":
# TEMPORARY -- DON'T DEPEND ON MPD FOR THIS -- USE DBUS #
elif event == "ifup":
cb_ifup()
elif event == "ifdown":
cb_ifdn()
else:
printer(' ... unknown event (no action)', tag='MPD')
# Timer 1: executed every 30 seconds
def cb_timer1():
global cSettings
#global disp
printer('Interval function [30 second]', level=LL_DEBUG, tag="TIMER1")
# save current position
# TODO: ONLY WHEN WE'RE ACTUALLY PLAYING SOMETHING...
#save_current_position()
# WHAT'S THE POINT OF THIS?:
# save settings (hu_settings)
cSettings.save()
#hudispdata = {}
#hudispdata['src'] = "USB" #temp.
#disp.dispdata(hudispdata)
return True
# called when the ifup script is called (interface up)
def cb_ifup():
global Sources
printer("WiFi interface UP: checking network related sources")
ix = 0
for source in Sources.getAll():
if source['depNetwork']:
#Sources.sourceCheck(ix)
Sources.sourceInit(ix) #TODO -- Add a re-init or something... or extend check() with init stuff
ix += 1
# display overview
printSummary(Sources)
# called when the ifdown script is called (interface down)
def cb_ifdn():
global Sources
printer("WiFi interface DOWN: marking network related sources unavailable")
# set all network dependend sources to unavailable
# TODO: We're assuming we only have wlan, add a check for any remaining interfaces in case we have other
Sources.setAvailable('depNetwork',True,False)
# display overview
printSummary(Sources)
# ********************************************************************************
# Headunit functions
#
def volume_att():
global volm
global hu_details
if 'att' in hu_details:
hu_details['att'] = not hu_details['att']
else:
hu_details['att'] = True
if hu_details['att']:
volm.set('20%')
else:
pre_att_vol = '60%' #TODO #VolPulse.get()
volm.set(pre_att_vol)
def do_source():
pass
def hu_play( index=None, index_sub=None, resume=True ):
global Sources
global cSettings
# set current index, if given
if not index is None:
Sources.setCurrent(index, index_sub)
if resume:
dLoaded = load_current_resume()
if not dLoaded is None:
Sources.sourcePlay(dLoaded)
else:
Sources.sourcePlay()
else:
Sources.sourcePlay()
# get current index(es)
arCurrIx = Sources.getIndexCurrent()
# get current source
currSrc = Sources.get(None)
# update source name
cSettings.set('source',currSrc['name'])
# update sub-source key (in case of sub-source)
if not arCurrIx[1] == None:
subsource_key = {}
for key in currSrc['subsource_key']:
subsource_key[key] = currSrc['subsources'][arCurrIx[1]][key]
cSettings.set('subsourcekey', subsource_key)
# commit changes
cSettings.save()
def dir_next():
global Sources
global arMpcPlaylistDirs
# get current source
currSrc = Sources.get(None)
# check if the source supports dirnext
if 'dirnext' in currSrc['controls'] and currSrc['controls']['dirnext']:
pa_sfx('button_feedback')
if not arMpcPlaylistDirs:
printer(' > Building new dirlist.. standby!', tag='nxtdir')
# TESTING
dir_to_file( True )
# TESTING
#ardirs = load_dirlist()
else:
printer(' > Reusing dirlist', tag='nxtdir')
# TESTING
nextpos = mpc_next_folder_pos(arMpcPlaylistDirs)
printer(' > Next folder @ {0}'.format(nextpos))
call(["mpc", "-q", "random", "off"])
call(["mpc", "-q", "play", str(nextpos)])
else:
pa_sfx('error')
printer('Function not available for this source.', level=LL_WARNING)
# change? instead pass a variable to be filled with the dirlist?
def dir_to_file( current=True ):
global arMpcPlaylistDirs
# local variables
dirname_current = ''
dirname_prev = ''
iPos = 1
pipe = Popen('mpc -f %file% playlist', shell=True, stdout=PIPE)
# if current == True, then update the global current dirlist, so first clear it:
if current:
arMpcPlaylistDirs = [ ]
# todo: future, create them per (sub)source
dirfile = '/mnt/PIHU_CONFIG/dl_current.txt'
with open(dirfile,'w') as dirs:
for line in pipe.stdout:
dirname_current=os.path.dirname(line.strip())
t = iPos, dirname_current
if dirname_prev != dirname_current:
# if current == True, then update the global current dirlist
if current:
arMpcPlaylistDirs.append(t)
dirs.write("{0}|{1}\n".format(iPos,dirname_current))
dirname_prev = dirname_current
iPos += 1
def load_dirlist():
dirfile = '/mnt/PIHU_CONFIG/dl_current.txt'
with open(dirfile,'r') as dirs:
for l in dirs:
#t = l.split('|')
t = [x.strip() for x in l.split('|')]
arMpcPlaylistDirs.append(t)
print arMpcPlaylistDirs
return arMpcPlaylistDirs
def mpc_next_folder_pos(arMpcPlaylistDirs):
# Get current folder
pipe = subprocess.check_output("mpc -f %file%", shell=True)
dirname_current = os.path.dirname(pipe.splitlines()[0])
print(' ... Current folder: {0:s}'.format(dirname_current))
#print(' >>> DEBUG info:')
#print mpc_get_PlaylistDirs_thread.isAlive()
try:
iNextPos = arMpcPlaylistDirs[([y[1] for y in arMpcPlaylistDirs].index(dirname_current)+1)][0]
print(' ... New folder = {0:s}'.format(arMpcPlaylistDirs[([y[1] for y in arMpcPlaylistDirs].index(dirname_current)+1)][1]))
except IndexError:
# I assume the end of the list has been reached...
print(' ... ERROR: IndexError - restart at 1')
iNextPos = 1
return iNextPos
# set random; req_state: <toggle | on | off>
# todo: implement "special random"-modes: random within album, artist, folder
def set_random( req_state ):
#global dSettings
global mpdc
global hu_details
global Sources
# get current random state
curr_state = hu_details['random']
printer('Random/Shuffle: Current:{0}, Requested:{1}'.format(curr_state, req_state), tag='random')
if req_state == curr_state:
printer('Already at requested state', tag='random')
return False
# get current source
currSrc = Sources.get(None)
# check if the source supports random
if not 'random' in currSrc or len(currSrc['random']) == 0:
printer('Random not available for this source', tag='random')
return False
# check type, we only support mpd at this time
if not 'type' in currSrc or not currSrc['type'] == 'mpd':
printer('Random not available for this source type (only mpd)', tag='random')
return False
# set newState
if req_state in currSrc['random']:
newState = req_state
elif req_state == 'toggle':
if curr_state == 'off':
newState = 'on'
elif curr_state == 'on':
newState = 'off'
else:
#newState = '' #mpc will toggle
printer('Can only toggle when state is on or off', tag='random')
return False
# sound effect
if newState == 'on':
pa_sfx('button_feedback')
elif newState == 'off':
pa_sfx('reset_shuffle')
# update display
printer('Setting Random/Shuffle to: {0}'.format(newState), tag='random')
hudispdata = {}
hudispdata['rnd'] = newState
disp.dispdata(hudispdata)
# apply newState
hu_details['random'] = newState
mpdc.random( newState )
# bluetooth:
"""
elif dSettings['source'] == 3:
pa_sfx('button_feedback')
bt_shuffle()
else:
print(' ... Random/Shuffle not supported for this source.')
"""
return True
def do_update():
global Sources
def locmus_update( folder ):
global mpdc
#Update database
mpdc.update( folder, False ) # False = Don't wait for completion (will be picked up by the mpd callback)
# get local folders
for source in Sources.getAll():
if source['name'] == 'locmus':
if 'subsources' in source and len(source['subsources']) > 0:
printer('Updating local database')
for subsource in source['subsources']:
if 'mpd_dir' in subsource:
mpd_dir = subsource['mpd_dir']
locmus_update(mpd_dir)
else:
printer('No local databases configured', level=LL_WARNING)
else:
printer('No local source available', level=LL_WARNING)
# the only update is an locmus_update ;-)
#locmus_update()
# ********************************************************************************
# Misc. functions
#
# turn off the device
def shutdown():
global configuration
global cSettings
global Sources
# save settings (hu_settings)
cSettings.save()
# stop source (hu_source)
Sources.sourceStop()
# call shutdown command
""" This command may be different on different distributions, therefore it's saved in the configuration
Debian: call(["systemctl", "poweroff", "-i"])
Buildroot: call(["halt"])
"""
call(configuration['shutdown_cmd'])
# ********************************************************************************
# Initialization functions
#
# - Loggers
# - Configuration
# - Operational settings
#
# Initiate logging to log file.
# Use logger.info instead of print.
def init_logging_f( logdir, logfile, runcount ):
global logger
# create the log dir, if it doesn't exist yet
if not os.path.exists(logdir):
os.makedirs(logdir)
iCounterLen = 6
currlogfile = os.path.join(logdir, logfile+'.'+str(runcount).rjust(iCounterLen,'0')+'.log')
# create file handler
fh = logging.FileHandler(currlogfile)
fh.setLevel(logging.DEBUG)
# create formatters
fmtr_fh = RemAnsiFormatter("%(asctime)-9s [%(levelname)-8s] %(tag)s %(message)s")
# add formatter to handlers
fh.setFormatter(fmtr_fh)
# add fh to logger
logger.addHandler(fh)
logger.info('Logging started: File ({0})'.format(currlogfile),extra={'tag':'log'})
#
# housekeeping
#
# remove all but the last 10 runs
iStart = len(logfile)+1
iRemTo = runcount-10
# loop through the logdir
for filename in os.listdir(logdir):
if filename.startswith(logfile) and filename.endswith('.log'):
#print filename #(os.path.join(directory, filename))
logCounter = filename[iStart:iStart+iCounterLen]
if int(logCounter) <= iRemTo:
#print os.path.join(logdir, filename)
os.remove(os.path.join(logdir, filename))