-
Notifications
You must be signed in to change notification settings - Fork 0
/
pjindoor.py
2764 lines (2132 loc) · 84.9 KB
/
pjindoor.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
#!/bin/python
# ###############################################################
#
# Imports
#
# ###############################################################
import kivy
kivy.require('1.9.0')
from kivy.app import App
from kivy.adapters.listadapter import ListAdapter
from kivy.clock import Clock, mainthread
from kivy.config import Config, ConfigParser
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.logger import Logger, LoggerHistory
from kivy.network.urlrequest import UrlRequest
from kivy.properties import ListProperty
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.button import Button
#from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.uix.listview import ListView, ListItemLabel
from kivy.uix.popup import Popup
from kivy.uix.settings import Settings, SettingsWithSpinner, SettingsWithSidebar
from kivy.uix.scatter import Scatter
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.widget import Widget
import atexit
import datetime
import errno
import fcntl
import json
import signal
import socket
import StringIO
import subprocess
import time
from threading import Thread
import pjsua as pj
from my_lib import *
from kivy.cache import Cache
Cache._categories['kv.image']['limit'] = 50 # 0
Cache._categories['kv.texture']['limit'] = 50 # 0
###############################################################
#
# Declarations
#
# ###############################################################
config = get_config()
sipRegEvent = None
# ###############################################################
#
# Functions
#
# ###############################################################
@atexit.register
def kill_subprocesses():
"tidy up at exit or break"
global procs, config
repo = ''
try: repo = config.get('service','update_repo')
except: repo = 'production'
if repo == 'development': stop_sw_watchdog()
sendNodeInfo('[***]STOP')
Logger.info('%s: destroy lib at exit' % whoami())
try: pj.Lib.destroy()
except: pass
Logger.info('%s: kill subprocesses at exit' % whoami())
for proc in procs:
try: proc.kill()
except: pass
send_command('pkill -9 omxplayer')
# ###############################################################
#
# Classes
#
# ###############################################################
class MyAccountCallback(pj.AccountCallback):
"Callback to receive events from account"
def __init__(self, account=None):
pj.AccountCallback.__init__(self, account)
# ###############################################################
def on_reg_state(self):
"SIP account registration callback"
global sipRegStatus, sipRegEvent
info = self.account.info()
sipRegStatus = info.reg_status == 200
Logger.info("pjSip on_reg_state: Registration complete, status=%d expires in %d sec"\
% (info.reg_status, info.reg_expires))
Logger.debug("pjSip on_reg_state: account reason=%s oltext=%s active=%d olstatus=%s"\
% (info.reg_reason, info.online_text, info.reg_active, info.online_status))
if sipRegStatus:
sendNodeInfo('[***]SIPREG: REGISTERED')
sendNodeInfo('[***]SIP: FREE')
sipRegStatus = True
else:
sendNodeInfo('[***]SIPREG: ERROR ( %d )' % info.reg_status)
sipRegStatus = False
if sipRegEvent: Clock.unschedule(sipRegEvent)
sipRegEvent = Clock.schedule_once(self.registrationTimerWD, 15 if not sipRegStatus else info.reg_expires + 10)
# ###############################################################
def registrationTimerWD(self, dt):
"SIP registration watch dog"
global sipRegStatus, sipRegEvent, acc, mainLayout
Logger.warning("pjSip registration TO, status=%r" % (not sipRegStatus))
sendNodeInfo('[***]SIP: REG TimeOut')
sipRegStatus = False
Clock.schedule_once(lambda dt: mainLayout.init_myphone(), 1.)
# ###############################################################
def on_incoming_call(self, call):
"Notification on incoming call"
global current_call, mainLayout, docall_button_global, ROTATION, active_display_index
Logger.trace('pjSip %s: DND mode=%d' % (whoami(), mainLayout.dnd_mode))
if current_call or mainLayout.dnd_mode:
call.answer(486, "Busy")
return
if mainLayout.showVideoEvent or mainLayout.popupSettings:
if mainLayout.popupSettings:
mainLayout.popupSettings.dismiss()
mainLayout.popupSettings = None
Window.release_all_keyboards()
if mainLayout.showVideoEvent:
mainLayout.displays[active_display_index].resizePlayer()
Clock.unschedule(mainLayout.showVideoEvent)
mainLayout.showVideoEvent = None
mainLayout.showPlayers()
Logger.info("pjSip %s: Incoming call from %s" % (whoami(), call.info().remote_uri))
current_call = call
docall_button_global.parent.add_widget(mainLayout.btnReject, 2 if ROTATION in [0,180] else 0)
call_cb = MyCallCallback(current_call)
current_call.set_callback(call_cb)
current_call.answer(180)
# ###############################################################
class MyCallCallback(pj.CallCallback):
"Callback to receive events from Call"
sip_call_id_last = '***'
callTimerEvent = None
CALL_TIMEOUT = 60 * 3
RING_TIME = 5.0
# ###############################################################
def __init__(self, call=None):
pj.CallCallback.__init__(self, call)
# ###############################################################
def on_state(self):
"Notification when call state has changed"
global current_call, ring_event, main_state, mainLayout, docall_button_global
ci = self.call.info()
role = 'CALLER' if ci.role == 0 else 'CALLEE'
setloginfo(True, 'Call width=%s is %s (%d) last code=%d (%s) as role=%s'\
% (ci.remote_uri, ci.state_text, ci.state, ci.last_code, ci.last_reason, role))
Logger.info('pjSip on_state: Call width=%s is %s (%d) last code=%d (%s) as role=%s'\
% (ci.remote_uri, ci.state_text, ci.state, ci.last_code, ci.last_reason, role))
Logger.debug('pjSip on_state: sip_call_id=%s outgoing call=%r current call=%s'\
% (ci.sip_call_id, mainLayout.outgoingCall, str(current_call)))
if main_state == ci.state:# and self.sip_call_id_last == ci.sip_call_id:
Logger.warning('pjSip on_state: Call width=%s is %s (%d) last code=%d (%s) as role=%s'\
% (ci.remote_uri, ci.state_text, ci.state, ci.last_code, ci.last_reason, role))
return
prev_state = main_state
main_state = ci.state
if main_state == pj.CallState.EARLY:
mainLayout.findTargetWindow(ci.remote_uri)
if not ring_event and not mainLayout.outgoingCall:
ring_event = Clock.schedule_interval(playWAV, self.RING_TIME)
playWAV(self.RING_TIME)
else:
if ring_event:
Clock.unschedule(ring_event)
ring_event = None
stopWAV()
if self.sip_call_id_last == ci.sip_call_id:
Logger.error('pjSip %s: Unwanted message=%s from %s as %s'\
% (whoami(), ci.state_text, ci.remote_uri, role))
return
if self.callTimerEvent is None:
Clock.unschedule(self.callTimerEvent)
self.callTimerEvent = Clock.schedule_once(self.callTimerWD, self.CALL_TIMEOUT)
if main_state == pj.CallState.INCOMING or main_state == pj.CallState.EARLY:
docall_button_global.imgpath = HANGUP_OUTGOING_CALL_IMG if mainLayout.outgoingCall else ANSWER_CALL_IMG
mainLayout.setButtons(True)
mainLayout.finishScreenTiming()
elif main_state == pj.CallState.DISCONNECTED:
current_call = None
mainLayout.setButtons(False)
docall_button_global.imgpath = DND_CALL_IMG if mainLayout.dnd_mode else MAKE_CALL_IMG
docall_button_global.btntext = ''
mainLayout.startScreenTiming()
mainLayout.del_sliders()
mainLayout.showPlayers()
mainLayout.outgoingCall = False
self.sip_call_id_last = ci.sip_call_id
if not self.callTimerEvent is None:
Clock.unschedule(self.callTimerEvent)
self.callTimerEvent = None
try: docall_button_global.parent.remove_widget(mainLayout.btnReject)
except: pass
## playTone(BUSY_WAV)
sendNodeInfo('[***]SIP: FREE')
elif main_state == pj.CallState.CONFIRMED:
if docall_button_global.imgpath != HANGUP_CALL_IMG:
docall_button_global.imgpath = HANGUP_CALL_IMG
try: docall_button_global.parent.remove_widget(mainLayout.btnReject)
except: pass
Logger.info('pjSip call status: %s' % self.call.dump_status())
sendNodeInfo('[***]SIP: CALL')
elif main_state == pj.CallState.CALLING:
if not current_call is None:
Logger.warning('pjSip bad call: CALLING state %s <<>> %s' %(str(current_call), str(self.call)))
self.call.hangup()
return
## playTone(DIAL_WAV)
current_call = self.call
# docall_button_global.imgpath = ANSWER_CALL_IMG
setcallstat(outflag=(ci.role==0), status=main_state, prev_status=prev_state, call=ci.remote_uri)
if main_state == 6: main_state = 0
# ###############################################################
def on_media_state(self):
"Notification when call's media state has changed"
global mainLayout
if self.call.info().media_state == pj.MediaState.ACTIVE:
# Connect the call to sound device
call_slot = self.call.info().conf_slot
try:
pj.Lib.instance().conf_connect(call_slot, 0)
pj.Lib.instance().conf_connect(0, call_slot)
Logger.debug("pjSip %s: Media is now active" % whoami())
except pj.Error, e:
Logger.error("pjSip %s: Media is inactive due to ERROR: %s" % (whoami(), str(e)))
sendNodeInfo('[***]MEDIA: ERROR')
mainLayout.mediaErrorFlag = True
if check_usb_audio() > 0: mainLayout.reinitbackgroundtasks()
else:
Logger.debug("pjSip %s: Media is inactive" % whoami())
mainLayout.mediaErrorFlag = False
# ###############################################################
def callTimerWD(self, dt):
"SIP call watch dog"
global current_call, ring_event, main_state, mainLayout, acc
Logger.warning('%s:' % whoami())
self.callTimerEvent = None
main_state = pj.CallState.DISCONNECTED
mainLayout.setButtons(False)
docall_button_global.imgpath = DND_CALL_IMG if mainLayout.dnd_mode else MAKE_CALL_IMG
mainLayout.startScreenTiming()
mainLayout.del_sliders()
mainLayout.showPlayers()
mainLayout.outgoingCall = False
sendNodeInfo('[***]SIP: FREE')
if not ring_event is None:
Clock.unschedule(ring_event)
ring_event = None
stopWAV()
if not current_call is None:
try:
if current_call.is_valid(): current_call.hangup()
except:
pass
current_call = None
# ###############################################################
def make_call(uri):
"Function to make outgoing call"
global acc, mainLayout
Logger.info('%s: %s' % (whoami(), uri))
if not mainLayout.outgoing_mode: return None
Logger.info('%s: %s' % (whoami(), uri))
try:
if acc != None: return acc.make_call(uri, cb=MyCallCallback(pj.CallCallback))
except pj.Error, e:
reason = str(e)
Logger.error("pjSip %s exception: %s" % (whoami(), reason))
mainLayout.mediaErrorFlag = True if 'udio' in reason else False
if mainLayout.mediaErrorFlag and check_usb_audio() > 0:
mainLayout.reinitbackgroundtasks()
sendNodeInfo('[***]MEDIA: AUDIO ERROR')
else:
sendNodeInfo('[***]SIP: ERROR')
return None
# ###############################################################
#def log_cb(level, str, len):
# "pjSip logging callback"
# Logger.info('pjSip cb: (%d) %s' % (level, str))
# ##############################################################################
class BasicDisplay:
"basic screen class"
locks = 0 # stav zamkov na dverach
checkEvent = 0 # uloha kontroly stavu videa
def __init__(self,winpos,servaddr,sipcall,streamaddr,relaycmd,rotation=0,aspectratio='fill'):
"display area init"
global scr_mode, mainLayout, procs
self.screenIndex = len(procs)
self.winPosition = winpos.split(',')
self.winPosition = [int(i) for i in self.winPosition]
self.serverAddr = str(servaddr)
self.sipcall = str(sipcall)
self.streamUrl = str(streamaddr)
self.relayCmd = str(relaycmd)
self.playerPosition = [i for i in self.winPosition]
self.rotation = (360 - rotation) % 360
self.aspectratio = aspectratio # 'letterbox | stretch | fill'
self.isPlaying = True
delta = 2
self.playerPosition[0] += delta
self.playerPosition[1] += delta
self.playerPosition[2] -= 2*delta
self.playerPosition[3] -= 2*delta
if aspectratio in ['16:9','4:3']:
### keep aspect ratio:
keepW = False
if rotation in [0,180] and scr_mode in [2]\
or rotation in [90,270] and scr_mode in [1,2]:
keepW = True
pheight = self.playerPosition[3] - self.playerPosition[1] if rotation in [0,180] else self.playerPosition[2] - self.playerPosition[0]
pwidth = self.playerPosition[2] - self.playerPosition[0] if rotation in [0,180] else self.playerPosition[3] - self.playerPosition[1]
pdelta = 0
if keepW: #rotation in [0,180]:
if aspectratio == '16:9':
pdelta = int((pheight - (int(pwidth / 16) * 9)) / 2)
elif aspectratio == '4:3':
pdelta = int((pheight - (int(pwidth / 4) * 3)) / 2)
else:
if aspectratio == '16:9':
pdelta = int((pwidth - (int(pheight / 9) * 16)) / 2)
elif aspectratio == '4:3':
pdelta = int((pwidth - (int(pheight / 3) * 4)) / 2)
if pdelta < 0: pdelta = 0
Logger.info('%s: WxH=%dx%d d=%d %s' % (whoami(), pwidth, pheight, pdelta, aspectratio))
if pdelta > 0:
if rotation in [0,180]:
if keepW:
self.playerPosition[1] += pdelta
self.playerPosition[3] -= pdelta
else:
self.playerPosition[0] += pdelta
self.playerPosition[2] -= pdelta
else:
if not keepW:
self.playerPosition[1] += pdelta
self.playerPosition[3] -= pdelta
else:
self.playerPosition[0] += pdelta
self.playerPosition[2] -= pdelta
self.playerPosition = [str(i) for i in self.playerPosition]
prcs = self.initPlayer()
procs.append(prcs)
sendNodeInfo('[***]VIDEO: %d %s' % (self.screenIndex, 'OK' if prcs else 'ERROR'))
# tt = Thread(target=self.play_worker)
# tt.daemon = True
# tt.start()
self.startThread()
self.color = INACTIVE_DISPLAY_BACKGROUND
if self.rotation in [0,180]:
if scr_mode == 1:
self.actScreen = mainLayout.cameras1.children[0]
elif scr_mode == 2:
self.actScreen = mainLayout.cameras1.children[1] if self.screenIndex == 0 else mainLayout.cameras1.children[0]
elif scr_mode == 3:
self.actScreen = mainLayout.cameras1.children[0] if self.screenIndex == 0 else mainLayout.cameras2.children[0]
else:
self.actScreen = mainLayout.cameras1.children[1] if self.screenIndex == 0 else\
mainLayout.cameras1.children[0] if self.screenIndex == 1 else\
mainLayout.cameras2.children[1] if self.screenIndex == 2 else\
mainLayout.cameras2.children[0]
else:
cnt = len(mainLayout.cameras.children) - 1
self.actScreen = mainLayout.cameras.children[cnt - self.screenIndex]
self.printInfo()
self.setActive(False)
# ###############################################################
"""
def play_worker(self):
"Player thread"
global procs
_prcs = procs[self.screenIndex]
Logger.debug('%s: (%d) %r' % (whoami(), self.screenIndex, _prcs))
while True:
"" "
myLine = _prcs.stdout.readline()
if myLine:
Logger.info('%s: (%d) %s' % (whoami(), self.screenIndex, myLine))
# else:
# self.dbus_command(['status'])
# break
"" "
try:
(res,err) = _prcs.communicate()
Logger.info('%s: (%d) %s (%s)' % (whoami(), self.screenIndex, str(res), str(err)))
except:
Logger.error('%s: (%d) FIN!' % (whoami(), self.screenIndex))
self.dbus_command(['status'])
break
# time.sleep(.1)
"""
# ###############################################################
def startThread(self):
"start communication thread to external devicer"
Logger.debug('%s: (%d)' % (whoami(), self.screenIndex))
self.locks = 0x55
sendNodeInfo('[***]LOCK: %d %.2x' % (self.screenIndex, self.locks))
self.socket = None
if len(self.serverAddr):
self.bgrThread = Thread(target=self.tcpip_worker, kwargs={'addr': self.serverAddr})
self.bgrThread.daemon = True
self.bgrThread.start()
else:
self.bgrThread = None
# ###############################################################
def initPlayer(self):
"start video player"
global mainLayout, current_call, active_display_index
Logger.debug('%s: (%d)' % (whoami(), self.screenIndex))
dbn = DBUS_PLAYERNAME + str(self.screenIndex)
try:
if len(itools.omxl) and dbn in itools.omxl:
itools.omxl[dbn] = None
# del itools.omxl[dbn]
except:
pass
# sendNodeInfo('[***]VIDEO: %d ERROR' % self.screenIndex)
interval = 60.# + .2 * self.screenIndex
if self.checkEvent: Clock.unschedule(self.checkEvent)
self.checkEvent = Clock.schedule_interval(self.checkLoop, interval)
self.isPlaying = (mainLayout.scrmngr.current == CAMERA_SCR and not mainLayout.popupSettings and not current_call) or\
(current_call and active_display_index == self.screenIndex)
return subprocess.Popen(['omxplayer', '--live', '--no-osd', '--no-keys',\
'--alpha','0', '--layer','1', '--display','0',\
'--dbus_name',dbn, '--orientation',str(self.rotation),\
'--aspect-mode',self.aspectratio, '--win',','.join(self.playerPosition), self.streamUrl],\
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
# ###############################################################
def checkLoop(self, dt):
"check video player state"
global mainLayout #, current_call, active_display_index
dbn = DBUS_PLAYERNAME + str(self.screenIndex)
status = get_info('%s %s status' % (DBUSCONTROL_SCRIPT, dbn)).split('\n')
try: pos = int(status[1].split(' ')[1]) # check if position > 0
except: pos = 0
try: paused = str(status[2].split(' ')[1]).lower() != 'false' # check if paused == false
except: paused = True
if pos < 0 or paused:
sendNodeInfo('[***]VIDEO: %d ERROR' % (self.screenIndex))
Logger.warning('%s: (%d): %r' % (whoami(), self.screenIndex, status))
mainLayout.restart_player_window(self.screenIndex)
else:
sendNodeInfo('[***]VIDEO: %d OK' % self.screenIndex)
val = 255 if self.isPlaying else 0
self.dbus_command(TRANSPARENCY_VIDEO_CMD + [str(val)])
if self.bgrThread and not self.bgrThread.isAlive(): self.startThread()
# ###############################################################
def resizePlayer(self, newpos=''):
"resize video player area"
global mainLayout, scr_mode
Logger.debug('%s: (%d) %s' % (whoami(), self.screenIndex, newpos))
self.hidePlayer()
pos = []
pos = newpos.split(',') if len(newpos) else self.playerPosition
if len(newpos) > 0:
pos = [80,16,720,376] if self.rotation == 0 else [80,104,720,464] if self.rotation == 180\
else [352,8,700,472] if self.rotation == 90 else [100,8,448,472]
if self.aspectratio in ['16:9','4:3']:
### keep aspect ratio:
pheight = pos[3] - pos[1] if self.rotation in [0,180] else pos[2] - pos[0]
pwidth = pos[2] - pos[0] if self.rotation in [0,180] else pos[3] - pos[1]
if self.aspectratio == '16:9':
pdelta = int((pwidth - (int(pheight / 9) * 16)) / 2)
elif self.aspectratio == '4:3':
pdelta = int((pwidth - (int(pheight / 3) * 4)) / 2)
else: pdelta = 0
if pdelta < 0: pdelta = 0
if self.rotation in [0,180]:
pos[0] += pdelta
pos[2] -= pdelta
else:
pos[1] += pdelta
pos[3] -= pdelta
self.dbus_command(['setvideopos'] + pos)
# ###############################################################
def tcpip_worker(self, addr):
"TCPIP thread"
Logger.debug('%s: (%d) %s' % (whoami(), self.screenIndex, addr))
SERVER_REQ = 'GET /events.txt HTTP/1.1\n\n'
if ':' in addr:
b = addr.split(':')
a = (b[0],int(b[1]))
else:
a = (addr, 80)
while True:
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect(a)
time.sleep(1)
fcntl.fcntl(self.socket, fcntl.F_SETFL, os.O_NONBLOCK)
time.sleep(1)
self.socket.send(SERVER_REQ)
break
except IOError as e:
self.socket = None
Logger.warning('%s: (%d) %s CONNECT ERROR %s' % (whoami(), self.screenIndex, addr, str(e)))
#return
time.sleep(60)
msg = ''
noDataCounter = 0
while True:
try:
msg = self.socket.recv(4096) if not self.socket is None else ''
except socket.error as e: ###???
# except exception as e:
err = e.args[0]
if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
time.sleep(1) # No data available
noDataCounter += 1
if noDataCounter > 40: break # try reconnect
continue
else:
# a "real" error occurred
self.socket = None
Logger.warning('%s: (%d) %s ERROR: %s' % (whoami(), self.screenIndex, addr, str(e)))
msg = ''
break
except:
self.socket = None
if len(msg) > 0:
# got a message, do something
noDataCounter = 0
if '[' in msg and ']' in msg:
m = msg.splitlines() # split to separate lines
l = m[m.index('') + 1:] # skip over header part
# Logger.info('%s: (%d) %s' % (whoami(), self.screenIndex, str(l)))
self.processMessage(l)
else:
Logger.warning('%s: (%d) Reinit connection: %s' % (whoami(), self.screenIndex, addr))
try:
self.socket.close()
except: pass
self.socket = None
try:
time.sleep(5)
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect(a)
time.sleep(1)
fcntl.fcntl(self.socket, fcntl.F_SETFL, os.O_NONBLOCK)
time.sleep(1)
self.socket.send(SERVER_REQ)
except:
self.socket = None
time.sleep(15)
# ###############################################################
def processMessage(self, msg):
"process the message from the thread"
Logger.debug('%s: (%d)' % (whoami(), self.screenIndex))
cp = ConfigParser()
tmsg = []
for m in msg:
if '' == m or '[' in m or ('=' in m and not ';' in m): tmsg.append(m)
while len(tmsg):
msg = tmsg[:tmsg.index('') + 1]
s_config = '\n'.join(str(x) for x in msg)
#Logger.warning('%s: (%d) s_config=%s' % (whoami(), self.screenIndex, s_config))
tmsg = tmsg[tmsg.index('') + 1:]
buf = StringIO.StringIO(s_config)
cp.readfp(buf)
for sec_name in cp.sections():
#opt = cp.options(sec_name)
#for n,v in cp.items(sec_name):
#Logger.info('%s: (%d) section=%s n=%s v=%s' % (whoami(), self.screenIndex, sec_name, n, v))
if sec_name in ['evstat', 'event']:
x = cp.get(sec_name,'event')
if 'GUARD' in x: self.setLock(cp.get(sec_name,'message'))
#if 'event' == sec_name: pass
# ###############################################################
def setLock(self, value):
"set lock status"
global mainLayout
if not 'S' in value: return
m = value.strip('"').split('S')
mask = 0xf if int(m[0]) > 1 else 0xf0
val = 0xf if int(m[1]) == 1 else 0
if int(m[0]) > 1: val = val << 4
self.locks = (self.locks & mask) | val
Logger.debug('%s: (%d) lock=%.2x (%s m=%.2x v=%.2x)'\
% (whoami(), self.screenIndex, self.locks, value, mask, val))
sendNodeInfo('[***]LOCK: %d %.2x' % (self.screenIndex, self.locks))
mainLayout.setLockIcons(self.screenIndex, self.locks)
# Clock.schedule_once(mainLayout.image_update_loop, .5)
# ###############################################################
def dbus_command(self, params=[]):
"d-bus command"
global mainLayout
Logger.trace('%s: (%d) %r' % (whoami(), self.screenIndex, params))
if not send_dbus(DBUS_PLAYERNAME + str(self.screenIndex), params):
sendNodeInfo('[***]VIDEO: %d ERROR' % self.screenIndex)
mainLayout.restart_player_window(self.screenIndex)
# ###############################################################
def hidePlayer(self):
"hide video player area"
Logger.debug('%s:' % whoami())
self.color = [0,0,0] #NO_DISPLAY_BACKGROUND # INACTIVE_DISPLAY_BACKGROUND
self.actScreen.bgcolor = self.color
# ###############################################################
def setActive(self, active=True):
"add or remove active flag"
global current_call, scr_mode, mainLayout, docall_button_global
Logger.debug('%s: index=%d active=%d' % (whoami(), self.screenIndex, active))
# if current_call: return
self.color = ACTIVE_DISPLAY_BACKGROUND if active and (scr_mode != 1) else INACTIVE_DISPLAY_BACKGROUND
self.actScreen.bgcolor = self.color
if current_call: return
if active:
# change phone icon
docall_button_global.imgpath = DND_CALL_IMG if mainLayout.dnd_mode else MAKE_CALL_IMG
docall_button_global.imgpath = docall_button_global.imgpath if len(self.sipcall) else UNUSED_CALL_IMG
# ###############################################################
def printInfo(self):
"print class info"
Logger.debug('Display: id=%d area=%s IP=%s SIPcall=%s stream=%s'\
% (self.screenIndex, self.playerPosition, self.serverAddr, self.sipcall, self.streamUrl))
# ##############################################################################
class Indoor(FloatLayout):
lib = None # pjsip library
outgoingCall = False
dnd_mode = False
outgoing_mode = True
avolume = 100
micvolume = 100
brightness = 255
appRestartEvent = None
mediaErrorFlag = False # audio error
popupSettings = None # popup window is opened
volslider = None
micslider = None
masterPwd = '1234'
scrOrientation = 0
btnReject = None
btnDoCall = None
btnScrSaver = None
btnSettings = None
btnDoor1 = None
btnDoor2 = None
camerascreen = None
txtBasicLabel = None
workAreaHigh = 0
buttonAreaHigh = 0
infoAreaHigh = 0
sipPort = 5060
touches = {} # resize video player (to bigger)
touchdistance = -1. # touch distance
refreshIconEvent = None # timer to refresh icons
showVideoEvent = None # timer to return size back
netstatus = -1 # old value of NetLink.netstatus
reinitCntr = 0 # reinitialization counter
def __init__(self, **kwargs):
"app init"
global APP_NAME, APP_VERSION_CODE, SCREEN_SAVER, ROTATION, WATCHES, RING_TONE
global main_state, mainLayout, scrmngr, config, scr_mode
super(Indoor, self).__init__(**kwargs)
mainLayout = self
initloggers()
init_sw_watchdog()
sw_watchdog()
Clock.schedule_interval(sw_watchdog, SW_WD_TIME)
Clock.schedule_once(lambda dt: self.settings_worker(), 7.5)
self.loseNextTouch = False
self.displays = []
self.screenTimerEvent = None
main_state = 0
self.info_state = 0
self.myprocess = None
self.scrmngr = self.ids._screen_manager
scrmngr = self.scrmngr
self.sipServerAddr = ''
# nacitanie konfiguracie
try:
APP_NAME = config.get('about', 'app_name')
except:
Logger.warning('Indoor init: ERROR 3 = read config file!')
watches.APP_LABEL = APP_NAME
try:
if config.get('about', 'app_ver') != APP_VERSION_CODE:
config.set('about', 'app_ver', APP_VERSION_CODE)
config.write()
except:
Logger.warning('Indoor init: ERROR 3.1 = read config file!')
try:
value = config.get('command', 'watches').strip()
if value == 'analog' or value == 'digital': WATCHES = value
else: WATCHES = 'none'
except:
Logger.warning('Indoor init: ERROR 4 = read config file!')
scr_mode = 1
try:
scr_mode = config.getint('gui', 'screen_mode')
except:
Logger.warning('Indoor init_screen: ERROR 9 = read config file!')
scr_mode = 1
try:
screen_saver = config.getint('command', 'screen_saver')
if screen_saver > 0 and screen_saver < 120: SCREEN_SAVER = screen_saver * 60
except:
Logger.warning('Indoor init: ERROR 5 = read config file!')
try:
value = config.get('command', 'dnd_mode').strip()
self.dnd_mode = 'True' == value or '1' == value
except:
Logger.warning('Indoor init: ERROR 6 = read config file!')
try:
value = config.get('service', 'autoupdate').strip()
if 'True' == value or '1' == value:
Clock.schedule_interval(self.auto_update_loop, 3600)
except:
Logger.warning('Indoor init: ERROR 6.2 = read config file!')
try:
value = config.get('gui', 'outgoing_calls').strip()
self.outgoing_mode = 'True' == value or '1' == value
except:
Logger.warning('Indoor init: ERROR 6.1 = read config file!')
try:
br = config.getint('command', 'brightness')
if br > 0 and br < 256: self.brightness = br
except:
Logger.warning('Indoor init: ERROR 7 = read config file!')
self.brightness = 255
send_command('%s %d' % (BRIGHTNESS_SCRIPT, self.brightness))
try:
RING_TONE = config.get('devices', 'ringtone').strip()
except:
Logger.warning('Indoor init: ERROR 11 = read config file!')
RING_TONE = 'oldphone.wav'
tones.PHONERING_PLAYER = APLAYER + ' ' + APARAMS + RING_TONE
try:
self.masterPwd = config.get('service', 'masterpwd').strip()
except:
Logger.warning('Indoor init: ERROR 8 = read config file!')
self.masterPwd = '1234'
try:
self.scrOrientation = config.getint('gui', 'screen_orientation')
except:
Logger.warning('Indoor init: ERROR 8.1 = read config file!')
ROTATION = self.scrOrientation
self.get_volume_value()
initcallstat()
sendNodeInfo('[***]START')
# self.init_myphone()
# self.init_widgets()
Clock.schedule_once(lambda dt: self.init_myphone(), 3.1)
Clock.schedule_once(lambda dt: self.init_widgets(), 3.9)
self.infinite_event = Clock.schedule_interval(self.infinite_loop, 6.9)
Clock.schedule_interval(self.info_state_loop, 12.)
Clock.schedule_once(self.checkNetStatus, 5.)
Clock.schedule_once(lambda dt: send_command('./diag.sh init'), 15)
t = threading.Thread(target=procNetlink)
t.daemon = True
t.start()
# ###############################################################
def init_widgets(self):
"define app widgets"
global scr_mode, ROTATION
screensize = (800,480) if ROTATION in [0,180] else (480,800)
Logger.debug('%s: scr_mode=%d rotation=%d screensize=%r' % (whoami(), scr_mode, ROTATION, screensize))
self.ids.waitscr.size = screensize
self.ids.digiclock.size = screensize
self.ids.camera.size = screensize
self.ids.settings.size = screensize
self.camerascreen = self.ids.scattercameras
self.camerascreen.size = screensize
ROTATION = self.scrOrientation
h3 = 56 if ROTATION in [0,180] else 64 # info area
h2 = 47 if ROTATION in [0,180] else 94 # buttons
h1 = screensize[0] - h3 - h2 # cameras
self.workAreaHigh = h1
self.buttonAreaHigh = h2
self.infoAreaHigh = h3
self.workArea = MBoxLayout(orientation='horizontal')
self.infoArea = MBoxLayout(orientation='horizontal', size_hint_y=None, height=self.infoAreaHigh)
self.btnArea = MBoxLayout(orientation='vertical', size_hint_y=None, height=self.buttonAreaHigh)
self.camerascreen.add_widget(self.workArea)
self.camerascreen.add_widget(self.infoArea)
self.camerascreen.add_widget(self.btnArea)
self.init_buttons()
self.init_screen()
## self.init_sliders()
# ###############################################################
def init_buttons(self):