-
Notifications
You must be signed in to change notification settings - Fork 5
/
hpe-rc.py
2035 lines (1866 loc) · 73.7 KB
/
hpe-rc.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/env python
#
# Copyright (c) 2013 Joseph W. Metcalf
#
# Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby
# granted, provided that the above copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
# DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE
# USE OR PERFORMANCE OF THIS SOFTWARE.
#
# This product contains Uniden proprietary and/or copyrighted information. Used under license.
import sys, io, os
import string
import ConfigParser
import argparse
import urlparse
import time, datetime
import serial
import logging
import array
import struct
import cmd
import json
import wave
import hashlib
import threading
import Queue
import util
import defs
PROMPT = 'Not Connected'
UNIDEN = 'This product contains Uniden proprietary and/or copyrighted information. \nUsed under license.\n'
OK_VAR = ['port1','port2','port1_baud','port2_baud','loglevel','log_file','log_path','rd_input','rd_filter','rd_level','rd_sample','rd_threshold','rd_freq','rd_mode','rd_att','rd_rectime','rd_timeout','rd_file','rd_path','dateformat','mon_cmd','mon_file','mon_expire','mon_format','mon_path','cfg_path','feed_loop','feed_path','feed_delay','web_host','web_port','web_readonly','web_ip','web_browser','web_check','cmd','ajax_refresh']
INT_VAR = ['loglevel','port1_baud','port2_baud','rd_sample','rd_threshold','rd_timeout','rd_rectime','rd_level','feed_delay','mon_expire','web_port','web_check','update_check','ajax_refresh']
OOO_VAR = ['rd_att', 'log_file', 'rd_file', 'mon_file','mon_cmd','feed_loop','rd_scan','rd_filter','web','web_readonly','web_browser']
DIR_VAR = ['rd_path','feed_path','log_path','mon_path','cfg_path']
MOD_VAR = ['rd_mode']
FRQ_VAR = ['rd_freq']
LIST_VAR = ['web_ip']
OPEN_CMD = ['volume','scan','raw','dump','mute','close','cap','att','record','squelch','replay','status','feed','monitor','hold','avoid','next','prev', 'program', 'debug']
SUB_DICT = {'space': ' ','program': defs.PROGRAM}
REPLAY_STATUS = {'tgid' : 3, 'frequency' : 3, 'mode' : 0, 'att' : 0, 'subtone' : 4, 'nac' : 5, 'service_tag': 6, 'system' : 7,
'department' : 8, 'channel' : 9, 'squelch' : 0, 'mute' : 0, 'signal' :0, 'favorites_list' :10,
'uid' : 11, 'system_avoid' : 0, 'department_avoid' : 0, 'channel_avoid' : 0, 'status' : 0, 'service_name' : 0,
'subtone_string' : 0, 'replay_status' : 2}
SCAN_STATUS = {'tgid' : 2, 'frequency' : 2, 'mode' : 3, 'att' : 4, 'subtone' : 5, 'nac' : 6, 'service_tag': 7, 'system' : 8,
'department' : 9, 'channel' : 10, 'squelch' : 11, 'mute' : 12, 'signal' :13, 'favorites_list' :14,
'uid' : 15, 'system_avoid' : 16, 'department_avoid' : 17, 'channel_avoid' : 18, 'status' : 0, 'service_name' : 0,
'subtone_string' : 0, 'replay_status' : 0}
WAV_HEADER = {'IART\x40\x00\x00\x00': 8, 'IGNR\x40\x00\x00\x00' : 9, 'INAM\x40\x00\x00\x00' : 10, 'ICMT\x40\x00\x00\x00' : 2, 'ISBJ\x40\x00\x00\x00' : 14, 'ISRC\x10\x00\x00\x00' : 5, 'IKEY\x14\x00\x00\x00' : 7, 'ITCH\x40\x00\x00\x00' : 15}
AUTO_PORT = {'Windows' : ['COM1','COM2','COM3','COM4','COM5','COM6','COM7','COM8','COM9'],
'Linux' : ['/dev/ttyACM0','/dev/ttyACM1','/dev/ttyUSB0','/dev/ttyUSB1','/dev/ttyUSB2','/dev/ttyS0','/dev/ttyS1','/dev/ttyS2']
}
DUMP_FMT = {'hex' : '{0:02X}', 'bin' : '{0:08b}', 'text' : '{c}' }
COMMON_SYSTEM = ['channel','department','system']
ALT_SYSTEM = ['frequency', 'department','system']
INFO_SYSTEM = ['subtone']
COMPARE_SYSTEM = ['status','channel','channel_hold','channel_avoid','department','department_hold','department_avoid','system','system_hold','system_avoid']
HASH_ITEMS=['frequency','channel','channel_hold','channel_avoid','department','department_hold','department_avoid','system','system_hold','system_avoid','signal','uid','status','replay_status']
queue=Queue.Queue()
def ok():
print 'Ok.'
def idle(base=0.1):
time.sleep(base)
def r2r(ser, timeout=0, flush=False):
global serin
serial_lock = threading.Lock()
serial_lock.acquire()
if flush:
serin=''
ser.flush()
start_time=int(time.time())
rs=None
while rs==None:
if ser.inWaiting():
serin += ser.read(ser.inWaiting())
if chr(0x0d) in serin:
linein, sep, serin=serin.partition(chr(0x0d))
rs = response(linein)
else: # ADDED - REDUCES CPU BY 100X
idle(); # Thanks, Mark P.
if timeout != 0:
check_time=int(time.time())
if (check_time - start_time) >= timeout:
rs='\x00'
serial_lock.release()
return rs
def flush(ser):
rs=r2r(ser, timeout=1, flush=True)
CLEANUP = {'channel': 'TGID : ','tgid' : 'TGID : ', 'frequency' : 'TGID : ', 'uid' : 'UID : ', 'uid' :'UID:'}
def system_cleanup(system):
for key in CLEANUP:
if system[key]:
check=system[key].find(CLEANUP[key])
if check != -1:
system[key]=str(system[key][len(CLEANUP[key]):])
return system
def hash_system(system):
md = hashlib.md5()
for item in HASH_ITEMS:
md.update(system.get(item, item) or item)
return str(md.hexdigest())
def build_status(list, mapping, **kwargs):
"""Interpret list using dictionary map"""
global last_system
system = {}
if list:
for key in mapping:
if mapping[key]!=0:
try:
system[key] = bool(list[mapping[key]]) and list[mapping[key]].strip() or None
except:
system[key] = None
else:
system[key] = None
for key, value in kwargs.iteritems():
system[key] = value
system['time']=str(int(time.time()))
try:
system['service_name'] = defs.SERVICE_TYPES[system['service_tag']] or None
except KeyError:
system['service_name'] = None
system['subtone_string'] = subtone(system['subtone'])
system['sub_uid'] = sub_uid(system['subtone'], system['uid'])
system.update(prefix_dict(prefix='hp'))
if (system['squelch']=='1') and (system['mute']=='0'):
system['status']='Receiving'
elif system.get('replay_status', None)!=None:
if system['replay_status']=='STOP':
system['status']='Replay Stop'
else:
system['status']='Replay Mode'
elif system.get('feed', None)!=None:
system['status']='Downloading'
else:
system['status']='Scanning'
for item in ['channel','department','system']:
cmdtype=''.join([item[0].upper(),'HOLD'])
status=HP_cmd_on_off(ser1, '', type=cmdtype, display=False)
system[''.join([item,'_','hold'])] = digit_switch(status)
else:
for key in mapping:
system[key] = None
system['status']='Busy'
system['hash'] = hash_system(system)
return system_cleanup(system)
def arg_dict(instr):
try:
return dict(arg.split('=', 1) for arg in instr.split(' '))
except:
logging.error('Invalid Parameter List')
return []
def path_safe(instr):
valid_chars = '-_.() abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
return ''.join(x if x in valid_chars else '-' for x in instr )
def var_sub(instr, subs={}):
asubs = {}
asubs.update(subs)
asubs.update(SUB_DICT)
try:
asubs.update({'date':fn_dt(datetime.datetime.now(), config['dateformat'])})
asubs.update({'config_name': config['config_name']})
except:
pass
for key, value in asubs.items():
instr = instr.replace('%%(%s)%%' % key, value and path_safe(value) or '')
return instr
def fn_dt(dt, format='%Y-%m-%d_%H-%M-%S'):
"""Return formated datetime for filenames"""
return dt.strftime(format)
def fn_cuf(dt, format='%Y-%m-%d_%H-%M-%S'):
"""Convert Uniden-style filename to datetime format"""
return datetime.datetime.strptime(dt, format)
def set_config(key,value,verbose=True):
step = None
none = False
if value==None:
config[key] = value
elif key in FRQ_VAR:
if '.' in value:
try:
step=int(float(value)*1000000)
except:
logging.error(' '.join(['Invalid Frequency:', key]))
else:
try:
step=int(value)
except:
logging.error(' '.join(['Invalid Frequency:',key]))
if step:
if not (25000000 <= step <= 960000000):
logging.error(' '.join(['Frequency Out of Range:', key]))
step=None
elif key in INT_VAR:
try:
step = int(value)
except:
logging.error(' '.join(['Integer Required:',key]))
elif key in OOO_VAR:
if value.upper() in ['ON','OFF']:
step = value.upper()
else:
logging.error(' '.join(['Select ON or OFF:', key]))
elif key in MOD_VAR:
if value.upper() in ['AUTO','AM','FM','NFM']:
step = value.upper()
else:
logging.error(' '.join(['Select AUTO, AM, FM or NFM:', key]))
elif key in DIR_VAR:
try:
step = os.path.abspath(os.path.expanduser(var_sub(value, {'space' : ' '})))
except:
step = None
logging.error(' '.join(['Invalid Directory:', key]))
elif key in LIST_VAR:
if value=='':
step=None
none=True
else:
try:
step = value.strip().split(',')
except:
step = None
logging.error(' '.join(['Comma-Separated List Required:',key]))
else:
if value.capitalize()=='None':
step = None
none = True
else:
step = value
if step or none:
config[key]=step
if verbose:
print ' '.join(['Ok:',key,'=',str(step)])
if key=='loglevel':
logging.getLogger().setLevel(int(config['loglevel']))
if key=='web':
if config['web']=='ON':
web_server(command='start',port=config['web_port'])
else:
web_server(command='stop')
if key=='cmd':
HP_CMD().onecmd(value)
def build_favorites(set=None):
HP_program_mode(ser1, enter=True, display=False)
if set:
for key in favorites:
if key in set:
HP_fav_list(ser1,' '.join([key, 'ON']))
else:
HP_fav_list(ser1,' '.join([key, 'OFF']))
HP_fav_list(ser1, '', display=False)
HP_program_mode(ser1, enter=False, display=False)
HP_cmd_on_off(ser1,status='OFF', type='CHOLD', display=False)
def build_globals():
r_dict = {}
r_dict['g_record']=digit_switch(HP_cmd_on_off(ser1, '', type='REC', display=False))
r_dict['g_mute']=digit_switch(HP_cmd_on_off(ser1, '', type='MUTE', display=False))
r_dict['g_att']=digit_switch(HP_cmd_on_off(ser1, '', type='GATT', display=False))
return r_dict
def build_volsql():
r_dict = {}
r_dict['VOL']=int(HP_cmd_0_15(ser1, val='', type='VOL', display=False))
r_dict['SQL']=int(HP_cmd_0_15(ser1, val='', type='SQL', display=False))
return r_dict
def prefix_dict(prefix='ajax'):
global config
keylist=[]
for k in config.keys():
if k.startswith(''.join([prefix,'_'])):
keylist.append(k)
return dict((k, config[k]) for k in keylist)
def web_app(environ, start_response):
import mimetypes
global last_system
global config
global globals
global volsql
ajax_parameters=prefix_dict()
JSONMAP = {'ajax/monitor': last_system, '/ajax/system' : last_system, 'ajax/config' : config, 'ajax/favorites' : favorites,
'ajax/parameters': ajax_parameters, 'ajax/globals' : globals, 'ajax/volsql': volsql, 'ajax/test' : defs.TEST_DATA}
COMMANDMAP = {'command/quit':'quit','command/feed':'FEED','command/scan':'SCAN', 'command/replay' : 'REPLAY', 'command/cnext' : 'CNEXT', 'command/dnext': 'DNEXT',
'command/snext':'SNEXT','command/cprev' : 'CPREV', 'command/dprev': 'DPREV','command/sprev':'SPREV', 'command/cap' : 'CAP',
'toggle/mute':'MUTE', 'toggle/gatt':'GATT','toggle/record':'REC','toggle/chold':'CHOLD', 'toggle/dhold':'DHOLD',
'toggle/shold':'SHOLD', 'toggle/cavoid':'CAVOID', 'toggle/davoid':'DAVOID', 'toggle/savoid':'SAVOID',
'rep/next' : 'NEXT', 'rep/prev' : 'PREV', 'rep/pause' : 'PAUSE', 'rep/resume' : 'RESUME',
}
STARTMAP = {'start/monitor' : 'monitor', 'start/feed' : 'feed', 'kill' : 'kill'}
UDMAP = {'+/vol':'VOL','-/vol':'VOL','+/sql':'SQL','-/sql':'SQL'}
FILEMAP = {'feeds.html','monitor.html'}
PATHMAP = {'feeds' : config['feed_path'], 'monitor' : config['mon_path']}
POSTMAP = {'post/config' : 'config' , 'post/favorites': 'favorites'}
REDIRECT = {'jquery.js': 'jquery-1.10.2.min.js', '' : 'hpe-rc.html'}
FILES = {'hpe-rc.html' : None, 'base.css' : None, 'base.js' : None, 'HPe-rc64.png': None, 'hpe-rc.css' : None,
'hpe-rc.js' : None, 'jquery-1.10.2.min.js': None, 'jquery-1.8.2.min.js': None, 'favicon.ico' : None ,'config.html': None ,'favorites.html': None,
'feeds.html' : 'files.html', 'monitor.html': 'files.html'}
response=None
request_path=environ.get('PATH_INFO', '').lstrip('/')
request_hash=environ.get('HTTP_IF_NONE_MATCH', None)
request_ip=environ.get('REMOTE_ADDR', None)
request_method=environ.get('REQUEST_METHOD', None)
headers = []
if config['web_ip'] and request_ip not in config['web_ip']:
headers = [('Content-type', 'text/plain')]
status = '403 Forbidden'
response=status
start_response(status, headers)
return [response]
status = '200 OK'
for key, value in JSONMAP.items():
if (request_path==key) and value:
headers = [('Content-type', 'application/json')]
current_hash=value.get('hash', None)
if current_hash:
headers.append(('Etag',str(current_hash)))
if (request_hash==current_hash) and request_hash!=None:
status='304 Not Modified'
response=''
else:
status = '200 OK'
if key != 'ajax/favorites':
value['version'] = version_string()
headers.append(('Access-Control-Allow-Origin','*'))
headers.append(('Expires','-1'))
response=json.dumps(value)
if response==None:
try:
command=request_path.split('/',1)[0]
except:
command=None
for key, value in STARTMAP.items():
if (request_path==key) and value:
queue.put({'type': command,'command':value})
response=''
for key, value in COMMANDMAP.items():
if (request_path==key) and value:
if config['web_readonly']=='OFF':
queue.put({'type': command,'command':value})
response=''
for key, value in UDMAP.items():
if (request_path==key) and value:
if config['web_readonly']=='OFF':
queue.put({'type': request_path[0],'command':value})
response=''
if response==None and request_method=='POST':
for key, value in POSTMAP.items():
if request_path==key:
request_body_size = int(environ.get('CONTENT_LENGTH', 0))
request_body = environ['wsgi.input'].read(request_body_size)
if config['web_readonly']=='OFF':
queue.put({'type': command,'command':value, 'data':request_body})
status = '302 Found'
headers = [('Content-type', 'text/html'), ('Location', ''.join(['/',value,'.html']))]
response=''
if response==None:
for key, value in PATHMAP.items():
if request_path==key:
filenames = os.listdir(value)
filelist=[filename for filename in filenames]
response=json.dumps(filelist)
headers = [('Content-type', 'application/json')]
split=request_path.rpartition('/')
if split[0]==key:
response = open(''.join([value,'/',split[2]]), 'rb').read()
status = '200 OK'
headers = [('Content-type', mimetypes.guess_type(request_path)[0] or 'text/html')]
if response==None:
for request, source in FILES.items():
if request_path==request:
response = open(''.join(['web',os.sep,source or request_path]), 'rb').read()
status = '200 OK'
headers = [('Content-type', mimetypes.guess_type(source or request_path)[0] or 'text/html')]
if response=='':
headers = [('Content-type', 'text/html')]
status = '204 No Content'
if response==None:
for request, redirect in REDIRECT.items():
if request_path==request:
status = '302 Found'
headers = [('Content-type', 'text/html'), ('Location', ''.join(['/',redirect]))]
response=''
if response==None:
status = '404 Not Found'
headers = [('Content-type', 'text/html')]
response=status
headers.append(('Content-Length',str(len(response))))
start_response(status, headers)
return [response]
def web_server(command='start', port=8000):
import wsgiref.simple_server
global httpd
class MyWSGIRequestHandler(wsgiref.simple_server.WSGIRequestHandler):
def address_string(self): # Disable rDNS lookup on every request. Thanks, Andy!
return self.client_address[0]
class LogDevice():
def write(self, s):
logging.debug(s)
sys.stderr = LogDevice()
class server_thread(threading.Thread):
def run(self):
print
print 'Starting Web Server...'
try:
httpd.serve_forever(poll_interval=0.5)
except Exception as detail:
logging.error(' '.join(['Web Server can not be started:',detail]))
httpd.socket.close()
if httpd and command=='stop':
print
print 'Stopping Web Server...'
print
threading.Thread(target=httpd.shutdown).start()
httpd=None
if command=='start':
if not httpd:
httpd = wsgiref.simple_server.make_server(config['web_host'], config['web_port'], web_app, handler_class=MyWSGIRequestHandler)
server_thread().start()
else:
logging.warning('Web Server already started.')
class HP_PROGRAM(cmd.Cmd):
global config, ser1, ser2
prompt = ''.join(['Program Mode','> '])
intro = '\n'
doc_header = 'Available Commands'
misc_header = 'Additional Topics'
undoc_header = 'Other Commands'
ruler = '-'
def emptyline(self):
pass
def postcmd(self, stop, line):
print
return cmd.Cmd.postcmd(self, stop, line)
def precmd(self, line):
print
return cmd.Cmd.precmd(self, line)
def help_help(self):
print 'Type help [topic] for more information on commands and operation.'
def do_exit(self,line):
"""exit
Exit programming mode."""
HP_program_mode(ser1, enter=False)
HP_cmd_on_off(ser1,status='OFF', type='CHOLD') #HP-1 bug - Channel Hold set after program mode
return True
def do_favorites(self, line):
"""favorites [0-256] [ON|OFF]
Turn favorites lists on or off. Use this command without options
to display defined favorites lists."""
HP_fav_list(ser1, line)
class HP_DEBUG(cmd.Cmd):
global config, ser1, ser2
prompt = ''.join(['Debug Mode','> '])
intro = 'WARNING: Use these commands with caution!\nYou may have to restart/reconnect your scanner to return to normal operation.\n'
doc_header = 'Available Commands'
misc_header = 'Additional Topics'
undoc_header = 'Other Commands'
ruler = '-'
def emptyline(self):
pass
def postcmd(self, stop, line):
print
return cmd.Cmd.postcmd(self, stop, line)
def precmd(self, line):
print
return cmd.Cmd.precmd(self, line)
def help_help(self):
print 'Type help [topic] for more information on commands and operation.'
def do_exit(self,line):
"""exit
Exit debug mode."""
return True
def do_cmd(self, line):
"""cmd
Send formatted command string to scanner."""
HP_any_cmd(ser1, line)
def do_send(self, line):
"""send
Send string to scanner and read response."""
ser1.write(line)
ser1.write('\r')
rs=r2r(ser1)
logging.info(rs)
def do_checksum(self, status):
"""checksum [ON|OFF]
Turn HP-1 command checksums ON or OFF."""
HP_checksum(ser1, status)
def do_debugmode(self,line):
"""debugmode
Start HP-1 debug mode. Reset scanner to return to normal operation."""
ser1.write('\t'.join(['cdb','2']))
ser1.write('\r')
rs=r2r(ser1)
print rs
while True:
try:
rs=r2r(ser1)
print rs[0]
except KeyboardInterrupt:
print
ser1.flushInput()
ser1.write('RDB')
ser1.write('\r')
ser1.flushInput()
time.sleep(1)
rs=r2r(ser1, flush=True)
print rs
break
class HP_REPLAY(cmd.Cmd):
global config, ser1, ser2
prompt = ''.join(['Replay Mode','> '])
intro = '\n'
doc_header = 'Available Commands'
misc_header = 'Additional Topics'
undoc_header = 'Other Commands'
ruler = '-'
def emptyline(self):
pass
def postcmd(self, stop, line):
print
return cmd.Cmd.postcmd(self, stop, line)
def precmd(self, line):
print
return cmd.Cmd.precmd(self, line)
def help_help(self):
print 'Type help [topic] for more information on commands and operation.'
def do_status(self, line):
"""status
Display current system information in replay mode."""
status=HP_rep_status(ser1)
if not status==None:
try:
format_system(build_status(status, REPLAY_STATUS))
except:
logging.error('Unable to read status data.')
def do_pause(self,line):
"""pause
Pause playback."""
HP_replay_cmd(ser1,type='PAUSE')
def do_next(self,line):
"""next
Skip to next recording."""
HP_replay_cmd(ser1,type='NEXT')
def do_prev(self,line):
"""prev
Return to previous recording."""
HP_replay_cmd(ser1,type='PREV')
def do_resume(self,line):
"""resume
Resume playback."""
HP_replay_cmd(ser1,type='RESUME')
def do_exit(self,line):
"""exit
Leave replay mode."""
ok()
return True
class HP_CMD(cmd.Cmd):
global config, ser1, ser2
prompt = ''.join([PROMPT,'> '])
intro = UNIDEN
doc_header = 'Available Commands'
misc_header = 'Additional Topics'
undoc_header = 'Other Commands'
ruler = '-'
def emptyline(self):
pass
def postcmd(self, stop, line):
print
return cmd.Cmd.postcmd(self, stop, line)
def precmd(self, line):
print
if self.parseline(line)[0] in OPEN_CMD:
if not ser1:
logging.error('HomePatrol must be connected to use this command.')
return cmd.Cmd.precmd(self, '')
return cmd.Cmd.precmd(self, line)
def help_help(self):
print 'Type help [topic] for more information on commands and operation.'
def do_help(self, line):
cmd.Cmd.do_help(self, line)
if line in OPEN_CMD:
print
print ' {0}'.format('Note: HomePatrol must be connected to use this command.')
def do_save(self,line):
"""save [name]
Save current parameter set. Omit the name to save the default set."""
save_config(set=line)
def do_load(self,line):
"""load [name]
Load a new parameter set. Omit the name to load the default set."""
load_config(set=line)
def do_test(self,line):
"""test
Test command."""
ok()
def do_web(self,line):
"""web
Start Web UI. Press Control-C to exit."""
if not ser1:
HP_CMD().onecmd('open')
if ser1:
build_favorites()
set_config('web','ON',verbose=False)
if config['web_browser']=='ON':
import webbrowser
webbrowser.open_new(''.join(['http://', config['web_host']=='' and '127.0.0.1' or config['web_host'], ':', str(config['web_port'])]))
HP_www()
def do_monitor(self,line):
"""monitor
Start monitor mode. Press Ctrl-C to exit."""
HP_monitor(ser1)
def do_version(self,line):
"""version
Display program information"""
print version_string()
def do_set(self, line):
"""set parameter=[value] ...
Set one or more parameters.
Use set with no options for a list of available parameters.
"""
if line:
args=arg_dict(line)
for key in args:
if key in OK_VAR:
set_config(key, args[key])
else:
logging.error('Unknown Parameter')
else:
HP_CMD().onecmd('get')
def do_get(self,line):
"""get [match]
List all matching parameters.
Use get without an option for a full list of parameters. """
if line:
print ''.join(['Parameters Matching [',line,']'])
else:
print 'Available Parameters:'
print
for key in OK_VAR:
if key in OOO_VAR:
args = '[ON|OFF]'
elif key in MOD_VAR:
args = '[AUTO|AM|FM|NFM]'
elif key in INT_VAR:
args = '[Integer]'
elif key in FRQ_VAR:
args = '[MHZ|HZ]'
elif key in LIST_VAR:
args = '[X,Y,Z]'
else:
args = '[String]'
if line:
if key.find(line) != -1:
print '{0: <62} {1: <15}'.format('='.join([key, str(config[key])])[:61], args)
else:
try:
print '{0: <62} {1: <15}'.format('='.join([key, str(config[key])])[:61], args)
except:
pass
def do_scan(self, line):
"""scan
Set HomePatrol to Scan Mode."""
HP_scanmode(ser1)
def do_program(self, line):
"""program
Set scanner to Program Mode. Only programming commands will be available."""
HP_program_mode(ser1, enter=True)
HP_PROGRAM().cmdloop()
def do_debug(self, line):
"""debug
Enter Debug Mode. Only debug commands will be available."""
HP_DEBUG().cmdloop()
def do_replay(self, line):
"""replay
Set scanner to Replay Mode. Only replay commands will be available."""
HP_replaymode(ser1)
HP_REPLAY().cmdloop()
def do_cap(self, line):
"""cap
Capture a screenshot.
Images can not be captured when receiving in Scan Mode unless
recording is disabled by removing the batteries and using AC power."""
HP_screencap(ser1)
def do_status(self, line):
"""status
Display current system information in scan mode."""
status=HP_status(ser1)
if not status==None:
try:
format_system(build_status(status, SCAN_STATUS))
except:
logging.error('Unable to read status data.')
def do_raw(self, line):
"""raw
Read raw discriminator data from scanner using set parameters."""
HP_rawmode(ser1,freq=config['rd_freq'],mode=config['rd_mode'],att=config['rd_att'],filter=config['rd_filter'])
HP_rawread(ser1,ser2,file=config['rd_file'],timeout=config['rd_timeout'], record_time=config['rd_rectime'])
def do_dump(self, line):
"""dump [hex|bin|text]
Raw Mode with data slicer hex, binary or text dump."""
HP_rawmode(ser1,freq=config['rd_freq'],mode=config['rd_mode'],att=config['rd_att'])
HP_rawread(ser1,ser2,file=config['rd_file'],timeout=config['rd_timeout'], record_time=config['rd_rectime'], dump=True, strfmt=str(line), wav=False)
def do_open(self, line):
"""open
Connect HomePatrol to serial port."""
HP_open(config['port1'], config['port2'])
if config['hp_model'] and ser1:
if config['hp_model'] not in defs.SUPPORTED_SCANNERS:
logging.warning('This scanner is not supported by this program.')
self.prompt = ''.join([config['hp_model'],'> '])
def do_close(self, line):
"""close
Close all open serial ports."""
global ser1, ser2
if ser1:
logging.debug(' '.join(['Close',':',config['port1'],]))
ser1.close()
ser1=None
ok()
if ser2:
logging.debug(' '.join(['Close',':',config['port2'],]))
ser2.close()
ser2=None
self.prompt = ''.join([PROMPT,'> '])
def do_feed(self,status):
"""feed [ON|OFF]
Turn audio feed download ON or OFF.
Use this command without an option to check current setting."""
cmd=HP_cmd_on_off(ser1, status, type='STS', cmd='AUF')
if cmd=='ON':
HP_audio_feed(ser1)
def do_volume(self,vol):
"""volume [0-15]
Set volume level on scanner."""
HP_cmd_0_15(ser1,val=vol, type='VOL')
def do_squelch(self,sql):
"""squelch [0-15]
Set squelch level on scanner."""
HP_cmd_0_15(ser1,val=sql, type='SQL')
def do_mute(self,status):
"""mute [ON|OFF]
Turn mute ON or OFF.
Use this command without an option to check current setting."""
HP_cmd_on_off(ser1, status, type='MUTE')
def do_att(self,status):
"""att [ON|OFF]
Turn global attenuation ON or OFF.
Use this command without an option to check current setting."""
HP_cmd_on_off(ser1, status, type='GATT')
def do_record(self,status):
"""record [ON|OFF]
Turn audio recording ON or OFF.
Type record without an option to check current setting."""
HP_cmd_on_off(ser1, status, type='REC')
def do_bye(self, line):
"""bye
Exit program."""
HP_CMD().onecmd('close')
web_server(command='stop')
return True
def do_hold(self,line):
"""hold [system|department|channel] [ON|OFF]
Set category hold status. Use this command without a switch option
to check current setting."""
HP_hold_avoid(ser1, cmd=line, type='HOLD')
def do_avoid(self,line):
"""avoid [system|department|channel] [ON|OFF]
Set category avoid status. Use this command without a switch option
to check current setting."""
HP_hold_avoid(ser1, cmd=line, type='AVOID')
def do_next(self,line):
"""next [system|department|channel]
Set next system, department or channel. This command defaults to
channel control if an option is not specified."""
HP_hold_avoid(ser1, cmd=line, type='NEXT')
def do_prev(self,line):
"""next [system|department|channel]
Set previous system, department or channel. This command defaults to
channel control if an option is not specified."""
HP_hold_avoid(ser1, cmd=line, type='PREV')
def checksum(st):
return str(reduce(lambda x,y:x+y, map(ord, st)))
def command(cmd, *args, **kwargs):
"""Build command string for HP"""
flag=kwargs.get('flag', None)
if cmd:
base = ''.join([cmd,'\t','\t'.join([str(x) for x in args]),'\t'])
else:
base = ''.join(['\t'.join([str(x) for x in args[0]]),'\t'])
return ''.join([base, flag and flag or checksum(base),'\r'])
def checkerr(*args, **kwargs):
error=False
display=kwargs.get('display', True)
status=0
if 'ERR' in args[0]:
status=1
error=True
if 'NG' in args[0]:
status=2
error=True
if error and display:
logging.error(status==2 and 'Command Not Available' or status==1 and 'Invalid Command' or status==3 and 'No Data Available')
elif display:
logging.debug('OK')
return False
return error
def response(st):
return st.split('\t')
def subtone(code):
try:
icode=int(code)
except:
return None
if 64 <= icode <= 113:
return defs.CTCSS[code]
if 128 <= icode <= 231:
return defs.DCS[code]
if icode==0 or icode==127:
return ''
def sub_uid(code, uid):
try:
icode=int(code)
except:
icode=None
if icode:
if 64 <= icode <= 113:
return 'CTCSS'
if 128 <= icode <= 231:
return 'DCS'
elif uid and uid!='':
return 'UID'
return ''
def csv_system(system, short=True):
output = ''.join([var_sub(config['mon_format'], system),'\n'])
return output
def compare_systems(system1, system2):
if system1 and system2:
for key in COMPARE_SYSTEM: # Only compare items we're interested in - some fields are not always available
if system1[key] != system2[key]:
return False
else:
return False
return True
def digit_switch(s):
return s=='ON' and '1' or '0'
def format_system(system, monitor=False, header=True, systems=True, delay=2, other_system=None):
global last_system, display_system, timer
current_timer = int(time.time())
if not system and last_system:
system=last_system
if last_system['channel']:
if other_system:
display_system=other_system
last_system=None
if not monitor:
display_system=COMMON_SYSTEM
elif (delay <= current_timer - timer <= delay*2):
display_system=COMMON_SYSTEM if (display_system==ALT_SYSTEM or display_system==None) else ALT_SYSTEM
timer=int(time.time())
elif last_system and compare_systems(system,last_system) and monitor:
last_system=system
return
else:
timer=int(time.time())
last_system=system
if not display_system:
display_system=COMMON_SYSTEM
if header:
for (item,alt) in zip(COMMON_SYSTEM, ALT_SYSTEM):
if item==alt or not monitor:
print '{0: <25}'.format(item.upper()),
else:
print '{0: <25}'.format('/'.join([item.upper(),alt.upper()])),
print
if systems:
for key in display_system:
if system[key]:
offset = 0
print '{0}{1: <25}'.format('', format_data(system, key)[offset:24+offset]),