-
Notifications
You must be signed in to change notification settings - Fork 93
/
elm.py
2248 lines (2113 loc) · 92.4 KB
/
elm.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 python3
# -*- coding: utf-8 -*-
###########################################################################
# ELM327-emulator
# ELM327 Emulator for testing software interfacing OBDII via ELM327 adapter
# https://github.com/Ircama/ELM327-emulator
# (C) Ircama 2021 - CC-BY-NC-SA-4.0
###########################################################################
import logging
import logging.config
from pathlib import Path
import yaml
import re
import os
import socket
import serial
from enum import Enum
if not os.name == 'nt':
import pty
import tty
import threading
import time
import traceback
import errno
from random import choices
from .obd_message import ObdMessage
from .obd_message import ELM_R_OK, ELM_R_UNKNOWN, ST
from .obd_message import ECU_ADDR_E, ECU_R_ADDR_E, ECU_ADDR_I, ECU_R_ADDR_I
from .__version__ import __version__
from functools import reduce # only used in readme examples
import string
from xml.etree.ElementTree import fromstring, ParseError
import importlib
import pkgutil
import inspect
# Configuration constants__________________________________________________
FORWARD_READ_TIMEOUT = 0.2 # seconds
SERIAL_BAUDRATE = 38400 # bps
NETWORK_INTERFACES = ""
PLUGIN_DIR = __package__ + ".plugins"
MAX_TASKS = 20
ISO_TP_MULTIFRAME_MODULE = 'ISO-TP request pending'
MIN_SIZE_UDS_LENGTH = 20 # Minimum size to use a UDS header with additional length byte (ISO 14230-2)
INTERRUPT_TASK_IF_NOT_HEX = False
ELM_VALID_CHARS = r"^[a-zA-Z0-9 \n\r\b\t@,.?]*$"
ECU_TASK = "task_ecu_"
DEFAULT_ECU_TASK = 'Default ECU Task module'
ELM_VERSION = "ELM327 v1.5"
ELM_HEADER_VERSION = "\r\r"
"""
Ref. to ISO 14229-1 and ISO 14230, this is a list of SIDs (UDS service
identifiers) which have additional sub-function bytes in the related
positive answer. The value indicates the number of bytes to add to the
answer for each requested SID. Not included SIDs in this list have 0
additional bytes in the answer.
"""
uds_sid_pos_answer = {
"01": 1, # Show current data
"02": 1, # Show freeze frame data
"05": 1, # Test results, oxygen sensor monitoring
"09": 1, # Request vehicle information
"10": 1, # Diagnostic Session Control (DSC)
"11": 1, # ECU Reset (ER)
"14": 0, # Clear Diagnostic Information DTC (CDTCI)
"19": 2, # Read DTC Information
"21": 1, # Read Data by Local Id
"22": 2, # Read Data By Identifier (RDBI)
"23": 0, # Read memory by address (RMBA)
"24": 0, # Read Scaling Data By Identifier
"27": 1, # Security Access (SA)
"2A": 0, # Read Data By Periodic Identifier
"2C": 0, # Dynamically Define Data Identifier
"2E": 2, # Write Data By Identifier (WDBI)
"2F": 0, # Input Output Control By Identifier
"30": 1, # IO Control by Local Id
"31": 1, # Routine Control - Start Routine by Local ID (RC)
"38": 0, # Start Routine by Address
"3B": 1, # ?
"3D": 0, # Write Memory by Address (WMBA)
"3E": 1, # Tester Present (TP)
"85": 1, # Control DTC Setting
}
# End of configuration constants_______________________________________________
class Tasks:
"""
Base class for tasks.
All tasks/plugins shall implement a class named Task derived from Tasks.
"""
class RETURN:
"""
Return values for all Tasks methods
"""
TERMINATE = False
CONTINUE = True
ERROR = (None, TERMINATE, None)
INCOMPLETE = (None, CONTINUE, None)
def PASSTHROUGH(cmd): return None, Tasks.RETURN.TERMINATE, cmd
def TASK_CONTINUE(cmd): return None, Tasks.RETURN.CONTINUE, cmd
def ANSWER(answer): return answer, Tasks.RETURN.TERMINATE, None
def __init__(self, emulator, pid, header, ecu, request, attrib,
do_write=False):
self.emulator = emulator # reference to the emulator namespace
self.shared = None # A ISO-TP Multiframe special task will not use a shared namespace
if ecu in self.emulator.task_shared_ns:
self.shared = self.emulator.task_shared_ns[ecu] # shared namespace
if pid: # None if ECU Task, pid if ELM command Task
self.pid = pid # PID label
self.header = header # request header
self.request = request # original request data (stored before running the start() method)
self.attrib = attrib # dictionary element (None if not pertinent)
self.do_write = do_write # (boolean) will write to the application
self.frame = None # ISO-TP Multiframe request frame counter
self.length = None # ISO-TP Multiframe request length counter
self.flow_control = 0 # ISO-TP Multiframe request flow control
self.flow_control_end = 0x20 # ISO-TP Multiframe request flow control repetitions
self.ecu = ecu # ECU name
else:
self.shared = self # ECU Task
self.logging = emulator.logger # logger reference
self.time_started = time.time() # timer (to be used to simulate background processing)
def HD(self, header):
"""
Generates the XML tag related to the header byte of the response (ECU ID)
:param size: header (ECU ID)
:return: XML tag related to the header of the response
"""
return ('<header>' + header + '</header>')
def SZ(self, size):
"""
Generates the XML tag related to the size byte of the response
:param size: string including the size byte
:return: XML tag related to the size byte of the response
"""
return ('<size>' + size + '</size>')
def DT(self, data):
"""
Generates the XML tag related to the data part of the response
:param data: data part (string of hex data spaced every two bytes)
:return: XML tag related to the data part of the response
"""
return ('<data>' + data + '</data>')
def AW(self, answer):
"""
Generates the XML tag related to the response, which will be
automatically translated in header, size and data.
:param answer: data part (string of hex data)
:return: XML tag related to the response
"""
return ('<answer>' + answer + '</answer>')
def PA(self, pos_answer):
"""
Generates a positive answer XML tag, including header, size and data.
:param answer: data part (string of hex data)
:return: XML tag related to the response
"""
return ('<pos_answer>' + pos_answer + '</pos_answer>')
def NA(self, neg_answer):
"""
Generates a negative answer XML tag, including header, size and data.
:param answer: data part (string of hex data)
:return: XML tag related to the response
"""
return ('<neg_answer>' + neg_answer + '</neg_answer>')
def task_get_request(self):
"""
Get the original request command that initiated the task (used to
generate the answers)
:return: return the original request string
"""
return self.request
def task_request_matched(self, request):
"""
Check whether the request in the argument matches the original request
that invoked the task.
:param request:
:return: boolean (true if the given request matches the original task request)
"""
if not self.attrib:
return None
return re.match(self.attrib['REQUEST'], request)
def start(self, cmd, length=None, frame=None):
"""
This method is executed when the task is started.
If not overridden, it calls run()
:param cmd: request to process
:return: tuple of three values:
- XML response (or None for no output)
- boolean to terminate the task or to keep it active
- request to be subsequently processed after outputting the XML
response in the first element (or Null to disable subsequent
processing)
"""
return self.run(cmd, length, frame)
def stop(self, cmd, length=None, frame=None):
"""
This method is executed when the task is interrupted by an error.
If not overridden, it returns an error.
:param cmd: request to process
:return: tuple of three values:
- XML response (or None for no output)
- boolean to terminate the task or to keep it active
- request to be subsequently processed after outputting the XML
response in the first element (or Null to disable subsequent
processing)
"""
return Tasks.RETURN.ERROR
def run(self, cmd, length=None, frame=None):
"""
Main method to be overridden by the actual task; it is always run
if start and stop are not overridden, otherwise it is run for the
subsequent frames after the first one
:param cmd: request to process
:return: tuple of three values:
- XML response (or None for no output)
- boolean to terminate the task or to keep it active
- request to be subsequently processed after outputting the XML
response in the first element (or Null to disable subsequent
processing)
"""
return Tasks.RETURN.PASSTHROUGH(cmd)
class EcuTasks(Tasks):
"""
ECU Task (same as normal tasks, but return is set to continue by default)
"""
def run(self, cmd, length=None, frame=None):
return EcuTasks.RETURN.TASK_CONTINUE(cmd)
class IsoTpMultiframe(Tasks):
"""
Special task to aggregate an ISO-TP Multiframe request into a single string
before processing the request.
"""
def run(self, cmd, length=None, frame=None):
"""
Compose a ISO-TP Multiframe request. Call it on each request fragment,
passing the standard method parameters, until data is returned.
:param cmd: frame data (excluding header and length)
:param length: decimal value of the length byte of a ISO-TP Multiframe frame
:param frame: can be None (single frame), 0 (First Frame) or > 0 (subsequent frame)
:return:
error = Tasks.TASK.ERROR
incomplete request = Tasks.TASK.INCOMPLETE
complete request = Tasks.TASK.PASSTHROUGH(cmd)
"""
if frame is not None and frame == 0 and length > 0: # First Frame (FF)
if self.frame or self.length:
self.logging.error('Invalid initial frame %s %s', length, cmd)
return Tasks.RETURN.ERROR
self.req = cmd
self.frame = 1
self.length = length
elif (frame is not None and frame > 0 and self.frame == frame and
length is None): # valid Consecutive Frame (CF)
self.req += cmd
self.frame += 1
elif (frame is not None and frame == -1 and self.frame == 16 and
length is None): # valid Consecutive Frame (CF) - 20 after 2F
self.req += cmd
self.frame = 1 # re-cycle the input frame count to 21
elif ((length is None or length > 0) and
frame is None and self.frame is None): # Single Frame (SF)
self.req = cmd
self.length = length
if length:
return Tasks.RETURN.PASSTHROUGH(self.req[:self.length * 2])
else:
return Tasks.RETURN.PASSTHROUGH(self.req)
else:
self.logging.error(
'Invalid consecutive frame %s with data %s, stored frame: %s',
frame, repr(cmd), self.frame)
return Tasks.RETURN.ERROR
# Process Flow Control (FC)
if self.flow_control:
self.flow_control -= 1
else:
if ('cmd_cfc' not in self.emulator.counters or
self.emulator.counters['cmd_cfc'] == 1):
resp = self.emulator.handle_response(
('<flow>' + hex(self.flow_control_end)[2:].upper() +
' 00</flow>'),
do_write=self.do_write,
request_header=self.header,
request_data=cmd)
if not self.do_write:
self.logging.warning("Output data: %s", repr(resp))
self.flow_control = self.flow_control_end - 1
if self.length * 2 <= len(self.req):
self.frame = None
return Tasks.RETURN.PASSTHROUGH(self.req[:self.length * 2])
return Tasks.RETURN.INCOMPLETE
def setup_logging(
default_path=Path(__file__).stem + '.yaml',
default_level=logging.INFO,
env_key=os.path.basename(Path(__file__).stem).upper() + '_LOG_CFG'):
"""
Setup logging facility
:param default_path: logging file pathname
:param default_level: default logging level
:param env_key: default environment variable
:return: (none)
"""
path = default_path
if not os.path.exists(path):
path = os.path.join(
os.path.dirname(Path(__file__)), 'elm.yaml')
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
def is_hex_sp(s):
"""
Validate a string containing hex (in any number, not necessarily
grouped into digit pairs because the header might have three digits),
or spaces, or newlines.
For instance, if containing a PID, it returns True, if containing
ST or AT commands, it returns False.
:param s: string to validate
:return: True if matching, otherwise False
"""
return re.match(r"^[0-9a-fA-F \t\r\n]*$", s or "") is not None
def len_hex(s):
"""
Check that the argument string is hexadecimal (digit pairs). If not,
return False. If hex, return the number of hex bytes (digit pairs).
:param s: hex string
:return: either the number of hex bytes (0 or more bytes) or False (invalid
digit, or digits not grouped into pairs).
"""
try:
return len(bytearray.fromhex(s))
except Exception:
return False
class Elm:
"""
Main class of the ELM327-emulator
"""
class THREAD:
"""
Possible states for the Context Manager thread
"""
STOPPED = 0
STARTING = 1
ACTIVE = 2
PAUSED = 3
TERMINATED = 4
def sequence(self, pid, base, max, factor, n_bytes):
"""
Generate a hex data string of n_bytes based on the number of times
a PID is called (counter, possibly weighted with choice_weights
if "Choice" is SEQUENTIAL) and using the following formula:
returned value = factor * ( counter % (max * 2) ) + base
:param pid: string including the PID name in ObdMessage
:param base: minimum value (to be added to the formula)
:param max: capping value for the counter
:param factor: multiplier of the counter capped value
:param n_bytes: length of the generated hex data string
:return: hex data string
"""
# get the number of times a pid has been called
c = self.counters[pid] if pid in self.counters else 0
if self.choice_mode == self.Choice.SEQUENTIAL:
c = c / self.choice_weights[0]
# compute the new value [= factor * ( counter % (max * 2) ) + base]
p = int(factor * abs(max - (c + max) % (max * 2))) + base
# get its hex string
s = ("%.X" % p).zfill(n_bytes * 2)
# space the string into chunks of two bytes
return " ".join(s[i:i + 2] for i in range(0, len(s), 2))
def reset(self, sleep):
"""
Return all settings to their defaults.
Called by __init__(), ATZ and ATD.
"""
logging.debug("Resetting counters and sleeping for %s seconds", sleep)
time.sleep(sleep)
for i in [k for k in self.counters if k.startswith('cmd_')]:
del (self.counters[i])
self.counters['ELM_PIDS_A'] = 0
self.counters['ELM_MIDS_A'] = 0
self.counters['cmd_echo'] = not self.no_echo
self.counters['cmd_set_header'] = ECU_ADDR_E.upper()
self.counters['cmd_version'] = self.version
self.counters.update(self.presets)
def set_defaults(self):
"""
Called by __init__() and terminate()
"""
self.scenario = 'default'
self.interbyte_out_delay = 0 # seconds - UDS P1 timer - Inter byte time for ECU response
self.delay = 0 # seconds - UDS P2 timer - Time between tester request and ECU response or two ECU responses
self.multiframe_timer = 5 # seconds - UDS P3 Timer - Time between end of ECU responses and start of new tester request
self.max_req_timeout = 1440 # seconds - UDS P4 timer - Inter byte time for tester request (ref. req_timeout counter)
self.answer = {}
self.counters = {}
self.counters.update(self.presets)
if hasattr(self, "tasks"):
for ecu in self.tasks:
for i in reversed(self.tasks[ecu]):
logging.debug(
'Stopping task "%s", ECU="%s", '
'method=stop()',
i.__module__,
ecu)
try: # Run the stop() method
i.stop(None)
except Exception as e:
logging.critical(
'Error while stopping task "%s", ECU="%s", '
'method=stop(): %s',
i.__module__,
ecu,
e, exc_info=True)
self.tasks = {}
if hasattr(self, "task_shared_ns"):
for ecu in self.task_shared_ns:
logging.debug(
'Stopping ECU task "%s", ECU="%s", '
'method=stop()',
self.task_shared_ns[ecu].__module__,
ecu)
try: # Run the stop() method
self.task_shared_ns[ecu].stop(None)
except Exception as e:
logging.critical(
'Error while stopping ECU task "%s", ECU="%s", '
'method=stop(): %s',
self.task_shared_ns[ecu].__module__,
ecu,
e, exc_info=True)
self.task_shared_ns = {}
self.shared = None
def set_sorted_obd_msg(self, scenario=None):
"""
Concatenate the appropriate subdictionaries according to "scenario".
Manage priority by sorting the obtained dictionary.
Check how ObdMessage dictionary is built: if it includes the "default"
and 'AT' subdictionaries (they should be there if using the default
ObdMessage), use them, otherwise only the subdictionary of the selected
scenario is used.
:param scenario: when set, it changes the scenario
:return: (none)
"""
if scenario is not None:
self.scenario = scenario
if 'default' in self.ObdMessage and 'AT' in self.ObdMessage:
# Perform a union of the three subdictionaries
self.sortedOBDMsg = {
**self.ObdMessage['default'], # highest priority
**self.ObdMessage['AT'],
**self.ObdMessage[self.scenario]
# lowest priority ('Priority' to be checked)
}
else:
self.sortedOBDMsg = {**self.ObdMessage[self.scenario]}
# Add 'Priority' to all pids and sort basing on priority (highest = 1, lowest=10)
self.sortedOBDMsg = sorted(
self.sortedOBDMsg.items(),
key=lambda x: x[1]['Priority'] if 'Priority' in x[1] else 10)
def __init__(
self,
batch_mode=False,
newline=False,
no_echo=False,
serial_port=None,
device_port=None,
serial_baudrate="",
net_port=None,
forward_net_host=None,
forward_net_port=None,
forward_serial_port=None,
forward_serial_baudrate=None,
forward_timeout=None):
self.version = ELM_VERSION
self.header_version = ELM_HEADER_VERSION
self.presets = {}
self.ObdMessage = ObdMessage
self.ELM_R_UNKNOWN = ELM_R_UNKNOWN
self.set_defaults()
self.set_sorted_obd_msg()
self.batch_mode = batch_mode
self.newline = newline
self.no_echo = no_echo
self.serial_port = serial_port
self.device_port = device_port
self.serial_baudrate = serial_baudrate
self.net_port = net_port
self.forward_net_host = forward_net_host
self.forward_net_port = forward_net_port
self.forward_serial_port = forward_serial_port
self.forward_serial_baudrate = forward_serial_baudrate
self.forward_timeout = forward_timeout
self.reset(0)
self.slave_name = None # pty port name, if pty is used
self.master_fd = None # pty port FD, if pty is used, or device com port FD (IO)
self.slave_fd = None # pty side used by the client application
self.serial_fd = None # serial COM port file descriptor (pySerial)
self.sock_inet = None
self.fw_sock_inet = None
self.fw_serial_fd = None
self.sock_conn = None
self.sock_addr = None
self.thread = None
self.plugins = {}
self.request_timer = {}
self.choice_mode = self.Choice.SEQUENTIAL
self.choice_weights = [1]
class Choice(Enum):
SEQUENTIAL = 0
RANDOM = 1
def __enter__(self):
# start the read thread
self.threadState = self.THREAD.STARTING
self.thread = threading.Thread(target=self.run)
self.thread.daemon = True
self.thread.start()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.terminate()
return False # don't suppress any exceptions
def terminate(self):
"""
Termination procedure.
"""
logging.debug("Start termination procedure.")
if (self.thread and
self.threadState != self.THREAD.STOPPED and
self.threadState != self.THREAD.TERMINATED):
time.sleep(0.1)
try:
self.thread.join(1)
except:
logging.debug("Cannot join current thread.")
self.thread = None
self.threadState = self.THREAD.TERMINATED
try:
if self.slave_fd:
os.close(self.slave_fd)
if self.master_fd: # pty or device
thread = threading.Thread(
target=os.close, args=(self.master_fd,))
thread.start()
thread.join(1)
if thread.is_alive():
logging.critical(
'Cannot close file descriptor. '
'Forcing program termination.')
os._exit(5)
if self.serial_fd: # serial COM - pySerial
self.reset_input_buffer()
self.reset_output_buffer()
self.serial_fd.close()
if self.sock_inet:
self.sock_inet.shutdown(socket.SHUT_RDWR)
self.sock_inet.close()
except:
logging.debug("Cannot close file descriptors.")
self.set_defaults()
logging.debug("Terminated.")
return True
def socket_server(self):
"""
Create an INET, STREAMing socket
Set self.sock_inet
"""
if self.sock_inet:
self.sock_inet.shutdown(socket.SHUT_RDWR)
self.sock_inet.close()
self.sock_conn = None
self.sock_addr = None
errmsg = "Unknown error"
HOST = "0.0.0.0"
for res in socket.getaddrinfo(HOST, self.net_port,
socket.AF_UNSPEC,
socket.SOCK_STREAM, 0,
socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
self.sock_inet = socket.socket(af, socktype, proto)
self.sock_inet.setsockopt(
socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock_inet.setsockopt(
socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except OSError as msg:
errmsg = msg
self.sock_inet = None
continue
try:
# Bind the socket to the port
self.sock_inet.bind((NETWORK_INTERFACES, self.net_port))
# Become a socket server and listen for incoming connections
self.sock_inet.listen(1)
except OSError as msg:
errmsg = msg
self.sock_inet.close()
self.sock_inet = None
continue
break
if self.sock_inet is None:
logging.error(
"Local socket %s creation failed: %s.",
self.net_port, errmsg)
return False
return True
def connect_serial(self):
"""
Shall be called after get_pty() and before a read operation.
It opens the serial port, if not yet opened.
It is expected to be blocking.
Returns True if the serial or pty port is opened,
or None in case of error.
"""
# if the port is already opened, return True...
if self.slave_name or self.master_fd or self.serial_fd:
return True
# else open the port
if self.device_port: # os IO
try:
self.master_fd = os.open(
self.device_port,
os.O_RDWR | os.O_NOCTTY | os.O_SYNC)
except Exception as e:
logging.critical("Error while opening device %s:\n%s",
repr(self.device_port), e)
return None
return True
elif self.serial_port: # pySerial COM
try:
self.serial_fd = serial.Serial(
port=self.serial_port,
baudrate=self.serial_baudrate or SERIAL_BAUDRATE)
self.slave_name = self.get_port_name(extended=True)
except Exception as e:
logging.critical("Error while opening serial COM %s:\n%s",
repr(self.serial_port), e)
return None
return True
else:
return False
def get_pty(self):
"""
Return the opened pty port, or None if the pty port
cannot be opened (non UNIX system).
In case of UNIX system and if the port is not yet opened, open it.
It is not blocking.
"""
# if the port is already opened, return the port name...
if self.slave_name:
return self.slave_name
elif self.master_fd and self.device_port:
return self.device_port
elif self.serial_fd and self.serial_port:
return self.serial_port
elif self.master_fd:
logging.critical("Internal error, no configured device port.")
return None
elif self.serial_fd:
logging.critical("Internal error, no configured COM port.")
return None
# ...else, with a UNIX system, make a new pty
self.slave_fd = None
if os.name == 'nt':
self.slave_fd = None
return None
else:
if not self.device_port and not self.serial_port:
self.master_fd, self.slave_fd = pty.openpty()
tty.setraw(self.slave_fd)
self.slave_name = os.ttyname(self.slave_fd)
logging.debug("Pty name: %s", self.slave_name)
return self.slave_name
def choice(self, values):
"""
Select one of the values in the list argument according to the adopted
method, which can be sequential or random.
:param values: list of possible values
:return: selected value
"""
if not isinstance(values, (list, tuple)):
logging.error(
'Invalid usage of "choice" function, which needs a list.')
return ""
if self.choice_mode == self.Choice.RANDOM:
len_weights = len(self.choice_weights)
len_values = len(values)
return choices(values, [self.choice_weights[i] if i < len_weights
else 1
for i in range(len_values)])[0]
elif self.choice_mode == self.Choice.SEQUENTIAL:
if "cmd_last_pid" not in self.counters:
logging.error(
'Internal error - Invalid choice usage; '
'missing "cmd_last_pid" counter.')
return (
values[int((self.counters[self.counters["cmd_last_pid"]] - 1) /
self.choice_weights[0]) % len(values)])
else:
logging.error(
"Internal error - Invalid choice mode.")
def run(self): # daemon thread
"""
This is the core method.
Can be run directly (in-process) or by the Context Manager within
a thread: ref. __enter__()
No return code.
"""
setup_logging()
self.logger = logging.getLogger()
if self.net_port:
if not self.socket_server():
logging.critical("Net connection failed.")
self.terminate()
return False
else:
if (not self.device_port and
not self.serial_port and
not self.get_pty()):
if os.name == 'nt':
logging.critical("Invalid setting for Windows.")
else:
logging.critical("Pseudo-tty port connection failed.")
self.terminate()
return False
if self.sock_inet:
if self.net_port:
msg = 'at ' + self.get_port_name()
else:
msg = 'with no open TCP/IP port.'
else:
msg = 'on ' + self.get_port_name()
if self.batch_mode:
logging.debug(
'ELM327 OBD-II adapter emulator v%s started '
'%s_______________', __version__, msg)
else:
logging.info(
'\n\nELM327 OBD-II adapter emulator v%s started '
'%s\n', __version__, msg)
""" the ELM's main IO loop """
# Load and validate plugins
self.plugins = {
name: importlib.import_module(PLUGIN_DIR + "." + name)
for finder, name, ispkg
in pkgutil.iter_modules(
importlib.import_module(PLUGIN_DIR).__path__)
if name.startswith('task_')
}
remove = []
for k, v in self.plugins.items():
if (not (hasattr(v, "Task")) or
not inspect.isclass(v.Task)):
logging.critical(
"Task class not available in plugin %s", k)
remove += [k]
continue
for k in remove:
del self.plugins[k]
self.threadState = self.THREAD.ACTIVE
while (self.threadState != self.THREAD.STOPPED and
self.threadState != self.THREAD.TERMINATED):
if self.threadState == self.THREAD.PAUSED:
time.sleep(0.1)
continue
# get the latest request
self.cmd = self.normalized_read_line()
if (self.threadState == self.THREAD.STOPPED or
self.threadState == self.THREAD.TERMINATED):
return True
if self.cmd is None:
continue
# process 'fast' option (command repetition)
if re.match('^ *$', self.cmd) and "cmd_last_cmd" in self.counters:
self.cmd = self.counters["cmd_last_cmd"]
logging.debug("repeating previous command: %s", repr(self.cmd))
else:
self.counters["cmd_last_cmd"] = self.cmd
logging.debug("Received %s", repr(self.cmd))
# if the request includes valid data, handle it
if re.match(ELM_VALID_CHARS, self.cmd):
try:
request_header, request_data, resp = self.handle_request(
self.cmd, do_write=True)
except Exception as e:
logging.critical("Error while processing %s:\n%s\n%s",
repr(self.cmd), e, traceback.format_exc())
continue
if resp is not None:
self.handle_response(
resp,
do_write=True,
request_header=request_header,
request_data=request_data)
else:
logging.warning("Invalid request: %s", repr(self.cmd))
return True
def accept_connection(self):
"""
Perform the "accept" socket method of an INET connection.
Return when a connection is accepted.
:return: True if a connection is accepted. False if error.
"""
if self.sock_conn is None or self.sock_addr is None:
# Accept network connections
try:
logging.debug(
"Waiting for connection at %s", self.get_port_name())
(self.sock_conn, self.sock_addr) = self.sock_inet.accept()
except OSError as msg:
if msg.errno == errno.EINVAL: # [Errno 22] invalid argument
return False
logging.error("Failed accepting connection: %s", msg)
return False
logging.debug("Connected by %s", self.sock_addr)
return True
def serial_client(self):
"""
Internally used by send_receive_forward().
Open the forwarded port if serial mode is used..
:return: True when successfully opened, otherwise False
"""
if self.fw_serial_fd:
return True
try:
self.fw_serial_fd = serial.Serial(
port=self.forward_serial_port,
baudrate=int(self.forward_serial_baudrate)
if self.forward_serial_baudrate else SERIAL_BAUDRATE,
timeout=self.forward_timeout or FORWARD_READ_TIMEOUT)
return True
except Exception as e:
logging.error('Cannot open forward port: %s', e)
return False
def net_client(self):
"""
Internally used by send_receive_forward()
Open a socket connection if socket mode is used.
:return: (not really used)
"""
if (self.fw_sock_inet
or self.forward_net_host is None
or self.forward_net_port is None):
return False
s = None
for res in socket.getaddrinfo(
self.forward_net_host, self.forward_net_port,
socket.AF_UNSPEC, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
self.sock_inet.setsockopt(
socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock_inet.setsockopt(
socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except OSError as msg:
s = None
continue
try:
s.connect(sa)
s.settimeout(self.forward_timeout or FORWARD_READ_TIMEOUT)
except OSError as msg:
s.close()
s = None
continue
break
if s is None:
logging.critical(
"Cannot connect to host %s with port %s",
self.forward_net_host, self.forward_net_port)
self.terminate()
return False
self.fw_sock_inet = s
return True
def send_receive_forward(self, i):
"""
If a forwarder is active, send data if it is not None
and try receiving data until a timeout.
Then received data are logged and returned.
return False: no connection
return None: no data
return data: decoded string
"""
if self.forward_serial_port:
if self.fw_serial_fd is None:
if not self.serial_client():
return False
if self.fw_serial_fd:
if i:
self.fw_serial_fd.write(i)
logging.info(
"Write forward data: %s", repr(i))
proxy_data = self.fw_serial_fd.read(1024)
logging.info(
"Read forward data: %s", repr(proxy_data))
return repr(proxy_data)
return False
if not self.forward_net_host or not self.forward_net_port:
return False
if self.fw_sock_inet is None:
self.net_client()
if self.fw_sock_inet:
if i:
try:
self.fw_sock_inet.sendall(i)
logging.info(
"Write forward data: %s", repr(i))
except BrokenPipeError:
logging.error(
"The network link of the OBDII interface dropped.")
try:
proxy_data = self.fw_sock_inet.recv(1024)
logging.info(
"Read forward data: %s", repr(proxy_data))
return proxy_data.decode("utf-8", "ignore")
except socket.timeout:
logging.info(
"No forward data received.")