ELM327-emulator

A Python emulator of the ELM327 OBD-II adapter connected to a vehicle supporting multi-ECU simulation.
ELM327-emulator connects client applications to multiple emulated ECUs via OBD-II interface through different networking systems, including serial communication (where pseudo-terminals are used if supported by the operating systems), or direct interaction with communication devices, or TCP/IP, or Bluetooth. Besides emulating the ELM327 adapter, it can also emulate the diagnostic bus itself, exposing a CAN interface running the SLCAN (Lawicel) firmware or a K-Line ECU (ISO 9141-2 / ISO 14230), so that applications driving a CANable or a VAG KKL adapter can talk to the emulated ECUs. The software simulates an ELM327 adapter connected to a vehicle, includes a command-line interface for extensive monitoring and offers a documented Python development framework to implement ECU emulation objects.
ELM327-emulator is able to support basic ELM327 commands and OBD service requests through stateless request/response method via OBD-II, but can also handle stateful UDS communication with ISO-TP Flow Control and Keyword Protocol 2000, concurrently emulating multiple ECUs. It is designed to be extended via a plugin architecture to allow easy development of specific tasks implementing workflows, including the possibility to simulate anomalies for testing purposes. Many AT commands are supported, as well as some OBDLink AT/ST commands. Diagnostic Trouble Codes (modes 03, 07 and 0A) can be simulated, a mode 01 request can carry multiple PIDs, and requests sent to the functional address (7DF or 18DB33F1) are answered by the emulated ECUs.
ELM327-emulator supports different operating systems including Windows, macOS and UNIX/Linux; it is agnostic of the client application and has been tested with python-OBD as well as with many applications on Windows, Linux and on smartphone devices.
An internal dictionary (named ObdMessage) allows configuring the emulation, which is currently set to reproduce the message flow generated by more ECUs, including the basic communication of a Toyota Auris Hybrid car (through the scenario car option) and can be easily extended to simulate communication produced by other vehicles or ECUs. In case of more complex interactions (e.g., entering privileged diagnostic sessions and performing reset or flash upload operations), the dictionary can instance tasks, which are implemented through plugins, very simple to be developed by users extending the software. Some example of plugins is already included.
ELM327-emulator also offers a feature that compares the emulation with the direct connection of an OBD-II adapter to allow extending the dictionary by reporting unmatched requests. In addition, it provides an auxiliary scanning tool (obd_dictionary) that builds the ObdMessage dictionary of a specific vehicle by automatically querying all standard OBD service requests one by one (as well as querying additional custom PIDs specified by the user via CSV file); the dictionary can then be used to emulate stateless request/responses of a specific car or ECU.
Installation
Check that the Python version is 3.6 or higher (python3 -V), then install ELM327-emulator with the following command:
python3 -m pip install ELM327-emulator
This is enough to run the software.
Prerequisite components: pyyaml, obd and pyserial; in addition, on non Windows systems python-daemon and lockfile (used for the PID lock file of the daemon mode) and with Windows pyreadline3. All needed prerequisites are automatically installed with the package. On macOS, the optional pyobjc-framework-IOBluetooth component is required by the native Bluetooth interface (-w) and can be installed with python3 -m pip install "ELM327-emulator[bluetooth]".
obd (python-OBD) is needed for obd_dictionary. It is better to use an updated version of python-OBD package (e.g., the one installed from GitHub with python3 -m pip install --upgrade git+https://github.com/brendan-w/python-OBD.git).
Alternatively to the above mentioned installation method, the following steps allow installing the latest version from GitHub.
-
Optional preliminary configuration with Ubuntu (if not already done):
sudo apt-get update
sudo apt-get -y upgrade
sudo add-apt-repository universe # this is only needed if "sudo apt install python3-pip" fails
sudo apt-get update
sudo apt install -y python3-pip
python3 -m pip install --upgrade pip
sudo apt install -y git
-
Optional preliminary configuration with Windows:
- install the latest version of Python (also available from Microsoft Store);
- if you want to install ELM327-emulator from GitHub, install git from Git-scm or using the Git for Windows installer;
- if the interface to use is a serial COM port (
-p), also install com0com (no installation is needed when using the TCP/IP -n interface, the native Bluetooth -w one, or the OS device -P one);
- optionally, check that PIP is upgraded (
python3 -m pip install --upgrade pip).
-
Run this command:
python3 -m pip install git+https://github.com/ircama/ELM327-emulator
To uninstall:
python3 -m pip uninstall -y ELM327-emulator
Basic use
The emulator allows batch and interactive mode. The latter is the default and can be executed as follows:
python3 -m elm
or simply:
elm
After starting the program, the emulator is ready to use.
To enable the preconfigured set of OBD service requests of a Toyota Auris Hybrid car, enter scenario car (or, alternatively, run the emulator with the -s car option, i.e python3 -m elm -s car).
By default, ELM327-emulator uses serial communication. The external application interfacing the emulator just needs to connect to the virtual device shown by the emulator and interact with the vehicle as if it was accessing a real ELM327 adapter.
Alternatively to the serial communication, ELM327-emulator supports TCP/IP networking through the -n option, followed by the port number (wich in most cases is 35000). Example:
python3 -m elm -n 35000
All subsequent information is not needed for basic usage of the tool and allows mastering ELM327-emulator, exploiting it to test specific features including the simulation of communication exceptions, which are not always easy to be reproduced with a real link.
Running the pre-built executable program
The elm327-emulator.zip archive in the Releases folder incudes the elm327-emulator.exe executable asset; the ZIP archive is auto-generated by a GitHub Action. elm327-emulator.exe is a Windows application that can be directly executed.
Compatibility
ELM327-emulator has been tested with Python 3.6, 3.7, 3.8, 3.9, 3.10, 3.11, 3.12, 3.13 and 3.14. Previous Python versions are not supported.
When using serial communication, with UNIX/Linux OSs, this code uses pty pseudo-terminals. With Windows, you should first install com0com (a kernel-mode virtual serial port driver), or other virtual serial port software; alternatively, cygwin and Windows Subsystem for Linux (WSL) are supported.
Note. com0com is only required by the serial COM port interface (option -p): a virtual serial port pair cannot be created from Python because Windows provides no user-mode pseudo-terminal facility and a COMx device requires a kernel-mode driver. The TCP/IP interface (option -n) and the native Bluetooth interface (option -w) need no driver at all, so they can be used on Windows without com0com; refer to Running on Windows and Usage of native Bluetooth (SPP).
Usage
The description of the ELM327-emulator command-line option is the following:
usage: elm [-h] [-V] [-e] [-l] [-t] [-d] [-b FILE] [-p PORT] [-P DEVICE_PORT] [-w [NAME]] [-k CHANNEL] [-c PORT] [-K PORT] [-a BAUDRATE]
[-v LOG] [-s SCENARIO] [-n INET_PORT] [-i INTERFACE] [-H INET_FORWARD_HOST] [-N INET_FORWARD_PORT]
[-S FORWARD_SERIAL_PORT] [-B FORWARD_SERIAL_BAUDRATE] [-T FORWARD_TIMEOUT]
optional arguments:
-h, --help show this help message and exit
-V, --version Print ELM327-emulator version and exit
-e, --no-echo Disable echo by default
-l, --newline Use newline (<NL>) instead of carriage return <CR> for detecting a line separator
-t, --terminate Terminate the daemon process sending SIGTERM
-d, --daemon Run ELM327-emulator in daemon mode.
-b FILE, --batch FILE
Run ELM327-emulator in batch mode. Argument is the output file. The first line in that file will be the virtual
serial device
-p PORT, --port PORT Set a serial communication port instead of using a pseudo-tty.
-P DEVICE_PORT, --device DEVICE_PORT
Set the communication device to be opened instead of using a pseudo-tty port.
-w [NAME], --bluetooth [NAME]
Use a native Bluetooth RFCOMM/SPP port instead of a serial port or a pseudo-tty (no virtual serial port driver,
such as com0com, is needed). The optional argument is the advertised Bluetooth service name (default: ELM327).
-k CHANNEL, --bt_channel CHANNEL
Set the RFCOMM channel used by the native Bluetooth SPP server (default: 1; a free channel is selected
automatically when the requested one is unavailable).
-c PORT, --slcan PORT
Emulate a CAN interface running the SLCAN (Lawicel) firmware on the given serial port, instead of the ELM327
protocol: the connected CAN application exchanges CAN frames with the emulated ECUs of the selected scenario.
Use a virtual serial port pair (e.g. com0com) or a pseudo-tty.
-K PORT, --kline PORT
Emulate an ECU connected to a K-Line interface (a VAG KKL or similar serial K-Line adapter) on the given serial
port, instead of the ELM327 protocol: the connected application drives the K-Line directly (ISO 9141-2 /
ISO 14230) and the emulated ECUs answer the OBD-II requests found on the line. Use a virtual serial port pair
(e.g. com0com) or a pseudo-tty.
-a BAUDRATE, --baudrate BAUDRATE
Set the serial device baud rate used by ELM327-emulator.
-v LOG, --log LOG Preset a log level in interactive mode.
-s SCENARIO, --scenario SCENARIO
Set the scenario used by ELM327-emulator.
-n INET_PORT, --net INET_PORT
Set the INET socket port used by ELM327-emulator.
-i INTERFACE, --interface INTERFACE
Set the local network interface address used by the TCP/IP server (option -n). It defaults to 127.0.0.1,
so that only applications running on this host can connect; use 0.0.0.0 (IPv4) or :: (IPv6) to accept
connections from other devices on the network.
-H INET_FORWARD_HOST, --forward_host INET_FORWARD_HOST
Set the INET host used by ELM327-emulator.when forwarding the client interaction to a remote OBD-II port.
-N INET_FORWARD_PORT, --forward_port INET_FORWARD_PORT
Set the INET socket port used by ELM327-emulator when forwarding the client interaction to a remote OBD-II port.
-S FORWARD_SERIAL_PORT, --forward_serial_port FORWARD_SERIAL_PORT
Set the serial device port used by ELM327-emulator when forwarding the client interaction to a serial device.
-B FORWARD_SERIAL_BAUDRATE, --forward_serial_baudrate FORWARD_SERIAL_BAUDRATE
Set the device baud rate used by ELM327-emulator when forwarding the client interaction to a serial device.
-T FORWARD_TIMEOUT, --forward_timeout FORWARD_TIMEOUT
Set forward timeout as floating number (default is 5 seconds).
ELM327-emulator v4.0.0 - ELM327 OBD-II adapter emulator
Description
The communication port to be used by the application interfacing the emulator is displayed when starting the program. E.g. on UNIX/Linux:
ELM327-emulator is running on /dev/pts/0
When running on Windows with the serial COM port interface, the following message is shown:
ELM327-emulator is running on com0com serial port pair reading from COM3
When using the native Bluetooth interface, the RFCOMM channel to be configured in the client application is reported as well:
ELM327-emulator is running on Bluetooth RFCOMM/SPP server 'ELM327' on channel 5 (adapter 00:11:22:33:44:55).
Embedded dictionary of AT Commands and OBD service requests
A dictionary named ObdMessage is used to define commands and PIDs. The dictionary includes more sections (named scenarios):
'AT': set of default AT and ST commands
'default': set of default PIDs
'car': PIDs of a Toyota Auris Hybrid vehicle
'mt05': basic set of PIDs of an MT05 ECU from Delphi used in many motorbikes and ATV’s
- any additional custom section can be used to define specific scenarios
Default settings include both the ‘AT’ and the ‘default’ scenarios.
The dictionary used to parse each ELM command is dynamically built as a union of three defined scenarios in the following order: ‘default’, ‘AT’, custom scenario (when applied). Each subsequent scenario redefines the commands of the previous scenarios. In principle, ‘AT’ scenario is added to ‘default’ and, if a custom scenario is used, this is also added on top, and all equal keys are replaced. Then the Priority key defines the precedence to match elements.
If a custom scenario is selected through the scenario command, any key defined in the custom scenario replaces the default settings (‘AT’ and ‘default’ scenarios).
The key used in the dictionary consists of a unique identifier for each PID. Allowed case-insensitive values for each key (PID):
'Request': received data; a regular expression can be used
'Descr': string describing the PID
'Exec': command to be executed
'Log': logging.debug argument
'Info': logging.info argument
'Warning': logging.warning argument
'ResponseFooter': run a function and returns a footer to the response (a lambda function can be used)
'ResponseHeader': run a function and returns a header to the response (a lambda function can be used)
'Response': returned data; can be a string, or a list/tuple of strings; if more strings are included (e.g., if a tuple or a list is used), the emulator selects one of them each time, according to the criteria defined by the choose command, which can be either sequential (default) or random.
'Action': can be set to ‘skip’ in order to skip the processing of the PID
'Header': if set, process the command only if the corresponding header (CAN ID) matches
'Priority'=number: when set, the key has higher priority than the default (highest number = 1, lowest = 10 = default)
'Task': if set, the related header/request activates a specific task referring to an installed plugin.
The emulator provides a monitoring front-end, supporting commands and controlling the backend thread which executes the actual process.
Built-in keywords
At the CMD> prompt, the emulator accepts the commands described in the following table.
| Command |
Description |
help |
List available commands (or detailed help with “help cmd”). |
port |
Print the used TCP/IP port, or the used device, or the serial COM port, or the serial pseudo-tty, depending on the selected interface. |
test |
Test the OBD-II request specified in the argument. Check also “verify” and “write”. The autocompletion (by pressing or double-pressing TAB) allows prompting all defined OBD-II requests (PIDs). |
write |
Write the formatted XML response specified in the argument to the connected application. The ASCII null character is represented as \x00 (Use “verify” to avoid the write operation.) |
verify |
Test the processing of the formatted XML response specified in the argument (like “write”, but without writing to the application). The ASCII null character is represented as \x00. |
loglevel |
If an argument is given, set the logging level, otherwise show the current one. Valid numbers or words: CRITICAL=50, ERROR=40, WARNING=30, INFO=20, DEBUG=10. The autocompletion (by pressing or double-pressing TAB) allows prompting all available values. |
quit |
quit the program (or end-of-file/Control-D, or break/Control-C) |
counters |
print the number of each executed PIDs (upper case names), the values associated to some ‘AT’ PIDs (cmd_…), the unknown requests, the emulator response delay, the total number of executed commands (commands) and the current scenario (scenario). The related dictionary is emulator.counters. |
edit |
Edit a PID answer. Arguments: PID, position, replaced bytes. If only the PID is given, remove a previous editing. |
tasks |
Print all available plugins; for each used ECU, print all active tasks and dump related namespaces; dump also the shared namespaces. |
pause |
pause the execution. (Related attribute is emulator.threadState = emulator.THREAD.PAUSED.) |
prompt |
toggle prompt off/on if no argument is used, or change the prompt if using an argument |
resume |
resume the execution after pausing; also prints the used device. (Related attribute is emulator.threadState = emulator.THREAD.ACTIVE) |
delay <n> |
delay each emulator response of <n> seconds (floating-point number; default is 0.5 seconds) |
wait <n> |
delay the execution of the next command of <n> seconds (floating-point number; default is 10 seconds) |
timer [<name> <value>] |
Print or set the UDS timers P1, P2, P3, P4. The first argument is the timer name, the second is the value in seconds. Without arguments, print all timer values. Decimals are allowed. |
engineoff |
switch to engineoff scenario |
scenario <scenario> |
switch to <scenario> scenario; if the scenario is missing or invalid, defaults to 'car'. The autocompletion (by pressing or double-pressing TAB) allows prompting all compatible scenarios. defined in emulator.ObdMessage. (Related attribute is emulator.scenario.) |
default |
reset to default scenario |
reset |
reset the emulator (counters and variables) |
color |
toggle usage of colors off/on |
history [<n>] |
print the last 20 items of the command history; if an argument is given, print the last n items in the history; with argument clear, clear the history. The command history is permanently saved to file .ELM327_emulator_history within the home directory. |
merge <module> |
import a scenario from an external module and merges it with the emulator configuration. <module> shall be a Python file including the ObdMessage dictionary (e.g., generated by obd_dictionary) without .py extension (notice that the physical file shall be in the current directory and shall end with .py). The autocompletion allows prompting all compatible files in the current directory (type merge, then press space, then press TAB). After a successful merge, the new scenario can be activated through the scenario command. |
version |
Print ELM327-emulator version. With an argument, set the ELM version. If the argument is hexheader followed by a sequence of hex digits, the header of the ELM version is updated with the sequence. If the argument is reset, header and ELM version strings are set to default values. The autocompletion can be used with this command. |
commands |
List the description of each available command. |
choice |
Print or select the adopted method to choose the return value of answers that are expressed as a list of data. Possible values are “sequential” (the returned value follows the list sequence, which is the default mode) or “random” (the returned value is randomly selected within the values in the list). Optional list of weights can be added; decimals are allowed; the default value is 1. Autocompletion is allowed for this command. |
usage |
Open a web browser showing this documentation. |
In addition to the previously listed keywords, any Python command is allowed to query/configure the backend thread.
Examples of usage of the choice command:
# Use sequential mode with default weight:
choice SEQUENTIAL
# Use random mode with default weight:
choice RANDOM
# Use sequential mode with weight 30 (each step occurs after 30 requests):
choice SEQUENTIAL 10
# Use sequential mode with weights [10, 1, 0.5].
# Digits represent the relative probability of respective values in the "Response" list.
# Missing weights are replaced with 1. In the example,
# the first value in the list is 10 times more likely to be selected than the second,
# which is twice the third; this third is half the fourth and all the subsequent values.
choice RANDOM 10 1 0.5
At the command prompt, cursors and keyboard shortcuts are allowed. Autocompletion (via TAB key) is active for all previously described commands and also allows Python keywords and namespaces (built-ins, self and global). If the autocompletion matches a single item, this is immediately expanded; Conversely, if more possibilities are matched, none of them is returned, but pressing TAB again a list of available options is displayed.
Testing OBD-II requests
ELM327-emulator allows testing OBD-II requests through the test command directly via the command line, like in this example, where the ‘010C’ pid is tested:
python3 -m elm -s car
test 010c
test ath1
test 010c
The autocompletion is allowed for the argument, to prompt and select values (PIDs) defined in the dictionary.
The answer (Command output) will be 41 0C 13 FB \r\r>, OK\r\r>, 7E8 04 41 0C 09 F6 \r\r>, which will reflect what ELM327-emulator returns to a real OBD-II application.
Diagnostic Trouble Codes (DTCs)
The car scenario emulates the DTCs stored in the DTC_STORED, DTC_PENDING and DTC_PERMANENT variables of obd_message.py, which are empty by default (no fault is stored and the MIL is off, as reported by PID 0101).
Add the DTCs to be simulated, to test how an application manages them:
DTC_STORED = ['0143', '0196', '0234'] # mode 03 (stored DTCs, e.g. P0143)
DTC_PENDING = ['0300'] # mode 07 (pending DTCs)
DTC_PERMANENT = ['0420'] # mode 0A (permanent DTCs)
The related requests are answered with the ISO-TP single or multiple frame encoding:
test ath1
test 03
# '7E8 10 09 43 01 43 01 96 02 \r7E8 21 34 04 20 00 00 00 00 \r\r>'
A mode 04 request (Clear DTC) clears the DTC lists, so that subsequent mode 03, 07 and 0A requests answer the “no DTC” response (43 00, 47 00 and 4A 00); ATZ or ATD restore the configured DTCs.
Multiple PIDs in a single request
The car scenario supports mode 01 requests including up to six PIDs (ref. SAE J1979), like 010C0D0110, returning the data of every supported PID in a single ISO-TP response (multiple CAN frames when the answer is longer than 7 bytes):
test ath1
test 010C0D
# '7E8 06 41 0C 13 FB 0D 5C \r\r>'
test 010C0D0110
# '7E8 10 0E 41 0C 13 FB 0D 5C \r7E8 21 01 00 07 A1 00 10 11 \r7E8 22 5B \r\r>'
Requests including more than six PIDs are not answered (they are not compliant with SAE J1979).
Requests to the functional address
Requests sent to the functional (broadcast) address (ATSH 7DF, or 18DB33F1 for 29 bit CAN) are answered by the entries of every ECU defined in the scenario, even when they are related to a physical address; the response includes the address of the answering ECU (e.g. 7E8 for the engine ECU).
test atsh 7df
test 0100
# '7E8 06 41 00 BE 3F A8 13 \r\r>'
Special setters
The counters starting with cmd_… are special setters. They are represented in the following table and store data related to AT/ST commands.
| Special setter |
Related AT/ST command |
Handled |
Description |
PID |
cmd_echo |
ATE0, ATE1 |
Yes |
Echo off or on |
AT_ECHO |
cmd_linefeeds |
ATL0, ATL1 |
Yes |
Linefeeds off or on |
AT_LINEFEEDS |
cmd_spaces |
ATS0, ATS1 |
Yes |
Spaces off or on |
AT_SPACES |
cmd_set_header |
ATSH |
Yes |
Set the request header |
AT_SET_HEADER |
cmd_use_header |
ATH0, ATH1 |
Yes |
Headers off or on |
AT_USE_HEADERS |
cmd_last_cmd |
|
Yes |
Last executed request |
(ref. cmd_last_pid) |
cmd_last_pid |
(ref. cmd_last_cmd) |
Yes |
Label of the last used PID |
(last PID) |
cmd_cra |
ATCRAx (x=hex digit) |
Yes |
Set SET CAN Receive address filter argument |
AT_SET_CAN_RX_ADDR |
cmd_caf |
ATCAF0, ATCAF1 |
Yes |
Set CAN Auto formatting on/off (0 = use PCI byte in requests) |
AT_CAF |
cmd_cfc |
ATCFC0, ATCFC1 |
Yes |
Set CAN Flow control off or on |
AT_CFC |
cmd_can |
(none) |
Yes |
Include headers in CAN requests (experimental - to be removed) |
(none) |
cmd_atkw |
ATKW, ATKW0, ATKW1 |
Yes |
Display or set keyword |
AT_DKW, AT_SKW |
cmd_version |
ATI, ATWS, ATZ |
Yes |
ELM version (def. ELM327 v1.5) |
AT_I, AT_WARM_START, AT_RESET |
cmd_fcsm |
ATFCSM m (m = mode) |
No |
Set flow control to mode m |
AT_FCSM |
cmd_proto |
ATSPx (x=hex digit) |
No |
Set protocol |
AT_PROTO |
cmd_memory |
ATM0, ATM1 |
No |
Set Memory off or on |
AT_MEMORY |
cmd_fcsh |
ATFCSHx (x=hex digit) |
No |
Set FLOW CONTROL set HEADER |
AT_FCSH |
cmd_fcsd |
ATFCSDx (x=hex digit) |
No |
Set FLOW CONTROL set DATA |
AT_FCSD |
cmd_fcsm |
ATFCSMx (x=hex digit) |
No |
Set FLOW CONTROL set MODE |
AT_FCSM |
cmd_timeout |
ATSTx (x=hex digit) |
No |
Set timeout |
AT_SET_TIMEOUT |
cmd_cea |
ATCEAx (x=hex digit) |
No |
Set CAN extended address |
AT_CEA |
cmd_adaptive_t |
ATATx (x=0, 1, 2) |
No |
Set adaptive timing mode |
AT_ADAPTIVE_TIMING |
cmd_try_proto |
ATTPx (x=hex digit) |
No |
Try protocol |
AT_TRY_PROTO |
cmd_iso_baud |
ATIB 10, or 48, or 96 |
No |
Set ISO baud rate |
AT_ISO_BAUD |
cmd_response |
ATR0, ATR1 |
No |
Set responses off/on |
AT_RESPONSES |
cmd_brd |
ATBRDn (n=two digits) |
No |
Set UART baud rate divisor |
AT_BRD |
cmd_long_msg |
ATAL, ATNL |
No |
Set message length |
AT_LONG_MSG, AT_NORMAL_LENGTH |
cmd_iia |
ATIIA hh (hh = addr) |
No |
Set the ISO 5-baud init address to hh |
AT_ISO_INIT_ADDR |
cmd_rec_addr |
ATSR hh (hh = addr) |
No |
Set receive address |
AT_SET_RECEIVE_ADDR |
cmd_hfm |
ATCM m (m = addr) |
No |
Set the CAN hardware filter mask |
AT_CAN_HFM |
cmd_brt |
ATBRT t (t = timeout) |
No |
Set UART baud rate timeout |
AT_BRT |
cmd_wakeup |
ATSW hh (hh = addr) |
No |
Set wakeup |
AT_WAKEUP |
cmd_st_slx |
STSLXm (m=string) |
No |
Enable or disable sleep/wakeup triggers |
ST_SLX |
cmd_st_proto |
STPp (p=number) |
No |
Set current ST protocol |
ST_PROTO |
cmd_st_fcap |
STCFCPA t,STCAFCP t |
No |
Add a flow control address pair |
ST_STCAFCP |
cmd_stip4 |
STIP4 n (n = delay) |
No |
Set Tx Interbyte delay |
ST_IP4 |
cmd_stpto |
STPTO t (t = timeout) |
No |
Set OBD Request Timeout |
ST_PTO |
cmd_atv |
ATV0, ATV1 |
No |
Set variable DLC on or off |
AT_V |
cmd_dlc |
ATD0, ATD1 |
Yes |
Display of the DLC byte with headers off (with ATH1 the length byte is always part of the frame representation) |
AT_DLC |
cmd_dtc_cleared |
04 (Clear DTC) |
Yes |
Set when the DTC lists have been cleared |
GET_DTC, SHOW_DIAG_TC, SHOW_PENDING_TC, UNKNOWN_0A |
Unhandled setter means that the AT/ST command is recognized, the related counter is valued but no process is currently associated.
echo and linefeed settings are both disabled by default. They can be configured via related AT commands (ATE1 and ATL1). The special setters cmd_echo and cmd_linefeeds allow enabling them via command line. Example:
emulator.counters['cmd_linefeeds'] = True; emulator.counters['cmd_echo'] = True
This is the same as:
test ATL1
test ATE1
Possible values of emulator.counters['cmd_linefeeds']:
| Value |
Behaviour |
separator among lines |
separator at the end of the response |
| 0 |
(Default) Each line in the response is separated by one CR and the response is closed by two CRs (selected with ATL0). |
\r |
\r\r |
| 1 |
Each line in the response is separated by one CR+LF and the response is closed by two CR+LF (selected with ATL1). |
\r\n |
\r\n\r\n |
| 2 |
Each line in the response is separated by one LF and the response is closed by two LFs. |
\n |
\n\n |
| 3 |
Each line in the response is separated and closed by a CR. |
\r |
\r |
| 4 |
Each line in the response is separated and closed by a CR+LF. |
\r\n |
\r\n |
| 5 |
Each line in the response is closed by a LF. |
\n |
\n |
Space characters are inserted by default in the ECU response as per specification. To remove them, use the AT command ATS0 or emulator.counters['cmd_spaces'] = 0.
By default the header (CAN ID) is not included in the ECU response. To add it, use the AT command ATH1 or emulator.counters['cmd_use_header'] = True.
The default ECU header is ECU_ADDR_E (e.g., “7E0”, producing answer “7E8”; ref. obd_message.py). Use cmd_set_header to customize it, or, alternatively use the command test atsh <header>.
The last executed request is stored in cmd_last_cmd. This is used to repeat the command when the ‘fast’ option is set (command repetition, using a newline). While executing the command, cmd_last_pid is valued with the PID label referred to the request.
Each time the interface is reset by an ATZ command, the special setters are restored to their default settings and any specific customization needs to be issued again. Use emulator.presets in order to preset the special setters so that they are applied as default values each time the interface is opened by an application. Example:
emulator.presets = { 'cmd_linefeeds': 4, 'cmd_spaces': 0 }
The cmd_spaces setting is the same as:
test ATS1
cmd_cra keeps the value set by ATCRA when setting and resetting the receive address filter. The following metacharacters are accepted:
- X for any single hex digit,
- W for any sequence of hex digits (one or more).
Example.
test ATCRA 7X8
test 0100
counters
It returns cmd_cra = 7X8.
To switch off autoformatting, set cmd_caf to False, like in the following example:
test atcaf0
counters
test 02 01 0C
To test the processing of full CAN messages, set cmd_can as in the following example:
emulator.counters["cmd_can"] = True
The above setting also implies the following ones, which are automatically changed by each subsequent CAN request:
self.counters['cmd_set_header'] # using the first three hex digits of the request
self.counters['cmd_caf'] = False
self.counters['cmd_use_header'] = True
Example of usage of cmd_can:
scenario car
emulator.counters["cmd_can"] = True
test 7E0 02 01 0C
test 7e2 02 01 5b
test 7E5 06 27 12 B1 51 D5 8F
To change the ELM version string in ELM commands, use the version command, which defaults to ELM327 v1.5. Use version reset to return to the default values of the ELM version string and related header. Check also the “elm_version” setter, which stores the temporary version string within the current session.
Example:
version ELM327 v2.3
test ati # Get the ELM327 version string
The returned code will be ‘ELM327 v2.3\r\r>’.
Through the hexheader argument of the version command, ELM327-emulator also allows to change the header bytes of the version string, which by default are two carriage return characters. The updated string should be composed by a sequence of hex digits. Example:
version hexheader 0d fc 0d 0d
Any change to the ELM version string and ELM header version bytes can be restored to default with:
version reset
Without parameters, version returns the ELM327-emulator version and ELM version parameters in use.
Other example to reproduce the ATZ output of a ScanTool.net OBDLink SX device:
version hexheader 00 00 00 00 0d 0d
version ELM327 v1.4b
test atz
The returned output is:
______Raw command:_______________
'<writeln>\x00\x00\x00\x00\r\rELM327 v1.4b</writeln>'
______Command output:____________
'\x00\x00\x00\x00\r\rELM327 v1.4b\r\r>'
The output is then written to the application when using the following command:
write <writeln>\x00\x00\x00\x00\r\rELM327 v1.4b</writeln>
Editing answers on the fly
Static answers in the ObdMessage dictionary can be edited on the fly through the edit command. It extracts the answer from a PID, stores it into the emulator.answer dictionary described in the next chapter and performs the editing in its data part. If the command is called with just the PID argument, it resets the emulator.answer dictionary for the referred PID, returning to the default answer.
Syntax: edit PID <position> <replaced bytes>
PID is an element name in the ObdMessage dictionary for the current scenario and with an associated static 'Response'.
Position is a number starting from 0, which can be decimal (e.g., edit VIN 10 AA BB CC DD) or in any other format (0o for octal, 0x for hex, 0b for binary; example: edit VIN 0x0A AA BB CC DD).
Replaced bytes is a string of hexadecimal digits in any format.
Note: this command only works for PIDs which have a static 'Response' in the ObdMessage dictionary. 'ResponseHeader', 'ResponseFooter' and 'Task' are not supported.
For more complex actions, the Edit class can be used with its answer() method, also allowing the Context Manager. See the related comments in interpreter.py for details on how to use this class.
The following example sets an edited response for 15 seconds, then restores the default answer.
with Edit(emulator, 'VIN') as e: e.answer(10, "AA BB CC DD"); time.sleep(15)
The following is a more complex command where the answer changes every three seconds:
with Edit(emulator, 'VIN') as e: \n\t for i in ['AA' 'BB' 'CC' 'DD']: \n\t\t e.answer(10, "01 02 03 " + i) \n\t\t time.sleep(3)
The edit command uses PIDs in the current scenario. To change scenario, use the scenario command. Example to change the value of FCLCINT1 (C/L Fuel Corr Int Cyl 1) on the MONITOR pid (2101, Delco “Mode 1 Message”) in the “mt05” scenario (Delphi MT05 ECU) to “AA BB” (spaces between hex digits are optional):
scenario mt05
edit MONITOR 0x0E AA BB
Notice that the mt05 scenario is automatically set by the ‘UDS_START_COMM’ PID (81). The method to dynamically change scenario is self.set_sorted_obd_msg(scenario).
Data Link and Network Layers
ELM327-emulator includes a basic processing of the ISO 15765-2 ISO-TP Layer and KWP2000 ISO 14230-2:1999 Data Link layer. The following elements are implemented:
- 3-byte and 4-byte KWP2000 header with frame length management (the “Format” byte always assumes address information and physical addressing; other cases are ignored),
- ISO-TP 11 bit CAN identifier (29 bit CAN identifiers are not supported)
- ISO-TP Single frame (SF), First frame (FF), Consecutive frame (CF), Flow control frame (FC),
- Basic input flow control of ISO-TP (with generation of FC output frames); output flow control (handling of FC input frames) is ignored,
- KWP2000 Checksum byte (CS) at the end of the ISO 14230-2:1999 message block (checksum verification in requests and checksum generation in responses),
- ISO-TP P1, P2, P3 and P4 timers.
The KWP2000 format is detected by a header >= three bytes.
Advanced usage
ELM327-emulator allows changing the UDS P1, P2, P3 and P4 timers via the timer command. The P4 timer controls the max delay between each entered character and by default is not active (e.g., set to 1440 seconds). The P4 timer can either be configured via timer P4 value, or by setting emulator.counters['req_timeout']. Decimals are allowed. Some adapters set P4 by default, discarding characters if each of them is not entered within a short time limit (apart from the first one after a CR/Carriage Return). The appropriate emulation for this timeout is to set emulator.counters['req_timeout']=0.015 (e.g., 15 milliseconds). Typing commands by hand via terminal emulator with such adapters is not possible as the allowed timing is too short. The same happens when setting req_timeout to 0.015 (or timer P4 0.015).
The command prompt also allows configuring the emulator.answer dictionary (ref. also previous paragraph), which has the goal to dynamically redefine answers for specific PIDs ('Pid': '...'). Its syntax is:
emulator.answer = { 'pid' : 'answer', 'pid' : 'answer', ... }
Example:
emulator.answer = { 'SPEED': '<writeln>NO DATA</writeln>', 'RPM': '<writeln>NO DATA</writeln>' }
# Or, alternatively:
emulator.answer['SPEED']='<writeln>NO DATA</writeln>'
emulator.answer['RPM']='<writeln>NO DATA</writeln>'
test 010d
test 010c
The above example forces SPEED and RPM PIDs to always return “NO DATA”.
To reset the emulator.answer string to its default value:
emulator.answer = {}
# Or, alternatively:
del emulator.answer['SPEED']
del emulator.answer['RPM']
test 010d
test 010c
To simulate that the adapter is not connected to the vehicle:
emulator.answer['AT_R_VOLT'] = '<writeln>0.0V</writeln>'
test atrv
As mentioned in the previous paragraph, the edit command simplifies the usage of emulator.answer.
The emulator.ELM_R_UNKNOWN parameter allows customizing the message returned in case of unknown/invalid command. The default message is ?\r, with an addition of a trailing \r. This message can be customized; for example, to just get \r, set the following:
emulator.ELM_R_UNKNOWN = ''
The dictionary can be used to modify answers within a workflow. The front-end allows implementing basic Python workflows and, when used in batch mode, can also be controlled by a piped external supervisor. The following examples show some simple workflows in interactive mode.
Example of automation which suspends the emulator for 10 seconds:
emulator.threadState = emulator.THREAD.PAUSED; time.sleep(10); emulator.threadState = emulator.THREAD.ACTIVE
Example of an automation that simulates the off/on ignition states:
CMD> for i in range(10): emulator.scenario="car" if i % 2 else "engineoff"; print(emulator.scenario); time.sleep(10)
engineoff
car
engineoff
car
engineoff
car
engineoff
car
engineoff
car
Configuring response strings
Response, ResponseHeader, ResponseFooter, emulator.answer and emulator.ELM_R_UNKNOWN support the following XML tags (which shall be produced without the xml envelope):
| Tag |
Line separator |
Behaviour |
Helper function |
<writeln> |
Yes |
The content is returned with the addition of a line separator at the end. <writeln></writeln> or <writeln />means newline. |
ST(writeln) |
<space> |
No |
The content is returned with the addition of a space at the end. <space></space> or <space /> means adding a simple space. |
|
<string> |
No |
The content is returned with no space and no line separator at the end. |
|
<header>, <size>, <data> |
Yes |
Standard response format composed of the concatenation of hexadecimal ECU header, related size code and hexadecimal data with the addition of a line separator at the end. The data part is not automatically converted into a multiframe if longer than 7 bytes. |
HD(header), SZ(size), DT(data) |
<header>, <size>, <subd> |
No |
Standard response format composed of the concatenation of hexadecimal ECU header, related size code and hexadecimal data with no line separator at the end (same as before). |
|
<exec> |
No |
Execution of single or multiple in-line Python commands (expressions or statements) returning the expression evaluation with no line separator at the end; any previous string is printed before the execution. |
|
<eval> |
No |
Like exec, but any previous string is concatenated (not immediately printed). |
|
<rh> |
No |
Force the usage of the request header included in this tag to generate the response instead of the one included in the real request. |
|
<rd> |
No |
Force the usage of the request data included in this tag to generate the response instead of the one included in the real request. |
|
<flow> |
Yes |
Generate a flow control response. |
|
<answer> |
Yes |
Generate an UDS generic response basing on request header (including header, length and generic data including the string in within this tag). Automatically generate Single Frames, Flow control frames, First Frame and Consecutive Frames. It is up to the dictionary or task to generate the appropriate positive or negative answer bytes. |
AW(answer) |
<pos_answer> |
Yes |
Generate an UDS positive answer response basing on request header and request data (the generated response includes header, length and UDS positive response data, then adding the string within this tag). Automatically generate multiframes if needed. If <rh> is used, the default request header is replaced by the one in this tag. If <rd> is used, the default request data is replaced by this tag. See the table named uds_sid_pos_answer in elm.py to check how ELM327-emulator computes the number of bytes to add to the answer for each requested SID. |
PA(pos_answer) |
<neg_answer> |
Yes |
Generate an UDS negative answer response basing on request header and request data (the generated response includes header, length and UDS negative response data, then adding the string within this tag). Automatically generate multiframes if needed. |
NA(neg_answer) |
Strings among tags are allowed and are returned as they are, with no line separator and stripping blank heading and footing characters.
Whenever possible, the usage of pos_answer and neg_answer is suggested, totally relying on ELM327-emulator for the construction of the answer. In such cases, ELM327-emulator builds the final bytestream basing on ISO 14230-2:1999 for the Data Link Layer and ISO 14230-3:1999 for the Application Layer.
The verify command can be used to test an XML response: the returned message will show what in normal operation is outputted to the communication port. Notice that, in order to check the produced <header> and <size> bytes, cmd_use_header shall be set to True (e.g., test ath1): these bytes are not returned when cmd_use_header is False. Besides, bytes included in the <data> tag will be returned with all spaces stripped out if cmd_spaces is False (e.g., test atsp0).
Tag nesting is not allowed.
Unknown tags are skipped.
Some special characters must be escaped within the XML fields, like:
| Symbol (name) |
Escape Sequence |
< (less-than) |
< (or <) |
> (greater-than) |
> (or >) |
The exec tag for instance can be used to embed real-time delays between strings or to differentiate answers. The return value of a statement is ignored. The evaluation of an expression is substituted. Example: 'Response' = '<string>SEARCHING...</string><exec>time.sleep(4.5)</exec><writeln /><writeln>UNABLE TO CONNECT</writeln>'. Notice that, as time.sleep` is a statement, the related return value is ignored.
Further processing can be achieved through a lambda function applied to ResponseHeader, ResponseFooter. It has to manage the following parameters: self, cmd, pid, uc_val (e.g., lambda self, cmd, pid, uc_val:).
- cmd: the request, received by the client application
- pid: the PID identifier (which can be used as key to index
self.counters and ObdMessage)
- uc_val:
ObdMessage dictionary related to pid with all keys converted to uppercase (e.g., uc_val['RESPONSE']).
Example of PID definition within the ObdMessage dictionary:
'ELM_PIDS_A': {
'Request': '^0100$',
'Descr': 'PIDS_A',
'ResponseHeader': \
lambda self, cmd, pid, uc_val: \
'<string>SEARCHING...</string>'
'<exec>time.sleep(4.5)</exec><writeln />'
'<writeln>UNABLE TO CONNECT</writeln>' \
if self.counters[pid] == 1 else \
self.choice([ST('NO DATA'), ST('BUS INIT:ERROR')]),
'Response': '',
'Priority': 5
},
In the above example, the first time ResponseHeader is executed (self.counters[pid] == 1), the produced response is SEARCHING..., followed by a one-second delay and then \rUNABLE TO CONNECT\r\r. For all subsequent messages, the response will be different and produces either NO DATA\r\r or BUS INIT:ERROR\r\r, according to the criteria (sequential or random) defined by the choice command.
The ability to add dynamic differentiators and delays within responses enables testing specific use cases and exceptions that are difficult to be achieved through a real connection with a car. These not only apply to the ObdMessage dictionary (by editing obd_message.py), but also to emulator.answer and emulator.ELM_R_UNKNOWN, that can be configured through the command line. Consider for instance the following dynamic configuration via command line:
emulator.answer['SPEED'] = '<exec>ECU_R_ADDR_E + " 03 41 0D 0A " if randint(0, 100) > 20 else "NO DATA"</exec><writeln />'
scenario car
test ath1
test atsh7e0
test 010D
In the above example, which illustrates an in-line expression substitution, the configuration of the ‘SPEED’ PID (Vehicle speed) is replaced with a dynamic answer and the ‘SPEED’ PID will return 7E8 03 41 0D 0A + line separator for most of the time. With 20% probability, NO DATA + line separator is returned. Notice that the last line separator is common to both options.
The following example shows how to dynamically generate an answer via command line by converting decimal numbers to hex string in order to allow comfortable testing of a PID by specifying decimal input values. Suppose that the PID needs to double the input. We use CUSTOM_FUEL_LEVEL PID in the example, testing the answer related to 15.5 liters.
Preliminarily, test number conversion with the command line:
"%.2X" % int(15.5*2)
1F
Apply it to CUSTOM_FUEL_LEVEL PID so that it returns 7C8 03 61 29 1F \r':
emulator.answer['CUSTOM_FUEL_LEVEL'] = '<header>7C8</header><size>03</size><subd>61 29</subd><eval>"%.2X" % int(15.5*2)</eval><space /><writeln />'
scenario car
test ath1
test atsh7c0
test 2129
The output is:
'7C8 03 61 29 1F \r\r>'
Or, alternatively, use the header variable instead of the header digits:
emulator.answer['CUSTOM_FUEL_LEVEL'] = '<exec>ECU_R_ADDR_I + " 03 61 29 " + "%.2X" % int(15.5*2)</exec><writeln> </writeln>'
scenario car
test ath1
test atsh7c0
test 2129
The following command sets SPEED (Vehicle speed) to 60 km/h via command line (60 can be changed to any integer value between 0 and 255):
emulator.answer['SPEED'] = '<header>7E8</header><size>03</size><subd>41 0D</subd><eval>"%.2X" % 60</eval><space /><writeln />'
scenario car
test ath1
test atsh7e0
test 010D
The output is:
'7E8 03 41 0D 3C \r\r>'
The following command sets RPM (Engine RPM) to 500 via command line:
emulator.answer['RPM'] = '<exec>ECU_R_ADDR_E + " 04 41 0C %.4X" % int(4 * 500)</exec><writeln />'
or
emulator.answer['RPM'] = '<header>7E8</header><size>04</size><subd>41 0C</subd><eval>"%.4X" % int(4 * 500)</eval><space /><writeln />'
scenario car
test ath1
test atsh7e0
test 010C
In both cases, the output is:
'7E8 04 41 0C 07D0 \r\r>'
To list the configuration, type emulator.answer, or simply counters. To remove the dynamic answer and return to the default configuration of the ‘SPEED’ PID, type del emulator.answer['SPEED'].
Command to configure PID ‘0100’ answer (PIDS_A) to BUS INIT: OK for its first query and to 48 6B 13 41 00 BE 1F B8 11 AD \r for all the subsequent queries:
emulator.answer['ELM_PIDS_A'] = '<exec>"BUS INIT: OK" if self.counters["ELM_PIDS_A"] < 2 else "48 6B 13 41 00 BE 1F B8 11 AD "</exec><writeln />'
scenario car
test ath1
test atsh7e0
emulator.counters["ELM_PIDS_A"] = 0
test 0100
test 0100
The output is:
'BUS INIT: OK\r\r>'
'48 6B 13 41 00 BE 1F B8 11 AD \r\r>'
The ELM_PIDS_A counter (emulator.counters["ELM_PIDS_A"]) can be reset with:
emulator.counters["ELM_PIDS_A"] = 0
The following example shows how to use the verify command (without single or double commas) to quickly test the conversion of an XML response; write does the same and also writes the produced output to the opened device.
python3 -m elm -s car
test ath1
test ats0
verify <header>7E0</header><size>03</size><data>01 02 03</data>
The output will be '7E003010203\r\r>'.
In the next example, we will use the pos_answer tag, that needs the request header and the request data to produce a valid UDS positive response; in normal operation, those data are automatically inserted by ELM327-emulator upon each request; if using verify (which has no clue about any previous request), they need to be specifically included (as cannot be acquired by the context). As mentioned, test ath1 instructs ELM327-emulator to return header and length.
test ath1 # return header and length
verify <rh>7E0</rh><rd>0902</rd><pos_answer>01 53 42 31 5A 53 33 4A 45 36 30 45 32 38 32 31 30 32</pos_answer>
The result will be 7E8 10 14 49 02 01 53 42 31 \r7E8 21 5A 53 33 4A 45 36 30 \r7E8 22 45 32 38 32 31 30 32 \r\r>.
The answer tag simply computes the length of the data bytes and adds the header; it does not need the rd tag; using the above example, to generate the same answer we need to add the UDS positive answer data “49 02”:
test ath1
verify <rh>7E0</rh><answer>49 02 01 53 42 31 5A 53 33 4A 45 36 30 45 32 38 32 31 30 32</answer>
Then the result will be the same: 7E8 10 14 49 02 01 53 42 31 \r7E8 21 5A 53 33 4A 45 36 30 \r7E8 22 45 32 38 32 31 30 32 \r\r>.
Example of neg_answer tag:
test ath1
verify <rh>7E0</rh><rd>010F</rd><neg_answer>44</neg_answer>
The result will be 7E8 03 7F 01 44 \r\r>.
Example of flow tag:
test ath1
verify <flow>20 00</flow>
The result will be 7E8 30 30 20 00 \r\r>.
To write the output of a test command to the application, copy its Raw command output and paste it to a write command.
Timers
The timer command allows showing or changing the UDS timers.
Values are in seconds (floating numbers are allowed).
| Timer name |
Description |
Default value |
Note |
| P1 |
Inter byte time for ECU response |
0 |
This timer is implemented by adding a fixed delay to each outputted character. If set to a value different than 0, ELM327-emulator outputs characters one by one, adding the indicated delay value after each of them. |
| P2 |
Time between tester request and ECU response or two ECU responses |
0 |
Same as the delay command: this timer is implemented by adding a fixed delay (the one indicated in the timer P2 value) after receiving each request (including also AT/ST commands) and before computing the response. |
| P3 |
Time between end of ECU responses and start of new tester request |
5 |
The related value controls the expiration timeout between two responses: if expiring within a multiframe or within an active task, the related operation is interrupted and the active tasks of the same ECU are removed, executing the stop() method. |
| P4 |
Inter byte time for tester request |
1440 |
The related value controls the time between each received request character to keep the whole request valid. If exceeding the timeout, the request is discarded. Changing this value configures the req_timeout counter. |
Tasks
ELM327-emulator provides an extendable plugin architecture defining tasks, which are entities allowing the implementation of stateless and stateful procedures, that can be nested and are chainable. Through plugins, ELM327-emulator offers a development framework to easily implement ECU emulation objects, which are able to manage persistent data within the same instance (its namespace) and within the same ECU (shared namespace). Tasks allow emulating multiple ECUs concurrently, where each ECU has its own data space.
In case of stateless requests/responses, an ECU function can be emulated through a simple configuration in the dictionary, without usage of a plugin. Alternatively, if stateful routines or more complex programming are needed, an ECU function leverages the implementation of tasks. The structure of tasks is designed to simplify the development of complex ECU functions, like for instance flash upload/download operations.
When ELM327-emulator starts, it enumerates all available plugins in its plugins subdirectory (elm/plugins). Each plugin defines an own task, named with the file name of the plugin. All the file names of the plugins must start with task_.
A task is invoked in the dictionary through the 'Task' tag, that refers to the name of an installed plugin. If a request associating a task is matched (including Request and possibly Header tags), its related task is activated by instantiating the Task class of the invoked plugin. After startup and after processing the request, the task can either terminate or remain active; in the latter case, it receives all subsequent requests related to the same header, allowing to implement a dedicated communication flow within a dedicated namespace. All tasks (regardless they terminate or remain active) take also advantage of a shared namespace, common to all requests addressed to the same ECU (see ECU Tasks for further information).
Tasks are interrupted by the following conditions:
- task termination performed by the plugin itself after processing the request (e.g, returning a method with
False or with self.TASK.TERMINATE as the second value of the return tuple);
- communication reset (e.g., communication disconnection, or “ATZ”, or reset command);
- expiration of the P3 timer.
Tasks and plugins can be monitored through the tasks command.
Multiple tasks can be concurrently instanced with different ECU IDs.
All plugins shall implement a class named Task derived from the Tasks class.
In a plugin, at least the run() method should be implemented, overriding the default method of the Tasks class. Allowed methods:
def start(self, cmd, *_): invoked to process the first request of a just created task (not required)
def stop(self, cmd, *_): invoked to process a request before interrupting the task (not required). Default is to return Tasks.RETURN.ERROR (do nothing).
def run(self, cmd, *_): invoked on any request after the first one; if start() is not implemented, run() is always invoked.
Task methods are called after processing the ISO-TP data link, so the request passed to the task methods includes the whole message, where the associated multiframe (consisting of multiple frames received from the communication port) is already assembled and interpreted into a single data string of consecutive hex values, without spaces. Tasks methods return an XML response string as the first value of the return tuple; this XML string will be subsequently processed by the embedded ISO-TP data link, generating the output strings then sent to the communication port.
A multiframe is internally processed as a special temporary task named ‘ISO-TP request pending’. It can be monitored through the tasks command.
All methods return a tuple of three elements:
-
an XML response string, which will be subsequently interpreted by the ISO-TP processor and then written to the client application; None means nothing to output;
-
a boolean (True = Tasks.RETURN.CONTINUE, or False = Tasks.RETURN.TERMINATE), to indicate whether the task remains active or terminates;
-
a request string (e.g., cmd) which will be processed by ELM327-emulator after the transmission of the XML response string; the value can be:
- None, meaning no subsequent request string to be processed, or
- the same unchanged request of the task method invocation, where the returned request is sent to the standard processing of its dictionary response elements (without re-executing the same task), or
- a different data than cmd in the task method, so that a full reprocessing of the new request is done (including running a task if defined).
This third element of the return tuple allows a task to also act as a filter or preprocessor, that receives a request (cmd), accounts it, possibly transforms it and forwards it to the standard processor.
Special return values:
Task.RETURN.ANSWER(answer), or (answer, Tasks.RETURN.TERMINATE, None): used with standard positive or negative answers, terminating the task (without any further request processing after the task is terminated);
Task.RETURN.PASSTHROUGH(cmd), or (None, Tasks.RETURN.TERMINATE, cmd): if the task returns the same unchanged cmd in the request, it is generally used for pure pass-through, like performing some accounting in the task, or logging, and then terminating the task while sending the same request to the standard processing of its dictionary response elements; if the task changes the returned data, a full reprocessing of the request is done;
Task.RETURN.ERROR, or (None, Tasks.RETURN.TERMINATE, None): used for error conditions; no output written while terminating the task;
Task.RETURN.INCOMPLETE, or (None, Tasks.RETURN.CONTINUE, None), used to allow internal processing of the request, without producing output and keeping the task active, so that the same task will also process all subsequent input requests addressed to the same ECU, until the task is terminated.
Tasks.RETURN.TASK_CONTINUE(cmd), or (None, Tasks.RETURN.CONTINUE, cmd) used for instance in ECU Tasks in order to pass the request to the subsequent processor, by keeping the ECU Task active for all subsequent requests, with its ECU namespace.
Check the Tasks class in elm.py for a list of the available variables initialized by its __init__() method.
Task namespaces
A task can exploit its own namespace, which is related to a specific task instance, that can remain active for subsequent requests if handled with Tasks.RETURN.CONTINUE. A task can also use the shared namespace of the ECU, which is associated to any kind of request referring to the same ECU ID. Notice that requests do not necessarily need to invoke a 'Task' to access the ECU shared namespace: also 'ResponseFooter' and 'ResponseHeader' can reference the ECU shared namespace.
Other than storing local variables, the task namespace is useful to persist class properties if the task terminates with Tasks.RETURN.CONTINUE, and also to perform preprocessing through the related task methods (start(), stop(), run()), so that any subsequent request of the same ECU will be processed by the same task, until task termination. All subsequent calls of an active task share the same namespace. For instance, if a task is configured as a filter, its namespace can be used while preprocessing all subsequent requests directed to the ECU, which will be sent to the same task until its termination.
The shared namespace for an ECU is named self.shared and can be associated to an ECU Task.
For instance, a task can create a variable named self.shared.my_data = True, that other tasks can use. The shared namespace can be used by different commands or tasks, if referring the same ECU. This area is created by ELM327-emulator at the first request referring to an ECU (and, if available, the related ECU Task start() method is executed). The shared namespace is already active when any task method is run. This shared area is reset by a communication disconnection, or “ATZ”, or reset command, or expiration of the P3 timer.
The easies way to configure tasks is to use Tasks.RETURN.TERMINATE (so that a task terminates after the execution of the invoked method, e.g., Task.RETURN.ANSWER(answer)) and to exploit self.shared to store persistent data, shared by different tasks and functions. The easies way to initialize shared data is through the definition of a start() method inside the related ECU Task.
ECU Tasks
An ECU Task is an optional request preprocessor which owns the shared namespace for its related ECU and is executed for each request referred to the same ECU, before interpreting the request (or running the task, regardless the request is a task or a simple command).
The plugin of the ECU Task shall be named “task_ecu_” followed by the hex header digits (case-insensitive) of the (source/destination) CAN id of the ECU (then followed by “.py”). For instance, in case of a request directed to an ECU with CAN id “7E0” (ATSH 7E0), the task ECU plugin shall be named “task_ecu_7E0.py”. In case of ATSH 8011F1, the related ECU task shall be named “task_ecu_11F1.py”. Hex digits accept the following metacharacters:
- X for any single hex digit,
- W for any sequence of hex digits (one or more).
The plugin shall implement a class named Task derived from the EcuTasks class.
Defining an ECU task is not required; if missing, a default shared namespace for the ECU is automatically created when the ECU is first used; no further preprocessing occurs; the task namespace will be anyway usable.
The allowed methods are the same as the normal tasks. The start() method of the ECU task is executed upon the first request reference of an ECU, when the shared namespace for the ECU is created. It can for instance be used to run one-time procedures like initializing resources used by subsequent commands (e.g., initialize shared variables and mapped memory used by a task). A typical return code is return Tasks.RETURN.TASK_CONTINUE(cmd) (EcuTask can be used in place of Task), so that the ECU task remains active with its namespace and the request is subsequently processed. Tasks.RETURN.TERMINATE can be used for testing purpose.
Example of a plugin implementing an ECU Task which fully disables the ECU processing, always returning “NO DATA” ("NO DATA", EcuTasks.RETURN.TERMINATE, None):
</data></size></header></neg_answer></rd></rh></pos_answer></answer></flow></rd></rh></eval></exec></subd></size></header></data></size></header></string></space></writeln></replaced></position></header></carriage></module></module></n></scenario></scenario></value></name></n></n></n></n></cr></nl>
> README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。
评论