forked from openxc/OpenXCAccessory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxc_vi.py
executable file
·1436 lines (1271 loc) · 59.3 KB
/
xc_vi.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 -x
# $Rev:: 427 $
# $Author:: [email protected] $
# $Date:: 2016-08-15 $
# $Update:: Enable/Disable VI communication $
#
# openXC-Modem Vehicle Interface (VI) agent class and associated functions
import logging
import os.path
import subprocess
import re
import string
import sys
import time
import datetime
import socket
import os
from smbus import SMBus
try:
import bluetooth
except ImportError:
LOG.debug("pybluez library not installed, can't use bluetooth interface")
bluetooth = None
from xc_common import *
from ota_upgrade import *
import xc_led
import xc_ver
import fileinput
import json
try:
import dweepy
except Exception:
LOG.debug('dweepy import failed')
#--------------------------------------------------------------------
# Web upload settings
#--------------------------------------------------------------------
XCMODEM_CONFIG_FILE = 'xc.conf'
XCMODEM_TRACE_RAW_FILE = 'vi_trace_raw.json'
XCMODEM_TRACE_RAW_BK_FILE = 'vi_trace_raw_bk.json'
XCMODEM_TRACE_FILE = 'vi_trace.json'
XCMODEM_V2X_TRACE_RAW_FILE = 'v2x_trace_raw.json'
XCMODEM_V2X_TRACE_RAW_BK_FILE = 'v2x_trace_raw_bk.json'
XCMODEM_V2X_TRACE_FILE = 'v2x_trace.json'
XCMODEM_DATA_MOUNT = '/mnt/data'
XCMODEM_DATA_DEVICE = '/dev/mmcblk0'
XCMODEM_DATA_PARTITION = 'mmcblk0p2'
XCMODEM_DATA_TRACE_PREFIX = '/mnt/data/vi_trace_raw'
XCMODEM_DATA_V2X_TRACE_PREFIX = '/mnt/data/v2x_trace_raw'
XCMODEM_DATA_TRACE_SUFFIX = 'json'
UPLOAD_TIMEOUT_FACTOR = 0.05 # in=7K/s out=140K/s
UPLOAD_OVERHEAD_TIME = 30 # 30s
TIMEOUT_RC = 124
#--------------------------------------------------------------------
FIRMWARE_RESET_BUTTON_MONITOR_INTERVAL = 5 # in seconds
#---------------------------------------------
def vi_bt_restart(name):
# restart bluetooth
LOG.debug("Re-starting bluetooth ...")
# terminate BT related apps if applicable using exit flag
exit_flag['bt_restart'] = 1
cmd = "/etc/init.d/bluetooth restart; /root/OpenXCAccessory/startup/btrestart; /root/OpenXCAccessory/startup/hci_on"
try:
subprocess.call(cmd, shell=True)
except Exceptions as e:
LOG.debug("%s %s" % (name, e))
pass
else:
pairing_registration()
exit_flag['bt_restart'] = 0
def vi_bt5_pair(addr, debug):
import pexpect
# Bluetooth 5 client tasks are performed using bluetoothctl
# Thus, python expected like function will be utilized for this task
try:
child = pexpect.spawn('bluetoothctl')
if debug:
child.logfile = sys.stdout
child.expect('.*#')
child.sendline('agent on')
child.sendline('pairable on')
child.sendline('scan on')
child.expect('.*NEW.* Device %s.*' % addr)
child.sendline('pair %s' % addr)
child.expect('.*PIN code:')
child.sendline('1234')
child.expect('Pairing successful')
child.sendline('exit')
except pexpect.TIMEOUT:
# Note: Bluez5 registers the device although it fails to pair !!
# Thus, remove the invalid entry if applicable
cmd = "bluez-test-device list | grep \"%s\"" % addr
if not subprocess.call(cmd, shell=True):
cmd = "bluez-test-device remove %s" % addr
subprocess.call(cmd, shell=True)
return False
else:
return True
#-------------------------------------------------------------------------------------------
def vi_cleanup():
LOG.debug("Performing cleanup...")
# Previous paired VI might incidently take over assigned mb/md
# app ports; thus, we should clean up old paired devices
# check if the device has already paired up
cmd = "for d in `bluez-test-device list | grep -v %s | grep -v %s | awk '/OpenXC-VI-/ {print $1}'`; \
do bluez-test-device remove $d; done" % (OPENXC_V2X_NAME_PREFIX, OPENXC_MODEM_NAME_PREFIX)
if subprocess.call(cmd, shell=True):
LOG.debug("clean up fail")
# Remove lingering trace file
cmd = "rm -f %s %s %s" % (XCMODEM_TRACE_RAW_FILE, XCMODEM_TRACE_RAW_BK_FILE, XCMODEM_TRACE_FILE)
subprocess.call(cmd, shell=True)
cmd = "rm -f %s %s %s" % (XCMODEM_V2X_TRACE_RAW_FILE, XCMODEM_V2X_TRACE_RAW_BK_FILE, XCMODEM_V2X_TRACE_FILE)
subprocess.call(cmd, shell=True)
# clean up lingering pppd process if exist
subprocess.call('if [ -r /var/run/ppp0.pid ]; then echo "cleanup pppd ..."; killall -q pppd; sleep 3; fi', shell=True)
# turn off all led - needed to be after pppd cleaning up to free /tty/ACM3 for GSM Led if applicable
xc_led.all_leds(0)
#---------------------------------------------------------------
# USB connection threads
#---------------------------------------------------------------
class usbSendThread (threading.Thread):
# don't support usb send so just ignore all entry
def __init__(self, name, usb, queue, eflag):
threading.Thread.__init__(self)
self.name = name
self.device = usb
self.queue = queue
self.eflag = eflag
def run(self):
LOG.debug("Starting " + self.name)
while not exit_flag[self.eflag]:
while not self.queue.empty():
try:
data = self.queue.get()
if not data.endswith(chr(0)): # All messages need to end with \0 per the message format spec
data = data + chr(0)
# print("%s [%s]\n" % (self.name, data))
# Ignore all usb write since it somehow halt vi
# dongle stream !!!
# self.device.write(data)
except IOError as e:
exit_flag[self.eflag] = 1
LOG.debug("%s %s" % (self.name, e))
break
msleep(1)
LOG.debug("disconnected " + self.name)
class usbRecvThread (threading.Thread):
def __init__(self, name, usb, queue, eflag):
threading.Thread.__init__(self)
self.name = name
self.device = usb
self.queue = queue
self.eflag = eflag
def run(self):
LOG.debug("Starting " + self.name)
while not exit_flag[self.eflag]:
try:
data = self.device.read()
# print("%s [%s]\n" % (self.name, data))
self.queue.put(data)
except IOError as e:
LOG.debug("%s %s" % (self.name, e))
exit_flag[self.eflag] = 1
break
LOG.debug("disconnected " + self.name)
#--------------------------------------------------
# usb modem class
#--------------------------------------------------
# Derived from openxc/sources/usb.py
import usb.core
import usb.util
class xcmodemUsb:
DEFAULT_VENDOR_ID = 0x1bc4
DEFAULT_PRODUCT_ID = 0x0001
DEFAULT_READ_REQUEST_SIZE = 512
# If we don't get DEFAULT_READ_REQUEST_SIZE bytes within this number of
# milliseconds, bail early and return whatever we have - could be zero,
# could be just less than 512. If data is really pumpin' we can get better
# throughput if the READ_REQUEST_SIZE is higher, but this delay has to be
# low enough that a single request isn't held back too long.
DEFAULT_READ_TIMEOUT = 200
DEFAULT_INTERFACE_NUMBER = 0
VEHICLE_DATA_IN_ENDPOINT = 2
VEHICLE_DATA_OUT_ENDPOINT = 5
LOG_IN_ENDPOINT = 11
def __init__(self, vendor_id=DEFAULT_VENDOR_ID,
product_id=DEFAULT_PRODUCT_ID):
self.device = None
devices = usb.core.find(find_all=True, idVendor=vendor_id, idProduct=product_id)
for device in devices:
try:
device.set_configuration()
except usb.core.USBError as e:
LOG.error("Skipping USB device: %s", e)
else:
self.device = device
addr = "%.4X:%.4X" % (vendor_id, product_id)
LOG.info("found VI USB %s" % addr)
port_mac['vi_app'] = addr
return
LOG.debug("VI as USB device isn't detected")
def valid(self):
return self.device
def stop(self):
usb.util.dispose_resources(self.device)
def read(self, timeout=None,
endpoint_address=VEHICLE_DATA_IN_ENDPOINT,
read_size=DEFAULT_READ_REQUEST_SIZE):
timeout = timeout or self.DEFAULT_READ_TIMEOUT
try:
return self.device.read(0x80 + endpoint_address,
read_size, self.DEFAULT_INTERFACE_NUMBER, timeout).tostring()
except (usb.core.USBError, AttributeError) as e:
if e.errno == 110:
# Timeout, it may just not be sending
return ""
raise IOError("USB device couldn't be read", e)
def write(self, data):
try:
self.device.write(self.VEHICLE_DATA_OUT_ENDPOINT, data)
except (usb.core.USBError, AttributeError) as e:
raise IOError("USB device couldn't be written", e)
#---------------------------------------------------------------------
# class for Modem's VI interface
#---------------------------------------------------------------------
class xcModemVi:
def __init__(self, port, inQ, outQ, sdebug = 0, debug = 0):
self.port = port
self.addr = None
self.socket = None
self.discovery_once = False
self.inQ = inQ
self.outQ = outQ
self.fp = None
self.v2x_fp = None
self.name = 'vi_app'
self.trace_enable = 0
self.v2x_trace_enable = 0
self.stop_web_upload = None
self.stop_v2x_web_upload = None
self.stop_dweet_upload = None
self.stop_trace = None
self.stop_monitor = None
self.stop_button_monitor = None
self.button_irq_cnt = 1
self.trace_lock = threading.Lock()
self.trace_raw_lock = threading.Lock()
self.v2x_trace_raw_lock = threading.Lock()
self.threads = []
self.lost_cnt = 0
self.gsm = None
self.bt5 = self.bt5_check()
self.sdebug = sdebug
self.debug = debug
self.boardid = boardid_inquiry(1)
self.config_mode = None
self.sd_space = 0
self.usb = None
self.modem_ip_addr = None
self.modem_port = None
self.conn_type = None
# LEDs instances
pathid = self.boardid > 0
self.bt_led = xc_led.xcModemLed('bt_led', led_path['bt'][pathid])
self.wifi_led = xc_led.xcModemLed('wifi_led', led_path['wifi'][pathid])
self.bat_led_grn = xc_led.xcModemLed('bat_led_grn', led_path['bat_grn'][pathid])
self.bat_led_red = xc_led.xcModemLed('bat_led_red', led_path['bat_red'][pathid])
modem_state[self.name] = vi_state.IDLE
self.charger = SMBus(0) # open Linux device /dev/ic2-0
self.led_cntl = SMBus(2) # open Linux device /dev/ic2-2
self.charger_fault = 0
self.battery_check()
def cur_conn_type(self):
return self.conn_type;
def modem_mac_inquiry(self):
# Return modem mac address
mac = subprocess.check_output('hcitool dev | grep hci0', shell=True).split()[1]
LOG.info("%s %s" % (board_type[self.boardid]['prefix'], mac))
return mac
def bt5_check(self):
# check if bluetooth 5 is used
bt_ver = subprocess.check_output("bluetoothd -v | awk -F . '{print $1}'", shell=True).strip()
LOG.debug('Bluez' + bt_ver)
return (int(bt_ver) >= 5)
def auto_discovery(self):
# Return address once the first openxc device found
LOG.info("Auto discovery ...")
try:
nearby_devices = bluetooth.discover_devices(lookup_names = True)
except BluetoothError as e:
LOG.error("BT error %s %s" % (self.name, e))
return None
for addr, name in nearby_devices:
LOG.debug(" %s - %s" % (addr, name))
if (name is not None \
and name.startswith(OPENXC_DEVICE_NAME_PREFIX) \
and not name.startswith(OPENXC_MODEM_NAME_PREFIX) \
and not name.startswith(OPENXC_V2X_NAME_PREFIX)):
LOG.info("Found %s - %s" % (addr, name))
self.addr = addr
break
self.discovery_once = True
return self.addr
def file_discovery(self, fname):
# Return address from existing configuration file
LOG.info("Static discovery ...")
brightness_override = 0
if os.path.exists(fname):
# setup default based on modem/v2x board
for key in ['gsm_enable', 'gps_enable', 'openxc_vi_enable', 'openxc_md_enable']:
conf_options[key] = int(board_type[self.boardid]['type'] != 'V2X')
try:
conf = open(fname, "r")
LOG.info(" Found %s ..." % fname)
for line in conf:
if not line.startswith('#') and line.strip(): # skip comments/blank lines
L = line.split() # split the string
key = L[0]
if conf_options.get(key) is not None: # for valid key
LOG.debug("old: (%s:%s)" % (key, conf_options[key]))
if key == 'gsm_enable' or key == 'gps_enable': # V2X doesn't support gsm/gps
if board_type[self.boardid]['type'] == 'V2X':
LOG.error("%s isn't a valid option of %s - skip it !!" % \
(key, board_type[self.boardid]['type']))
continue
if re.search(r'_enable', key, re.M|re.I):
conf_options[key] = int(L[1])
else:
if key == 'power_saving_mode': # validate power_mode
if power_mode.get(L[1]) is None:
LOG.error("%s isn't a valid value of %s - skip it !!" % (L[1], key))
continue
elif not brightness_override: # adjust brightness default if applicable
conf_options['led_brightness'] = power_mode[L[1]]['led_brightness']
elif key == 'openxc_vi_trace_filter_script': # validate filter script
if not os.path.exists(L[1]) or not os.access(L[1], os.X_OK):
LOG.error("%s isn't an executable script for %s - skip it !!" % (L[1], key))
continue
elif key == 'led_brightness': # validate led brightness
brightness = int(L[1])
if brightness < 0 or brightness > 255:
LOG.error("%s isn't a valid value of %s - skip it !!" % (L[1], key))
else:
conf_options[key] = brightness
brightness_override = 1
LOG.debug("new: (%s:%s)" % (key, conf_options[key]))
continue
conf_options[key] = L[1]
LOG.debug("new: (%s:%s)" % (key, conf_options[key]))
else:
LOG.error("%s isn't a valid key in %s - skip it !!" % (key, fname))
except IOError:
LOG.error("fail to open %s" % fname)
else:
conf.close()
if not conf_options['openxc_vi_enable']:
LOG.info("vi_app is disable")
# nothing to passthru
for l in passthru_flag.items():
(key, val) = l
passthru_flag[key] = 0
else:
addr = conf_options['openxc_vi_mac']
if addr is not None and addr != 'None':
self.addr = addr
LOG.info("found %s" % self.addr)
# config passthru
for l in passthru_flag.items():
(key, val) = l
passthru_flag[key] = passthru_enable[key]
self.vi_power_profile()
vi_auto_upgrade() # Note: auto upgrade might take awhile
# handle vi usb-connection if applicable
if self.usb is None:
self.usb = xcmodemUsb()
if self.usb.valid() is None:
del self.usb
self.usb = None
else:
self.addr = port_mac[self.name]
return self.addr
def web_discovery(self, fname):
# Obtain the config file from predefined URL using scp
# To maintain the original file, '.web' suffix will be used for
# the web download file
LOG.info("Web discovery ... ")
# Use WiFi if applicable
if not check_ping() == 0:
# Use GSM if applicable
if conf_options['gsm_enable']:
if not self.gsm.start():
# No need to move on without network connection
return None
# Use sshpass with given psswd for scp
# Remote cloud server require PEM which is provided in configuration option
wfname = fname + ".web"
# Form unique config file name
if re.search(r'/', conf_options['web_scp_config_url'], re.M|re.I):
delimiter = '/'
else:
delimiter = ':'
prefix = "%s%s." % (delimiter, socket.gethostname())
cfname = prefix.join(conf_options['web_scp_config_url'].rsplit(delimiter, 1))
cmd = "scp -o StrictHostKeyChecking=no -i %s %s@%s %s" % \
(conf_options['web_scp_pem'], \
conf_options['web_scp_userid'], \
cfname, \
wfname)
# LOG.debug("issuing '%s'" % cmd)
if subprocess.call(cmd, shell=True):
LOG.error("fail to scp %s from %s@%s" % (fname, \
conf_options['web_scp_userid'], \
cfname))
LOG.warn("Please make sure to register your device %s on the web server" % socket.gethostname())
return None
# Use WiFi if applicable
if not check_ping() == 0:
# Use GSM if applicable
if conf_options['gsm_enable']:
# Tear off gsm connection
self.gsm.stop()
# parse the file now
return self.file_discovery(wfname)
def gsm_instance(self, force = 0):
sys.path.append('../modem') # GSM is only supported in modem
import xc_modem_gsm
if force:
if self.gsm is not None:
LOG.info("Reinstantiate " + self.gsm.name)
del self.gsm
self.gsm = None
# Instantiate gsm module as needed
if self.gsm is None:
ppp_tear_off = power_mode[conf_options['power_saving_mode']]['ppp_tear_off']
self.gsm = xc_modem_gsm.xcModemGsm(sdebug = self.sdebug, debug = self.debug, tear_off = ppp_tear_off)
if not self.gsm.prep(conf_options['web_scp_apn']):
LOG.error("There is no network access !!!")
return False
return True
def modem_inquiry(self):
if (self.modem_ip_addr is None):
self.modem_ip_addr = conf_options['xcmodem_ip_addr']
return conf_options['xcmodem_ip_addr']
else:
return self.modem_ip_addr
def modem_available(self, modem_ip_addr):
LOG.info("Checking if Modem is available %s" % modem_ip_addr)
cmd = "ping -c 1 " + modem_ip_addr + " > /dev/null 2>&1"
LOG.info(cmd)
response = subprocess.call(cmd, shell=True)
if response == 0:
LOG.info("Modem responded to ping")
self.modem_ip_addr = modem_ip_addr
self.modem_port = 4567
return 1
else:
LOG.info("Modem did NOT respond to ping")
return 0
def vi_inquiry(self):
# determine the vi_app address using pre-defined priority scheme
if self.file_discovery(XCMODEM_CONFIG_FILE) is None and conf_options['openxc_vi_enable']:
if conf_options['web_scp_config_download_enable'] and conf_options['gsm_enable']:
# Prepare GSM if applicable using correct options
if not self.gsm_instance():
# skip web discovery
if self.auto_discovery() is None:
LOG.info("None OPENXC-VI Device Address Assignment!!!")
elif self.web_discovery(XCMODEM_CONFIG_FILE) is None:
if self.auto_discovery() is None:
LOG.info("None OPENXC-VI Device Address Assignment!!!")
elif self.auto_discovery() is None:
LOG.info("None OPENXC-VI Device Address Assignment!!!")
# Saving the current config file for reference
self.conf_save(XCMODEM_CONFIG_FILE + ".cur")
return self.addr
def vi_discovery(self):
LOG.info("Performing inquiry...")
self.bt_led.blink(1) # slow blink
try:
nearby_devices = bluetooth.discover_devices(duration=10,lookup_names = True)
except BluetoothError as e:
LOG.error("BT error %s %s" % (self.name, e))
return False
LOG.info("found %d devices" % len(nearby_devices))
for addr, name in nearby_devices:
LOG.info(" %s - %s" % (addr, name))
if (addr is not None and addr == self.addr):
self.bt_led.off() # done discovery
return True
self.bt_led.off() # done discovery
return False
def vi_pair(self):
# Work-around for dongle pairing
# subprocess.call('hciconfig hci0 sspmode disable', shell=True)
# check if the device has already paired up
cmd = "bluez-test-device list | grep \"%s\"" % self.addr
# LOG.debug("issuing: " + cmd)
if subprocess.call(cmd, shell=True):
# re-pairing
LOG.info("pairing %s ..." % self.addr)
self.bt_led.blink() # fast blink
if self.bt5:
rc = vi_bt5_pair(self.addr, self.debug)
else:
cmd = "echo '1234' | bluez-simple-agent hci0 %s 2>&1 1>/dev/null" % self.addr
# LOG.debug("issuing: " + cmd)
rc = not subprocess.call(cmd, shell=True)
self.bt_led.off() # done pairing
return rc
return True
def modem_connect(self):
# Modem is acting as Master/Client agent
LOG.info("trying to connect %s ..." % self.modem_ip_addr)
attempt = 1
while (attempt <= MAX_CONNECTION_ATTEMPT):
# Ensure if the device is paired
#if self.vi_pair():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
LOG.info("trying to connect to %s at port %s" % (self.modem_ip_addr, self.modem_port))
s.connect((self.modem_ip_addr, self.modem_port))
except IOError:
LOG.warn("Unable to connect to %s " % self.modem_ip_addr)
#s.shutdown(socket.SHUT_RDWR)
s.close()
time.sleep(3)
else:
self.bt_led.blink()
LOG.info("Opened modem connection at %s" % self.modem_port)
self.socket = s
#port_mac[self.name] = self.addr
break;
attempt += 1
self.bt_led.on()
return self.socket
def vi_connect(self):
# Modem is acting as Master/Client agent
LOG.info("connect %s ..." % self.addr)
attempt = 1
while (attempt <= MAX_CONNECTION_ATTEMPT):
# Ensure if the device is paired
if self.vi_pair():
socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
try:
socket.connect((self.addr, self.port))
except IOError:
LOG.warn("Unable to connect to %s" % self.addr)
else:
self.bt_led.on() # dongle connect
LOG.info("Opened bluetooth device at %s" % self.port)
self.socket = socket
port_mac[self.name] = self.addr
break;
attempt += 1
return self.socket
#-------------------------------------------------------------------
# Setup environment for backing the log to SD card datalog partition
#-------------------------------------------------------------------
def trace_sd_backup_prep(self):
# Prepare mSD mount
LOG.debug("SD backup prep")
if int(conf_options['openxc_vi_trace_number_of_backup']) > 0:
cmd = "fdisk -l %s | grep %s; \
if [ $? -eq 0 ]; then \
mount | grep %s; \
if [ $? -eq 0 ]; then \
umount %s; \
fi; \
mkdir -p %s; \
mount /dev/%s %s; \
else \
exit 1; \
fi" % (XCMODEM_DATA_DEVICE, XCMODEM_DATA_PARTITION, \
XCMODEM_DATA_MOUNT, \
XCMODEM_DATA_MOUNT, \
XCMODEM_DATA_MOUNT, \
XCMODEM_DATA_PARTITION, XCMODEM_DATA_MOUNT)
# LOG.debug("issuing '%s'" % cmd)
if subprocess.call(cmd, shell=True):
LOG.error("fail to prepare %s - skip SD backup" % XCMODEM_DATA_MOUNT)
conf_options['openxc_vi_trace_number_of_backup'] = 0 # Turn off SD backup
else:
cmd = "df -BK %s | tail -1 | awk '{print $4}' | awk -FK '{print $1}'" % XCMODEM_DATA_MOUNT
# LOG.debug("issuing '%s'" % cmd)
self.sd_space = int(subprocess.check_output(cmd, shell=True).split()[0]) * 1024
#-------------------------------------------------------------------
# Backup log to SD card datalog partition
#-------------------------------------------------------------------
def trace_sd_backup(self, bfname, bfsize, v2x_flag):
# sd backup file
LOG.debug("SD backup")
# check for space
fnum = int(conf_options['openxc_vi_trace_number_of_backup'])
while (fnum > 0) :
if self.sd_space < bfsize:
# remove file to make space
fname = "%s_%s.%s" % (XCMODEM_DATA_TRACE_PREFIX, fnum, XCMODEM_DATA_TRACE_SUFFIX)
if conf_options['openxc_vi_trace_backup_overwrite_enable']:
if os.path.exists(fname):
fsize = os.path.getsize(fname)
# LOG.debug("removing '%s'" % fname)
os.remove(fname)
self.sd_space += fsize
fnum -= 1
else:
LOG.info("Skip SD backup due to unsufficent space")
return # skip if no space left
else:
break
# pump up backup file
fnum = int(conf_options['openxc_vi_trace_number_of_backup'])
while (fnum > 0):
if v2x_flag:
fname1 = "%s_%s.%s" % (XCMODEM_DATA_V2X_TRACE_PREFIX, fnum, XCMODEM_DATA_TRACE_SUFFIX)
else:
fname1 = "%s_%s.%s" % (XCMODEM_DATA_TRACE_PREFIX, fnum, XCMODEM_DATA_TRACE_SUFFIX)
fnum -= 1
if v2x_flag:
fname2 = "%s_%s.%s" % (XCMODEM_DATA_V2X_TRACE_PREFIX, fnum, XCMODEM_DATA_TRACE_SUFFIX)
else:
fname2 = "%s_%s.%s" % (XCMODEM_DATA_TRACE_PREFIX, fnum, XCMODEM_DATA_TRACE_SUFFIX)
if os.path.exists(fname2):
if os.path.exists(fname1): # gain space
self.sd_space += os.path.getsize(fname1)
# LOG.debug("rename '%s to %s' " % (fname2, fname1))
os.rename(fname2, fname1)
# backup recent raw file
if v2x_flag:
fname = "%s_1.%s" % (XCMODEM_DATA_V2X_TRACE_PREFIX, XCMODEM_DATA_TRACE_SUFFIX)
else:
fname = "%s_1.%s" % (XCMODEM_DATA_TRACE_PREFIX, XCMODEM_DATA_TRACE_SUFFIX)
cmd = "cp -p %s %s" % (bfname, fname)
#LOG.debug("issuing '%s' " % cmd)
if subprocess.call(cmd, shell=True):
LOG.error("fail to backup %s" % fname)
else:
self.sd_space -= bfsize
#-------------------------------------------------------------------
# Control for capturing VI trace log
#-------------------------------------------------------------------
def trace_start(self, interval, rfname, bfname):
LOG.debug("Recording start: %s" % rfname)
# set up new trace
self.trace_raw_lock.acquire()
self.fp = open(rfname, "w+")
self.trace_raw_lock.release()
self.trace_enable = 1
time.sleep(interval)
self.trace_enable = 0
self.trace_raw_lock.acquire()
self.fp.close()
if (os.path.isfile(rfname)):
os.rename(rfname, bfname)
bfsize = os.path.getsize(bfname)
if (os.path.isfile(bfname)):
LOG.debug("Recording stop (size: %s) : %s" % (bfsize, rfname))
else:
LOG.debug("VI Recording failed")
if int(conf_options['openxc_vi_trace_number_of_backup']) > 0: # if SD backup is needed
self.trace_sd_backup(bfname, bfsize,0)
self.trace_raw_lock.release()
#-------------------------------------------------------------------
# Control for capturing V2X/RSU trace log
#-------------------------------------------------------------------
def v2x_trace_start(self, interval, rfname, bfname):
LOG.debug("Recording start: %s" % rfname)
# set up new trace
self.v2x_trace_raw_lock.acquire()
self.v2x_fp = open(rfname, "w+")
self.v2x_trace_raw_lock.release()
self.v2x_trace_enable = 1
time.sleep(interval)
self.v2x_trace_enable = 0
self.v2x_trace_raw_lock.acquire()
self.v2x_fp.close()
if (os.path.isfile(rfname)):
os.rename(rfname, bfname)
bfsize = os.path.getsize(bfname)
if (os.path.isfile(bfname)):
LOG.debug("Recording stop (size: %s) : %s" % (bfsize, rfname))
else:
LOG.debug("v2x Recording failed")
if int(conf_options['openxc_vi_trace_number_of_backup']) > 0: # if SD backup is needed
self.trace_sd_backup(bfname, bfsize,1)
self.v2x_trace_raw_lock.release()
def trace_prep(self, bfname, fname):
# make bk file readable so we can present it over network later on
#LOG.debug("Recording conversion")
# handle filtering script if applicable
if conf_options['openxc_vi_trace_filter_script'] is None or \
conf_options['openxc_vi_trace_filter_script'] == 'None':
filter = ""
else:
filter = "| %s" % conf_options['openxc_vi_trace_filter_script']
cmd = "sed -e 's/\\x0/\\r\\n/g' %s | sed -n -e '/{/ { /}/p }' %s > %s" % (bfname, filter, fname)
truncate_size = int(conf_options['openxc_vi_trace_truncate_size'])
self.trace_lock.acquire()
# LOG.debug("issuing '%s'" % cmd)
if subprocess.call(cmd, shell=True):
LOG.error("fail to convert %s" % fname)
elif truncate_size:
LOG.debug("Truncate %s to %s bytes" % (fname, truncate_size))
fp = open(fname, "rw+")
fp.truncate(truncate_size)
fp.close()
self.trace_lock.release()
def web_upload(self, bfname, fname):
if not os.path.exists(bfname):
LOG.debug("No trace yet to be uploaded")
return
# Prep the trace file
self.trace_prep(bfname, fname)
# Use WiFi if applicable
if not check_ping() == 0:
if (boardid_inquiry() > 1):
#LOG.info("No connection to cloud found!! Skipping upload")
return
# Use GSM if applicable
if conf_options['gsm_enable']:
# Create gsm instance as needed
if not self.gsm_instance():
return
if not self.gsm.start():
# No need to move on without network
if modem_state[self.gsm.name] == app_state.LOST:
# Create new gsm instance to re-establishing modem connection
if not self.gsm_instance(force = 1):
return
if not self.gsm.start():
return
else:
return
# OXM-93: Need timeout to terminate scp process in case something goes wrong
timeout = (float(conf_options['openxc_vi_trace_snapshot_duration']) * UPLOAD_TIMEOUT_FACTOR) + UPLOAD_OVERHEAD_TIME
# Use sshpass with given psswd for scp
# Remote cloud server require PEM which is provided in configuration option
if conf_options['web_scp_target_overwrite_enable']:
timestamp = ""
else:
timestamp = ".%s" % datetime.datetime.utcnow().strftime("%y%m%d%H%M%S")
if re.search(r'/', conf_options['web_scp_vi_target_url'], re.M|re.I):
delimiter = '/'
else:
delimiter = ':'
prefix = "%s%s%s." % (delimiter, socket.gethostname(), timestamp)
target = prefix.join(conf_options['web_scp_vi_target_url'].rsplit(delimiter, 1))
cmd = "timeout %s scp -o StrictHostKeyChecking=no -i %s %s %s@%s" % \
(int(timeout), \
conf_options['web_scp_pem'], \
fname, \
conf_options['web_scp_userid'], \
target)
#LOG.debug("VI_WEB_UPLOAD - issuing '%s'" % cmd)
self.trace_lock.acquire()
rc = subprocess.call(cmd, shell=True)
if rc:
if rc == TIMEOUT_RC:
msg = "Timeout (%ds)" % int(timeout)
#modem_state[self.gsm.name] = app_state.LOST
modem_state[self.name] = app_state.LOST
else:
msg = "Fail"
LOG.error("%s to scp upload %s to %s@%s" % (msg, fname, \
conf_options['web_scp_userid'], \
target))
self.trace_lock.release()
# Use WiFi if applicable
if not check_ping() == 0:
# Use GSM if applicable
if conf_options['gsm_enable']:
# Tear off gsm connection
self.gsm.stop()
#===================================================================
def web_v2x_upload(self, bfname, fname):
LOG.debug("******>>>> Start uploading trace to Web")
if not os.path.exists(bfname):
#LOG.debug("No trace yet to be uploaded")
return
# Prep the trace file
self.trace_prep(bfname, fname)
# Use WiFi if applicable
if not check_ping() == 0:
if (boardid_inquiry() > 1):
#LOG.info("No connection to cloud found!! Skipping upload")
return
# Use GSM if applicable
if conf_options['gsm_enable']:
# Create gsm instance as needed
if not self.gsm_instance():
return
if not self.gsm.start():
# No need to move on without network
if modem_state[self.gsm.name] == app_state.LOST:
# Create new gsm instance to re-establishing modem connection
if not self.gsm_instance(force = 1):
return
if not self.gsm.start():
return
else:
return
# OXM-93: Need timeout to terminate scp process in case something goes wrong
timeout = (float(conf_options['openxc_v2x_trace_snapshot_duration']) * UPLOAD_TIMEOUT_FACTOR) + UPLOAD_OVERHEAD_TIME
# Use sshpass with given psswd for scp
# Remote cloud server require PEM which is provided in configuration option
if conf_options['web_scp_target_overwrite_enable']:
timestamp = ""
else:
timestamp = ".%s" % datetime.datetime.utcnow().strftime("%y%m%d%H%M%S")
if re.search(r'/', conf_options['web_scp_xcV2Xrsu_target_url'], re.M|re.I):
delimiter = '/'
else:
delimiter = ':'
prefix = "%s%s%s." % (delimiter, socket.gethostname(), timestamp)
target = prefix.join(conf_options['web_scp_xcV2Xrsu_target_url'].rsplit(delimiter, 1))
cmd = "timeout %s scp -o StrictHostKeyChecking=no -i %s %s %s@%s" % \
(int(timeout), \
conf_options['web_scp_pem'], \
fname, \
conf_options['web_scp_userid'], \
target)
#LOG.debug("XCV2X_WEB_UPLOAD - issuing '%s'" % cmd)
self.trace_lock.acquire()
rc = subprocess.call(cmd, shell=True)
if rc:
if rc == TIMEOUT_RC:
msg = "Timeout (%ds)" % int(timeout)
#modem_state[self.gsm.name] = app_state.LOST
modem_state[self.name] = app_state.LOST
else:
msg = "Fail"
LOG.error("%s to scp upload %s to %s@%s" % (msg, fname, \
conf_options['web_scp_userid'], \
target))
self.trace_lock.release()
# Use WiFi if applicable
if not check_ping() == 0:
# Use GSM if applicable
if conf_options['gsm_enable']:
# Tear off gsm connection
self.gsm.stop()
#-------------------------------------------------------------------
# Dweet functions
#-------------------------------------------------------------------
def univ_file_read(name,mode):
return open(name,'rU')
def dweet_upload(self, bfname, fname):
if not os.path.exists(bfname):
LOG.debug("No trace yet to be Dweeted")
return
# Prep the trace file
self.trace_prep(bfname, fname)
# Use WiFi if applicable
if not check_ping() == 0:
if (boardid_inquiry() > 1):
#LOG.info("No connection to cloud found!! Skipping upload")
return
# Use GSM if applicable
if conf_options['gsm_enable']:
# Create gsm instance as needed
if not self.gsm_instance():
return
if not self.gsm.start():
# No need to move on without network
if modem_state[self.gsm.name] == app_state.LOST:
# Create new gsm instance to re-establishing modem connection
if not self.gsm_instance(force = 1):
return
if not self.gsm.start():
return
else:
return
self.trace_lock.acquire()
LOG.debug("buffering and sending dweet payload")
buff = ''
data = fileinput.input(fname,openhook=univ_file_read)
for idx,val in enumerate(data):
if val[-1:] == '\n':
val = val[:-1]
if idx==0:
val = '['+val
else:
val = ','+val
buff = buff + val
buff = buff+"]"
ret = dweepy.dweet_for(conf_options['dweet_thing_name'],{'trace':buff})
if not ret:
LOG.debug("dweet sending failed")
self.trace_lock.release()
# Use WiFi if applicable
if not check_ping() == 0:
# Use GSM if applicable