403
Open Vehicles Apr 24, 2022

Open Vehicles - Home | Read the Docs

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Open Vehicles - Home | Read the Docs

Open Vehicles

Apr 24 2022

User Guides

1 Open-Vehicle-Monitoring-System-3 (OVMS3) 3

2 User Guide 11

3 Plugins 89

4 BMW i3 i3s 113

5 DBC Based Vehicles 117

6 DEMO Vehicle 121

7 Fiat 500e 123

8 Hyundai Ioniq vFL 125

9 Jaguar IPace 127

10 Kia e-Niro 129

11 Kia Soul EV 131

12 Maxus eDeliver3 137

13 Mercedes-Benz B250E W242 139

14 MG EV 141

15 Mitsubishi Trio 145

16 Nissan Leafe-NV200 151

17 OBDII Vehicles 157

18 Renault Twizy 159

19 Renault Zoe 183

20 Smart ED Gen3 185

i

21 Smart EDEQ Gen4 (453) 189

22 Tesla Model 3 191

23 Tesla Model S 193

24 Tesla Roadster 195

25 Toyota RAV4 EV 201

26 Tracking Vehicles 203

27 VW e-Up 205

28 VW e-Up via OBD2 227

29 VW e-Up via Comfort CAN (T26A) 237

30 Command Line Interpreter 245

31 CAN Bus Data Logging 251

32 CRTD CAN Log Format 255

33 Web Framework amp Plugins 261

34 Scripting 341

35 CANopen 351

36 OVMS Server 361

37 OVMS Protocol v2 367

38 OVMS HTTP API 389

Index 399

ii

Open Vehicles

Note This online manual includes documentation for the stable release of the OVMS firmware (available as OTAversion tag ldquomainrdquo) and the latest nightly firmware build (available as OTA version ldquoedgerdquo) Select the manual versionmatching your setup using the menu on the bottom left

User Guides 1

Open Vehicles

2 User Guides

CHAPTER 1

Open-Vehicle-Monitoring-System-3 (OVMS3)

11 Introduction

The OVMS is an all open source vehicle remote monitoring diagnosis and control system

3

Open Vehicles

The system provides live monitoring of vehicle metrics like state of charge temperatures tyre pressures and diag-nostic fault conditions It will alert you about critical conditions and events like a charge abort battery cell failureor potential theft Depending on the vehicle integration it allows you to take control over the charge process cli-mate control tuning parameters of the engine and more OVMS developers are enthusiasts trying hard to provide asdetailed information about the internals of a vehicle as possible

While most new vehicles now include some kind of remote control system very few allow deep insight some willnot work in all regions and none will give you control over your personal data The OVMS fills that gap and alsoenables you to add all these features to existing vehicles of any kind

The OVMS can also be used for fleet monitoring It allows a fleet manager to not only track the vehicle locations butalso to monitor the vehiclersquos vitals remotely check for fault conditions offer services like automatic preheating forusers and take active control in case of abusive use As the system is open source and fully scriptable it can easilyintegrate custom access and control systems

For developers and technicians the OVMS includes a range of CAN tools including multiple logging formats aconfigurable OBD2 translator a DBC decoder a reverse engineering toolkit and a CANopen client The moduleprovides SSH access and WebSocket streaming and can stream and inject CAN frames via TCP Both the module andthe web frontend can be customized by plugins The module has three builtin CAN buses and can be extended by afourth one

The OVMS base component is a small and inexpensive hardware module that connects to the vehicle OBD2 port Thestandard kit includes a 3G modem to provide GSM connectivity and GPS and comes with a ready-to-use HologramioSIM card The US kit has been FCC certified the EU kit CE certified

The module provides a built-in Web App user interface and remote control via native cellphone Apps available forAndroid and iOS It integrates into homeprocess automation systems via MQTT and provides data logging to SDcard and to a server

12 Vehicle Support

bull Native Integration

ndash Chevrolet Volt Opel Ampera

ndash Chevrolet Bolt EV Opel Ampera-e

ndash BMW i3 i3s

ndash Fiat 500e

ndash Hyundai Ioniq vFL

ndash Jaguar Ipace

ndash Kia e-Niro Hyundai Kona

ndash Kia Soul EV

ndash Maxus eDeliver 3

ndash Mercedes-Benz B250E

ndash MG ZS EV

ndash Mitsubishi Trio (i-MiEV et al)

ndash Nissan Leaf e-NV200

ndash Renault Twizy

ndash Renault Zoe Kangoo

4 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

Open Vehicles

ndash Smart ED Gen3

ndash Smart EDEQ Gen4 (453)

ndash Tesla Model S

ndash Tesla Roadster

ndash Think City

ndash Toyota RAV4 EV

ndash VW e-Up

bull General Support

ndash DBC File Based

ndash GPS Tracking

ndash OBD-II Standard

ndash Zeva BMS

13 Links

bull User Resources

ndash User and Developer Guides (hint version selection in left menu at the bottom)

Stable release (OTA version ldquomainrdquo)

Latest nightly build (OTA version ldquoedgerdquo)

ndash User Support Forum

ndash Android App

ndash iOS App

bull Distributors

ndash FastTech (global)

ndash Medlock amp Sons (North America)

ndash OpenEnergyMonitor (UKEurope)

bull Servers

ndash Asia-Pacific

ndash GermanyEurope

bull Developers

ndash Developer Guide

ndash Developer Mailing List amp Archive

ndash Server Source

ndash Android App Source

ndash iOS App Source

13 Links 5

Open Vehicles

14 Hardware

bull Module Schematics and PCB Layouts

bull Base Module (v30-33)

ndash Black injection-moulded plastic enclosure approximately 99x73x29 mm excl plugs

ndash ESP32 WROVER processor (16MB flash 4MB SPI RAM 520KB SRAM dual core 160240MHz XtensaLX6 processor)

ndash WIFI 80211 bgn

ndash Bluetooth v42 BREDR and BLE

ndash 3x CAN buses

ndash 1x Micro USB connector (for flash download and serial console)

ndash 1x Micro SD card slot

ndash 1x Internal expansion slot

ndash 8x EGPIO 2x GPIO

ndash 1x GSM antenna connector

ndash 1x GPS antenna connector

ndash 1x DB9 vehicle connector

ndash 1x DB26 expansion connector

bull Modem Module v30-32

ndash US edition is SIM5360A (Dual-Band UMTSHSPA+ 8501900MHz Quad-Band GSMGPRSEDGE85090018001900MHz)

ndash EU edition is SIM5360J(E) (Dual-Band UMTSHSPA+ 9002100MHz Quad-Band GSMGPRSEDGE85090018001900MHz)

ndash 3G (EV-DOHSPA+) dual band modem

ndash Includes 2G (GSMGPRS) and 25G (EDGE) quad band

ndash GPSGNSS

6 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

Open Vehicles

ndash Nano (4FF) SIM slot

ndash HOLOGRAMIO nano sim included (can be exchanged if necessary)

bull Modem Module v33

ndash World edition SIM7600G (Multi-Band LTE-FDDLTE-TDDHSPA+ and GSMGPRSEDGE)

ndash 4G (LTE-FDDLTE-TDD) multi band modem

ndash Includes 3G (EV-DOHSPA+) 2G (GSMGPRS) and 25G (EDGE) quad band

ndash GPSGNSS

ndash Nano (4FF) SIM slot

ndash HOLOGRAMIO nano sim included (can be exchanged if necessary)

141 Extensions

The external DB26 DIAG connector provides access to the three CAN buses and offers some free extension ports Theinternal PCB expansion connector allows stacked additions of further modules and serves for routing GPIO ports tothe external DIAG connector See schematics for details

A very nice first extension module has been developed by Marko Juhanne OVMS-SWCAN

If you plan on developing a hardware extension or just want to do some custom adaptations have a look at ourprototyping PCB kit Itrsquos available in packs of 3 PCBs and includes headers and mounting material

If the kit isnrsquot available at the distributors please contact Mark Webb-Johnson markwebb-johnsonnet

14 Hardware 7

Open Vehicles

15 Development and Contributions

New developers are very welcome on any part of the system and we will gladly provide any help needed to getstarted

The purpose of this project is to get the community of vehicle hackers and enthusiasts to be able to expand the projectWe canrsquot do it all and there is so much to do What we are doing is providing an affordable and flexible base that thecommunity can work on and extend

Everything is open and APIs are public Other car modules can talk to the server and other Apps can show the statusand control the car This is a foundation that others hopefully will interface to and and build upon

If yoursquod like to contribute please accept our code of conduct

bull Introduce yourself on the developer mailing list

bull Be kind amp polite

bull Understand the framework concepts

bull Ask if you need help

bull Present your plans if in doubt

bull Write decent code

bull If you extend modules stick to their code style

bull Write brief but descriptive commit comments

bull Add user level descriptions to the change history

bull Provide documentation in the user guide

bull Use pull requests to submit your code for inclusion

A note on pull requests

Pull requests shall focus on one specific issue feature vehicle at a time and shall only mix vehicle specific changeswith framework changes if they depend on each other If changes are not or only loosely related split them intomultiple PRs (just as you would do with commits)

Usage hint create a branch for each pull request include only those commits in that branch (by cherry-picking ifnecessary) that shall be included in the pull request That way you can push further commits to that branch Githubwill automatically add them to an open pull request

16 Donations

The OVMS is a non-profit community project Hardware production and service can normally be financed by salesbut some things (eg prototype development and certifications) need extra money To help the project you can makea donation on the OVMS website httpswwwopenvehiclescomforum

Please also consider supporting the vehicle developers directly Check out their web sites and support addresses fortheir respective donation channels

Thank you

8 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

Open Vehicles

17 License

The project includes some third party libraries and components to which their respective licenses apply see componentsources for details

The project itself is published under the MIT license

Copyright (c) 2011-2020 Open Vehicles

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

Software which uses other licenses will be annotated appropriately

17 License 9

Open Vehicles

10 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

CHAPTER 2

User Guide

21 Warnings and Notices

211 OVMS-33-7600G FCC Statement

This equipment has been tested and found to comply with the limits for a Class B digital device pursuant to part15 of the FCC Rules These limits are designed to provide reasonable protection against harmful interference in aresidential installation This equipment generates uses and can radiate radio frequency energy and if not installedand used in accordance with the instructions may cause harmful interference to radio communications Howeverthere is no guarantee that interference will not occur in a particular installation If this equipment does cause harmfulinterference to radio or television reception which can be determined by turning the equipment off and on the user isencouraged to try to correct the interference by one or more of the following measures

bull Reorient or relocate the receiving antenna

bull Increase the separation between the equipment and receiver

bull Connect the equipment into an outlet on a circuit different from that to which the receiver is connected

bull Consult the dealer or an experienced radioTV technician for help

Caution Any changes or modications to this device not explicitly approved by manufacturer could void your authorityto operate this equipment

This device complies with part 15 of the FCC Rules Operation is subject to the following two conditions (1)This device may not cause harmful interference and (2) this device must accept any interference received includinginterference that may cause undesired operation

212 OVMS-33-7600G Specific Absorption Rate (SAR) information

This OVMS-33-7600G meets the governmentrsquos requirements for exposure to radio waves The guidelines are basedon standards that were developed by independent scientific organizations through periodic and thorough evaluationof scientific studies The standards include a substantial safety margin designed to assure the safety of all personsregardless of age or health FCC RF Exposure Information and Statement the SAR limit of USA (FCC) is 16 Wkg

11

Open Vehicles

averaged over one gram of tissue Device types OVMS-33-7600G has also been tested against this SAR limit Thisdevice was tested for typical body-worn operations with the back of the phone kept 0mm from the body To maintaincompliance with FCC RF exposure requirements use accessories that maintain an 0mm separation distance betweenthe userrsquos body and the back of the phone The use of belt clips holsters and similar accessories should not containmetallic components in its assembly The use of accessories that do not satisfy these requirements may not complywith FCC RF exposure requirements and should be avoided

213 OVMS-33-7600G CE Statement

EU importer information

OpenEnergyMonitorInTec F9Ffordd y Parc Parc MenaiBangorLL57 4FGUnited Kingdom

This product can be used across EU member states

Specification

12 Chapter 2 User Guide

Open Vehicles

Manufacturer Open Vehicles LtdHardware Version Software Version Frequency Range

bull 24G WIFI 2412MHz ~ 2472MHz(Max powerRated 1569dBm)

bull GSM 900 880MHz ~ 915MHz(Max powerRated 3266dBm)

bull DCS 1800 1710MHz ~ 1785MHz(Max powerRated 2975dBm)

bull WCDMA Band I 1920MHz ~ 1980MHz(Maxpower Rated 2340dBm)

bull WCDMA Band VIII 880MHz~915MHz(Maxpower Rated 2310dBm)

bull E-UTRA Band 1 1920MHz ~ 1980MHz(Maxpower Rated 2280dBm)

bull E-UTRA Band 3 1710MHz~1785MHz(Maxpower Rated 2240dBm)

bull E-UTRA Band 7 2500MHz ~ 2570MHz(Maxpower Rated 2297dBm)

bull E-UTRA Band 8 880MHz ~ 915MHz(Maxpower Rated 2240dBm)

bull E-UTRA Band 20 832MHz ~ 862MHz(Maxpower Rated 2295dBm)

bull E-UTRA Band 28 703MHz ~ 748MHz(Maxpower Rated 2237dBm)

bull E-UTRA Band 34 2010MHz ~ 2025MHz(Maxpower Rated 2279dBm)

bull E-UTRA Band 38 2570MHz ~ 2620MHz(Maxpower Rated 2296dBm)

bull E-UTRA Band 40 2300MHz ~ 2400MHz(Maxpower Rated 2348dBm)

Receiver category 3

Members applicability

1 Extreme temperature -20-45 Celcius

2 The device complies with RF specifications when the device used at 5mm form your body

3 RED 201453EU

Declaration of Conformity

Hereby Open Vehicles Ltd declares that this OVMS-33-7600G product is in compliance with essential requirementsand other relevant provisions of Directive 201453EU A copy of the Declaration of conformity can be found atwwwopenvehiclescom

21 Warnings and Notices 13

Open Vehicles

214 General Warnings

WarningOVMS is a hobbyist project not a commercial product It was designed by enthusiasts for enthusiasts Installationand use of this module requires some technical knowledge and if you donrsquot have that we recommend you contactother users in your area to ask for assistance

WarningThe OVMS module is continuously powered by the car even when the car is off While the OVMS module usesextremely low power it does continuously draw power from the carrsquos battery so it will contribute to lsquovampirersquo powerdrains

Do not allow your car battery to reach 0 SOC and if it does plug in and charge the car immediately Failure to dothis can result in unrecoverable failure of the carrsquos battery

The module can monitor the main and 12V battery and send alert notifications if the SOC or voltage drops below ahealthy level

215 Average Power Usage

The power used by the module depends on the component activation You can save power by disabling unusedcomponents This can be done automatically by the Power Management module to avoid deep discharging the 12Vbattery or you can use scripts to automate switching components off and on

The base components need approximately these power levels continuously while powered on

Component Avg Power 12V CurrentBase System 200 mW 17 mAWifi 330 mW 28 mAModem 170 mW 13 mAGPS 230 mW 19 mATotal 930 mW 78 mA

This adds up to

bull ~ 22 Wh or 2 Ah day

14 Chapter 2 User Guide

Open Vehicles

bull ~ 156 Wh or 13 Ah week

bull ~ 680 Wh or 57 Ah month

Note that depending on the vehicle type the module may also need to wake up the ECU periodically to retrieve thevehicle status Check the vehicle specific documentation sections for hints on the power usage for this and options toavoid or reduce this

22 Components

221 The OVMS Module

The OVMS v3 module is housed in a plastic enclosure held secure by four small screws Once open you can see themain OVMS v3 motherboard and an optional modem board

At one end of the module is the main DB9 connector you will use to connect to the vehicle as well as GSM (cellular)and GPS (positioning) antenna connections

At the other end of the module is the DA26 expansion connector the USB diagnostic connector and a Micro SD cardslot

Warning The USB port is a fragile PCB socket without reinforcement Handle it carefully do not apply forcewhen plugging or unplugging cables to not bend the plug If you need to use the port frequently two dots of hotglue at the port sides on the PCB can help to avoid breaking it off

If you open the module and take out the board take care to guide the port carefully and correctly into itrsquos case holewhen inserting the board into the casing again Insert the board USB port side first

If removinginstalling optional expansion boards (such as used for cellular connectivity) please take care to ensureyou secure screw down the expansion board using the four pillar posts provided Also please ensure that the cellularmodem connections are correct (follow the printed table on the modem board to know which antenna is which)

22 Components 15

Open Vehicles

WarningThe OVMS v3 enclosure is not waterproof and the components can be damaged by water Do not get the modulewet and do not connect it to your vehicle if it is wet

222 Cellular Modem Option and GSM Antenna

The cellular modem option allows you to control your vehicle when out of wifi coverage range The majority ofOVMS users choose this option and you will require it if you want to monitor your vehicle when away from home oroffice

OVMS modules sold in USA and Europe are provided with a Hologram SIM card pre-installed This low cost serviceallows you to get cellular connectivity simply It also allows you to roam between countries without worry Formodules purchased from China we recommend you purchase a Hologram SIM directly from the hologramio store(also available on Amazon)

Depending on settings verbosity towards the OVMS server rhythm of GPS tracking etc OVMS v3 will use between1 and 3 Megabytes per month of data (when using the v2 server protocol)

You do not have to use the Hologram service If you use another cellular provider the Sim Card format required is4FF Nano Micro Sim cards are hard to recut into the smaller format so please be careful to not damage the socketotherwise ask your operator for a swap (some do it for free)

If you are using the cellular option you should attach a suitable cellular antenna to the module using the antennaconnector labeled ldquoGSMrdquo

Modem Status LED

The blue LED on the modem board shows the current modem status

LED Status SIM5360 (3G) SIM7600 (4G)ON Searching network Searching networkFast blinking (200ms) Data Transmit Data Transmit 4G registeredSlow blinking (800ms) Registered network 2G3G registered networkOFF Power off Sleep Power off Sleep

223 GPSGNSS Antenna

Some OVMS vehicles can read the GPS signals from the car communication networks directly and do not require anyadditional hardware For others the OVMS v3 modem option also includes a GNSSGPS satellite tracking receiver

If you are using this option you should connect a suitable active GPS antenna to the connector labelled ldquoGPSrdquo

16 Chapter 2 User Guide

Open Vehicles

224 Vehicle Connection

The connection to the vehicle is by the DB9 connector labelled ldquoVEHICLErdquo This provides power to the OVMSmodule as well as connection to the vehicle communication networks

Different vehicles require different cables so you should refer to the appropriate vehicle section of this user guide todetermine which is correct for yours

225 OVMS Server v2

The OVMS Server v2 protocol is a proprietary protocol used to communicate between the vehicle and an OVMS v2server as well as from that server to the cellphone apps To provide compatibility with existing OVMS v2 cellphoneapps and servers OVMS v3 includes full support for the OVMS v2 protocol

226 OVMS Server v3

The OVMS Server v3 protocol is MQTT This is an industry standard protocol and means an OVMS v3 module cancommunicate with any standard MQTT server While this is the future of OVMS support for this is experimental atthe moment and production users should use OVMS Server v2 protocol

227 Upgrading from OVMS v1v2 to v3

The antenna and vehicle connectors for OVMS v3 are the same as for OVMS v2 and existing cablesantennas cangenerally be re-used for OVMS v3 Note however that the frequency ranges supported by individual 3G networksmay be different than 2G so may benefit from an antenna specifically designed for the 3G frequency ranges used

23 Installation

231 Pre-Installation Steps

WarningPrior to connecting the OVMS module to the vehicle or computer via USB if you have the GSM cellular option werecommend you connect a GSM antenna GSM systems are designed to always operate with an antenna andpowering on one without could damage the equipment

Prior to installation please make sure you have the following available

1 The OVMS v3 module in itrsquos enclosure

2 A micro-usb cable suitable for connecting to your computer

3 A laptop or desktop computer (if necessary)

23 Installation 17

Open Vehicles

4 A cable suitable for connecting to your vehicle

5 A GSM antenna (if you are using the cellular option)

6 A GPS antenna (if your vehicle type requires one)

You should also have ready access to this User Guide and wifi connectivity to the Internet

232 OVMS Module Installation

Powering the module

If you intend to configure the module on your desk before connecting it to the vehicle make sure your USB portdelivers power (around 500mA depending on modem and wifi activity) We recommend using a USB hub with aseparate power supply or a direct port of your laptop PC

Warning The v33 LTE Modem (SIMCOM 7600G) may not be able to connect or not power up at all whenpowered from USB even with a powered USB hub

If you cannot get the cellular connection to work on your desk try powering from your carrsquos OBD port first

Another option is adding a 12V supply on your desk eg using a standard RC 3S LiPo battery (connect 12V+ toOBD pin 16 and GND- to OBD pin 4) You can connect USB and OBD12V supply simultaneously be aware themodule will boot as soon as any power source is present

OVMS Server account

If you want to use the OVMS App andor server based telemetry services yoursquoll need an OVMS v2 server account Ifyou have not registered for an OVMS server account yet you can do so before starting the wizard to avoid needing toswitch networks in between There are currently two public v2 OVMS servers

1 Asia-Pacific httpswwwopenvehiclescom

2 Europe httpsdexters-webde

You will need to create a user account first Within your user account you then need to create a vehicle account Yoursquollneed to pick a unique vehicle ID for this eg your vehicle license plate number

Initial Connection (Wifi and Browser)

From the factory or after a factory reset your OVMS module will be running an access point with the followingcredentials

SSID OVMS Password OVMSinit

As this is insecure you should take care not to leave the module running unconfigured

Using your laptoptabletphone establish a wifi connection to the module You should see an IP address in the range1921684x allocated with a gateway at 19216841

Note Some smartphones (eg Android) require mobile data to be switched off to use a WiFi connection without ainterent connectivity

Launch your web browser and connect as follows

URL http19216841

Once connected you will be presented with a screen as follows

18 Chapter 2 User Guide

Open Vehicles

23 Installation 19

Open Vehicles

Setup wizard

The first thing to do is run the setup wizard Click Start setup now The wizard takes you through the initial setup infive simple steps telling you what it is doing and what to expect for each step

20 Chapter 2 User Guide

Open Vehicles

23 Installation 21

Open Vehicles

The wizard will need to reconfigure the module for the Wifi setup read the notes and be prepared to reconnect to themodule as necessary

Note we recommend not to use a password manager during the setup process Some browsers eg Chrome will fillin the module ID as the username which is wrong The login username needs to be admin

The wizard should be able to restore access after problems occurring in the process As a last resort if it fails to recoverat some point you can always do a factory reset and start over again

Manual configuration

After finishing the wizard or if you prefer to do a manual setup the configuration menus will provide single pages foreach module function These also contain advanced options for the features so itrsquos worth having a look

Vehicle Configuration

Go to Config Vehicle

Yoursquoll want to enter your vehicle type Vehicle ID (the same as you registered on the OVMS server) and distance unitsYou can also optionally enter your timezone (see httpswwwgnuorgsoftwarelibcmanualhtml_nodeTZ-Variablehtml for an article on GLIBC timezones for information on the format of this a list of suitable zone strings can alsobe found here httpsremotemonitoringsystemscatime-zone-abbreviationsphp)

OVMS Server v2 Configuration

Go to Config Server V2 to configure the connection to the OVMS v2 server you will be using

22 Chapter 2 User Guide

Open Vehicles

You should enter the server host (apiopenvehiclescom or ovmsdexters-webde usually) and vehicle password (akaserver password - as entered on the server when you registered your vehicle) The Vehicle ID field should already bethere and the other parameters are optional

Auto Start Configuration

OVMS has a powerful scripting language that can be used for complex configurations but to get started it is simplestto use the Auto Start system You get to this from the web interface by clicking Config Autostart

23 Installation 23

Open Vehicles

You will usually want to click to Enable auto start and Start server v2 The other fields should have been populatedcorrectly automatically for you If you are using the optional modem module you should also click Start modem toenable the modem

Once complete you can Save amp reboot to activate your new configuration

WarningDo not set the Wifi mode to AP+Client or Client before having configured your Wifi network

If you have configured this manually the Wifi network may not start automatically Log in using a USB terminal andeither do a factory reset (see Module Factory Reset) or (better) issue enable to enter secure mode then issue configset auto wifimode ap and reboot

Networking Options

OVMS v3 has a number of networking options to choose from You can either use these individually or combine themto provide failover and alternative network connectivity arrangements

1 Wifi Client OVMS can connect to a WiFi Access Point using standard WiFi (80211 bgn) protocols toconnect to a SSID (Access Point name) with associated password In simple client mode you can connect onlyto a single pre-specified SSID Alternatively you can use the scanning client mode to connect to any known

24 Chapter 2 User Guide

Open Vehicles

WiFi Access Point when within range (note however that this is not possible when you run both client andaccess point on the same OVMS device)

2 Wifi Access Point OVMS can operate as a WiFi Access Point itself using standard WiFi (80211 bgn) pro-tocols This allows users to connect to the OVMS module itself Note that OVMS v3 is not intended to be ahotspot and users cannot access the Internet via the OVMS module Wifi Access Point mode can be combinedwith simple Wifi Client mode to provide an access point for maintenance of the module as well as a client toaccess the Internet via another Access Point within range

3 Cellular Data OVMS supports optional modems to provide cellular connectivity These are configured viaConfig Modem

233 GSM SIM Activation (Hologram)

OVMS has partnered with Hologram and to provide a Hologram GSM SIM pre-installed in every OVMS kit purchasedfrom our partners in Europe and USA For modules purchased from China we recommend you purchase a HologramSIM directly from the hologramio store (also available on Amazon) In addition Hologram have provided OVMS acoupon code valid for US$5 off data usage

Hologram Coupon Code OVMS

To activate your Hologram SIM register at httpsdashboardhologramio then invoke ldquoActivate SIMrdquo in the dash-board

Note You donrsquot need to purchase a phone number for your SIM right now as there is no SMS support in V3 yet Forthe current status of SMS support see

bull Issue 62 SMS Notifications

bull Issue 63 SMS Command Gateway

When activating your Hologram SIM yoursquoll need to enter the ICCID written on the SIM itself You can also get thatelectronically (without having to open up the enclosure) from the OVMS web or terminal shell (Tools gt Shell) withthe following command

OVMS metric list mnetmdmiccid

The ICCID is also displayed during the setup process and on the modem configuration page when using the web userinterface

23 Installation 25

Open Vehicles

234 Firmware Update

The factory firmware that is provided with the module may be quite out of date You should perform a firmware updateto ensure that you have the latest firmware You can do this either over Wifi client connections or via an SD CARD

We recommend using the auto update system This will be preconfigured if you have used the setup wizard Theautomatic updates are done within a selectable hour of day and only if Wifi connectivity is available at the time

26 Chapter 2 User Guide

Open Vehicles

Flash from Web

You can typically just press the Flash now button and wait for completion

Flash from File

Using an SD CARD formatted as FAT download the firmware update and place it in a file called ovms3bin in theroot directory of the SD CARD Once the SD CARD is inserted the firmware update will start immediately

235 12V Monitoring

Note Since release 32006 the 12V calibration and alert setup can be done from the web UIrsquos vehicle configurationpage

As 12V batteries tend to die without warning and need to handle an additional unplanned constant load from theOVMS the module includes a 12V monitoring and alert system

Calibration

The 12V voltage is measured using the incoming voltage that powers the OVMS As the sensor used by the modulehas some manufacturing tolerances you should do an initial calibration Use a voltage meter to measure the actualvoltage somewhere suitable (eg at a 12V auxiliary equipment plug) calibrate the OVMS to show the same Thecalibration factor is set by

config set systemadc factor12v ltfactorgt

Calculate the ltfactorgt using oldFactor (displayedVoltage actualVoltage)

bull oldFactor is the old value set If you have not changed it yet it is 1957

bull displayedVoltage is the Voltage as displayed by the OVMS

bull actualVoltage is the Voltage as measured by hand using a voltmeter

The voltage is read once per second and smoothed over 5 samples so after changing the factor wait 5-10 seconds forthe new reading to settle

23 Installation 27

Open Vehicles

Configuration

The default 12V reference voltage (= fully charged amp calmed down voltage level) can be set by

config set vehicle 12vref ltvoltagegt

This config value initializes metric vb12vvoltageref on boot The metric will then be updated automati-cally if your vehicle supports the vecharging12v flag The measured reference voltage reflects the health of the12V battery and serves as the reference for the 12V alert if itrsquos higher than the configured default

The 12V alert threshold can be set by

config set vehicle 12valert ltvoltagediffgt

The 12V alert threshold is defined by a relative value to the 12v reference voltage If the actual 12V reading dropsbelow 12vref - 12valert the 12V alert is raised

The default reference voltage is 126V the default alert threshold 16V so the alert will be triggered if the voltagedrops below 110V This is suitable for standard lead-acid type batteries If yoursquove got another chemistry change thevalues accordingly

Related Metrics

Metric Example Value Meaningvb12vcurrent 06A Momentary current level at the 12V batteryvb12vvoltage 1328V Momentary voltage level at the 12V batteryvb12vvoltageref 1251V Reference voltage of the fully charged amp calmed down 12V batteryvb12vvoltagealert no If the 12V critical alert is active (yesno)vecharging12v yes If the 12V battery is charging or not (yesno)

Related Events

Event Data Purposevehiclealert12von 12V system voltage is below alert thresholdvehiclealert12voff 12V system voltage has recoveredvehiclecharge12vstart Vehicle 12V battery is chargingvehiclecharge12vstop Vehicle 12V battery has stopped charging

24 The OVMS Console

241 Console Connections

OVMS v3 includes a powerful command line console that can be accessed in various ways

1 Using a micro USB cable to a host computer

If the OVMS is not recognised via USB download the driver from SILABS website You will also need asuitable terminal emulator The baud rate is 115200 and you should not enable hardware flow control

2 TELNET (over wifi)

28 Chapter 2 User Guide

Open Vehicles

Note that for security reasons the telnet server component is not enabled in the default productionfirmware (but may be available in custom builds) If Telnet is available telnet to the IP address of themodule (or ltvehicleidgtlocal MDNS address)

3 SSH (over wifi)

SSH to the IP address of the module (or ltvehicleidgtlocal MDNS address) Note that when first bootedwith a network connection the module takes a minute or so to generate server side keys (which are storedin the config store)

4 Web Console SHELL tab

Use a web browser to connect to the IP address of the module (or ltvehicleidgtlocal MDNS address) ASHELL tab is available for direct command line console access

5 Remote Apps

The OVMS Android App currently includes a shell screen that can be used to issue command line consolecommands via the OVMS server v2 This functionality is not currently available in the iPhoneiPad App

6 SMS

Console commands can be issued via SMS

USB Console

Our recommendations for the USB console are as follows

1 You can use a Windows Linux Mac OSX workstation or an Android device with a USB OTG adapter cable

2 If your operating system does not have the SILABS USB driver you can download the driver from SILABSwebsite If you use Linux and your distribution includes the braille display driver ldquobrlttyrdquo you may need touninstall that as it claims any CP2102 device to be a braille device This applies eg to openSuSE 150

3 Plug in the module to your PClaptop using a micro USB cable Check to ensure a serial port appears (using theSILABS driver) For OSX and Linux this will normally appear as devttySLAB_USBtoUART or devttyUSB0(or 12 if other serial devices are connected) List your devices using ldquols devUSBrdquo

4 Once the serial port is available you will need a terminal emulator

bull For OSX the simplest is the built-in SCREEN utility You run this as screen -L devttySLAB_USBtoUART 115200 But note that the device path may be different for you - check with lsquolsdevUSBrsquo You can use lsquocontrol-a control-yrsquo or lsquocontrol-a k yrsquo (three key sequences) to exit the screenThe ldquo-Lrdquo option tells screen to capture a log of your session into the file ldquoscreenlogltngtrdquo

bull For Linux the SCREEN utility is also simple to get If it is not included with your distribution you can simplyyum install screen or apt-get install screen (depending on your distribution) From there the command is thesame as for OSX Alternatively you can use minicom (which is included with many linux distributions)

bull For Windows a simple approach is to download the free PUTTY terminal emulator This supports both directASYNC (over USB) connections as well as SSH (network) You can download putty using this link

bull For Android there are multiple USB serial Apps in the Play store A good recommendation is Serial USBTerminal by Kai Morich

5 Once you have established the connection press ENTER to see the ldquoOVMSgtrdquo prompt

SSH Console

A workstation (Mac Linux Window) on the same wifi network as the OVMS module can use the ssh protocol toconnect In Windows you can use the free PUTTY ssh client In Linux and OSX ssh is built-in

24 The OVMS Console 29

Open Vehicles

The syntax is simply

ssh userip

Where lsquouserrsquo is the username (normally lsquoovmsrsquo) and lsquoiprsquo is the IP address of the OVMS v3 module In environmentssupporting mDNS networking you should also be able to connect using the mDNS name ltvehicleidgtlocal Thepassword you enter is the module password

If you use ssh publicprivate key pairs you can store your public key on the OVMS v3 module to take advantage ofpasswordless login

OVMS config set sshkeys ltusergt ltpublic-keygt

In this case lsquouserrsquo is the username you use to ssh and the public key is your RSA public key (the long base64 blob oftext you find in id-rsapub between lsquossh-rsarsquo and your usernamecomment)

You can also use SCP to copy files to and from the OVMS v3 VFS

Note With OpenSSH version 88 (or later) the ssh-rsa algorithm has been disabled by default and needs to beenabled manually either on the command line

ssh -o HostkeyAlgorithms=+ssh-rsa -o PubkeyAcceptedAlgorithms=+ssh-rsa userip

or by adding a host entry to your ~sshconfig file

Host ovmsnamelocalHostkeyAlgorithms +ssh-rsaPubkeyAcceptedAlgorithms +ssh-rsa

242 Console Basics

Letrsquos use SSH to demonstrate this

$ ssh ovmsovmslocal

Welcome to the Open Vehicle Monitoring System (OVMS) - SSH ConsoleFirmware 31003-2-g7ea18b4-dirtyfactorymainHardware OVMS WIFI BLE BT cores=2 rev=ESP321

OVMS

When first connecting using USB the console will be in non-secure mode (as indicated by the ldquoOVMSgtrdquo prompt)Here only a limited number of commands are available (such as viewing network status modem status or systemtime) To get to secure mode enter the command lsquoenablersquo and provide the module password The prompt will thenchange to ldquoOVMSrdquo

OVMSgt enablePasswordSecure modeOVMS

You can enter the lsquodisablersquo command to get out of secure mode and lsquoexitrsquo to exit the console completely

When connecting via a pre-authenticated protocol such as SSH you will be in secure mode automatically

At any time you can use ldquordquo to show the available commands For example

30 Chapter 2 User Guide

Open Vehicles

OVMS Run a scriptboot BOOT frameworkcan CAN frameworkcharge Charging frameworkco CANopen frameworkconfig CONFIG frameworkdisable Leave secure mode (disable access to most commands)egpio EGPIO frameworkenable Enter secure mode (enable access to all commands)event EVENT frameworkexit End console sessionhelp Ask for helphomelink Activate specified homelink buttonlocation LOCATION frameworklock Lock vehiclelog LOG frameworkmetrics METRICS frameworkmodule MODULE frameworknetwork NETWORK frameworknotify NOTIFICATION frameworkobdii OBDII frameworkota OTA frameworkpower Power controlre RE frameworkscript Run a scriptsd SD CARD frameworkserver OVMS Server Connection frameworkmodem MODEM frameworkstat Show vehicle statusstore STORE frameworktest Test frameworktime TIME frameworkunlock Unlock vehicleunvalet Deactivate valet modevalet Activate valet modevehicle Vehicle frameworkvfs Virtual File System frameworkwakeup Wake up vehiclewifi WIFI framework

You can also use ldquordquo as part of a command to expand on the available options within that command root

OVMS wifi mode WIFI mode frameworkscan Perform a wifi scanstatus Show wifi status

OVMS wifi mode ap Acts as a WIFI Access Pointapclient Acts as a WIFI Access Point and Clientclient Connect to a WIFI network as a clientoff Turn off wifi networking

OVMS wifi mode client Usage wifi mode client ltssidgt ltbssidgt

Command tokens can be abbreviated so long as enough characters are entered to uniquely identify the command Op-

24 The OVMS Console 31

Open Vehicles

tionally pressing TAB at that point will auto-complete the token If the abbreviated form is not sufficient to be unique(in particular if no characters have been entered yet) then TAB will show a concise list of the possible subcommandsand retype the portion of the command line already entered so it can be completed

OVMS wifi ltTABgtmode scan statusOVMS wifi

Pressing TAB is legal at any point in the command if there is nothing more that can be completed automatically thenthere will just be no response to the TAB

25 Logging

251 Logging to the Console

Components of the OVMS system output diagnostic logs (information warnings etc) You can choose to displaythese logs on your connected console with the lsquolog monitor yesnorsquo command

OVMS log monitor Usage log monitor [no|yes]no Dont monitor logyes Monitor log

By default the USB console will have log monitoring lsquoyesrsquo SSH (and telnet if enabled) lsquonorsquo

The web shell does not use the log monitor command but has a checkbox in the upper right corner of the shellpanel instead The keyboard shortcut for the checkbox is L (Alt-L or Alt-Shift-L depending on your browser) Theweb frontend gets the continuous stream of log messages independent of the shell panel or the monitoring being activeand shows the last 100 messages received when opening the shell panel

Logs are output at various levels of verbosity and you can control what is shown both globally and on a per-componentbasis

OVMS log level none No logging (0)error Log at the ERROR level (1)warn Log at the WARN level (2)info Log at the INFO level (3)debug Log at the DEBUG level (4)verbose Log at the VERBOSE level (5)

(Note sorted here for level clarity)

The syntax of this command is log level ltlevelgt [ltcomponentgt] If the component is not specified thelevel applies to all components that donrsquot get a level set explicitly afterwards The levels increase in verbosity andsetting a particular level will also include all log output at a lower level of verbosity (so for example setting level infowill also include warn and error output)

A log line typically looks like this

I (32244049) ovms-server-v2 One or more peers have connectedLog message

Component nameTimestamp (milliseconds since boot)

Log level (I=INFO)

32 Chapter 2 User Guide

Open Vehicles

Log levels are applied on log message generation so a later change to a higher level will not reveal messages generatedpreviously

252 Logging to SD CARD

You can also choose to store logs on SD CARD This is very useful to capture debugging information for the develop-ers as the log will show what happened before a crash or misbehaviour

We recommend creating a directory to store logs ie

OVMS vfs mkdir sdlogs

To enable logging to a file issue for example

OVMS log file sdlogs20180420log

The destination file can be changed any time To disable logging to the file issue log close to restart loggingafter a close issue log open You may choose an arbitrary file name good practice is using some date andor bugidentification tag Note logging will append to the file if it already exists To remove a file use vfs rm

File logging does not persist over a reboot or crash (unless configured as shown below) you can use a script bound tothe sdmounted event to re-enable file logging automatically or configure automatic logging (see below)

You can use the webserver to view and download the files The webserver default configuration enables directorylistings and access to files located under the document root directory which is sd by default Any path not bound toan internal webserver function is served from the document root So you can get an inventory of your log files now atthe URL

http19216841logs

and access your log files from there or directly by their respective URLs Another option to retrieve the files withoutunmounting the SD card is by scp if you have configured SSH access

253 Logging Configuration

Use the web UI or config command to configure your log levels and file setup to be applied automatically on boot

OVMS config list loglog (readable writeable)

fileenable yesfilekeepdays 7filemaxsize 1024filepath sdlogslogfilesyncperiod 3level infolevelmodem infolevelv-twizy verboselevelwebserver debug

25 Logging 33

Open Vehicles

The log command can be used for temporary changes if you change the configuration it will be applied as a wholereplacing your temporary setup

If a maximum file size gt0 is configured the file will be closed and archived when the size is reached The archivename consists of the log file name with added suffix of the timestamp ie sdlogslog20180421-140356Using a logs directory will keep all your archived logs accessible at one place If filekeepdays is defined olderarchived logs will automatically be deleted on a daily base

Take care not to remove an SD card while logging to it is active (or any running file access) The log file should stillbe consistent as it is synchronized after every write but the SD file system currently cannot cope with SD removalwith open files You will need to reboot the module To avoid this always use the ldquoCloserdquo button or the log closecommand before removing the SD card

You donrsquot need to re-enable logging to an SD path after insertion the module will watch for the mount event andautomatically start logging to it

254 Performance Impact

SD card IO has an impact on the module performance So file logging should generally be switched off or runon a low level (ie ldquoinfordquo or ldquowarnrdquo) unless yoursquore hunting some bug or checking some details of operation Wealso recommend using a fast SD card for logging (check the speed with sd status check if you can raise configsdcard maxfreqkhz to 20000 kHz)

34 Chapter 2 User Guide

Open Vehicles

File logging is done by a separate task but flushing the file buffers to the SD card still may block the logging CPUcore or even both CPU cores for a short period To reduce the impact of this the log task by default only flushes thebuffer after 15 seconds of log inactivity This means you may lose the last log messages before a crash

To change the flush behaviour set config filesyncperiod to

bull 0 = never flush (ie only at log close log cycle)

bull lt 0 = flush every n log messages (ie -1 = flush after every message)

bull gt 0 = flush after n2 seconds idle

The log task counts the time spent for flushes and outputs it with the log status command

OVMS log statusLog listeners 3File logging status active

Log file path sdlogslogCurrent size 8170 kBCycle size 1024 kBCycle count 8Dropped messages 0Messages logged 70721Total fsync time 6511 s

This is an example for the default configuration of filesyncperiod 3 the logging here has on average taken6511 70721 = 9 ms per message

26 Configuration

OVMS stores all itrsquos configuration in a standardised protected configuration area accessed by the lsquoconfigrsquo commandThe configurations are organised as follows

ltparametergt ltinstancegt = ltvaluegt

For example

Parameter Instance Valuevehicle id OVMSBOXwifissid MYSSID MyPasswordauto init yes

Each parameter can be defined (by the component that owns it) as having readable andor writeable attributes andthese act as access control for the parameters

bull A lsquowriteablersquo parameter allows values to be created deleted and modified

bull A lsquoreadablersquo parameter allows values to be seen Instance names can be seen on non-readable parameters (it isjust the values themselves that are protected)

For example the lsquovehiclersquo parameter is readable and writeable

OVMS config list vehiclevehicle (readable writeable)

id MYCARtimezone HKT-8

But the lsquowifissidrsquo parameter is only writeable

26 Configuration 35

Open Vehicles

OVMS config list wifissidwifissid (protected writeable)

MYSSIDMyOtherSSIDMyNeighbour

The lsquoconfigrsquo command is used to manipulate these configurations as is fairly self-explanatory

OVMS config list Show configuration parametersinstancesrm Remove parameterinstanceset Set parameterinstance=value

You can add new instances to parameters simply by setting them

Beginning with firmware release 32009 a dedicated configuration section usr is provided for plugins Take care toprefix all instances introduced by a unique plugin name so your plugin can nicely coexist with others

27 WiFi Networking

The OVMS WiFi system is based on the ESP32 integrated WiFi transceiver It uses and provides WiFi protocols80211 bgn and WPA2 authentication The current hardware can only use 24 GHz frequency bands

The WiFi antenna is built into the ESP32 module (PCB antenna) Itrsquos possible to replace that by an external antennabut yoursquoll need electronics knowledge and SMD soldering skills amp equipment

271 Client amp Access Point Modes

The OVMS WiFi network can be configured as a client (connecting to existing WiFi networks) andor access point(providing itrsquos own private WiFi network) Both modes can be run simultaneously which is the recommended defaultThat way you can always connect to your module via WiFi

OVMS wifi statusPower onMode Access-Point + Client mode

STA SSID WLAN-214677 (-787 dBm) [scanning]MAC 30aea45fe7ecIP 19216821022552552550GW 19216821AP 7cff4d152f86

AP SSID DEX106EMAC 30aea45fe7edIP 19216841AP Stations 0

In client mode the module can connect to a fixed network or automatically scan all channels for known networks toconnect to (ldquoscanning moderdquo) Scanning mode is configured by enabling client mode without a specific client SSID

The module will normally receive an IP address gateway and DNS from the WiFi access point by DHCP See belowon how to connect with a manual static IP setup

36 Chapter 2 User Guide

Open Vehicles

In access point mode the module provides access for other WiFi devices on a private network with the IP subnet1921684024 The modulersquos IP address on this network is 19216841 The module does not provide aDNS or routing to a public WiFi or GSM network on this subnet

You can define multiple AP networks but only one can be active at a time

Use the wifi mode command to manually set the mode use the auto start configuration to configure your defaultmode and networks

Note The module cannot act as a mobile hotspot ie provide access to the internet via itrsquos modem connectionThatrsquos in part due to security considerations and in part due to hardware limitations If you need this considerinstalling a dedicated mobile hotspot and using that one via WiFi instead of the modem for the modulersquos internetaccess (you wonrsquot need the modem in this setup)

272 Scanning for Networks

To manually scan your environment for available WiFi networks do a wifi scan

OVMS wifi scanScanning for WIFI Access Points

AP SSID MAC ADDRESS CHAN RSSI AUTHENTICATION================================ ================= ==== ==== ==============WLAN-214677 7cff4d152f86 1 -83 WPA2_PSKTelekom_FON 78dd1209dcbe 11 -84 OPENWLAN-184248 78dd1209dcbc 11 -85 WPA2_PSK===========================================================================Scan complete 3 access point(s) found

This can also be done in the web UIrsquos WiFi client network configuration page by clicking on the Select button

After the module lost connection to a network a scan is performed automatically every 10 seconds until a new con-nection can be established If yoursquod like to see the background scans and results in the log enable log level verbosefor component esp32wifi

Scan Troubleshooting

If the module doesnrsquot find your access point or can only see it occasionally in the scan results you may need to raiseyour scan times This has been observed on some older Android hotspots

By default the module will scan each channel for 120 milliseconds To raise that set your scan time in millisecondsusing the config command like this eg to 200 milliseconds

OVMS config set network wifiscantmin 200

200 milliseconds have been reported to solve the Android hotspot issue In addition to the tmin configuration youmay need to allow more time looking for further access points after finding the first one Do so by setting tmax eg

OVMS config set network wifiscantmax 300

Note that every increase will increase the time a full scan takes so donrsquot set too high values Too high values mayresult in connection drops on the AP network of the module

27 WiFi Networking 37

Open Vehicles

273 WiFi Signal Quality

Note For best performance yoursquoll need a signal level of -85 dBm or higher

bull Open the web status page the Wifi signal level can be monitored in the ldquoLiverdquo box

bull Try moving turning tilting your router ndash centimeters can make a huge difference After each move step backfrom the router and watch how the signal develops

bull Try switching to another Wifi channel (router configuration)

bull Try adding a repeater half way from the router to the car

The module monitors the WiFi client signal quality and drops a WiFi connection (switches to modem if available) if itbecomes too bad The WiFi connection will be kept active and monitored and as the signal recovers the module willautomatically reconnect to the AP

The default threshold is to stop using the connection if it drops below -89 dBm A connection is assumed to be usableif the signal is above -87 dBm

Depending on your WiFi environment the WiFi connection may still be usable at lower signal levels but it normallywill need stable levels above -87 dBm

To tweak the thresholds use the web UI WiFi configuration or change the following configuration variables

OVMS config set network wifisqgood -870OVMS config set network wifisqbad -890

274 WiFi Mesh Configuration

In normal operation the module will try to stick to an established connection as long as possible If signal qualitydrops it will switch to the modem connection but monitor the WiFi signal and reassociate to the current AP if possible

If using a mesh network you may want to force scanning for a better mesh AP as soon as the signal drops below theldquobadrdquo threshold To do so set the network configuration wifibadreconnect to true either using the web UIor by doing

OVMS config set network wifibadreconnect yes

With this the module will perform a full WiFi reconnect cycle as soon as the signal becomes bad

This is meant for the car moving between cells of your mesh network eg if the first cell is checked in at your gatebut a much better cell becomes available in your garage car port It should not be enabled if your Wifi signal isgenerally poor as that will cause many disconnects amp reconnects

275 Static IP SSID Configuration

To connect with a static client address instead of using DHCP use the wifi ip static command

OVMS wifi ip static [ltipgt ltsubnetgt ltgatewaygt]

The gateway will also be used as the DNS

To configure persistent static details for a known SSID set these using the following configuration syntax

38 Chapter 2 User Guide

Open Vehicles

OVMS config set wifissid ltssidgtovmsstaticip ltipgtltsubnetgtltgatewaygt

You can also force connection to a specific AP by itrsquos MAC address ldquoBSSIDrdquo in WiFi terms To do so you need tosupply the MAC address as a second argument to the wifi mode client or as the third argument to the wifimode apclient command

OVMS wifi mode client ltssidgt ltbssidgt

OVMS wifi mode apclient ltapssidgt ltssidgt ltbssidgt

This currently needs manual activation by command Hint use a script for example bound to a location

276 AP Bandwidth Configuration

In normal operation the default AP bandwidth is set to 20Mhz to reduce interference and improve the signal quality Ifa wider 40Mhz bandwidth is preferred eg for high throughput logging set the network configuration wifiapbwwith the command

OVMS config set network wifiapbw 40

Once the parameter is set the module will require rebooting to take effect The default bandwidth can be restored byeither removing the parameter or setting it to 20

28 Virtual File System (VFS)

OVMS includes a Virtual File System (VFS) used to unify all storage in the system The primary configuration andscripting storage is mounted as lsquostorersquo and the SD card as lsquosdrsquo A lsquovfsrsquo set of commands is provided for basicmanipulation of these stores

OVMS vfs append VFS Append a line to a filecat VFS Display a filecp VFS Copy a fileedit VFS Edit a filels VFS Directory Listingmkdir VFS Create a directorymv VFS Rename a filerm VFS Delete a filermdir VFS Delete a directorystat VFS Status of a filetail VFS Output tail of a file

Please take care This is a very small microcontroller based system with limited storage The store area should onlybe used for storage of configurations and small scripts The sd SD CARD area is more flexibly and can be used forstoring of configuration logs firmware images etc

281 Network Access

Network access to the VFS is available via SCP or through the web server

SCP can access the whole file system and is readwrite

28 Virtual File System (VFS) 39

Open Vehicles

copy a new firmware to the sd card on an OVMS named leaf in my ssh configscp buildovms3bin leafsddev_ovms3bin

copy a config backup from OVMS named leaf to my local directoryscp leafsdbackupcfg-2019-12-05zip

In the upload example the firmware can then be loaded with the OTA flash vfs command

The web server offers read access rooted at the sd card An example retrieving that same config file from the SCPexample would look like

httpleaf-abrlocalbackupcfg-2019-12-05zip

29 Metrics

Metrics are at the heart of the OVMS v3 system They are strongly typed named parameters with values in specificunits (and able to be automatically converted to other units) For example a metric to record the motor temperaturemay be an integer in Celsius units and may be convertible to Fahrenheit

The full list of metrics available can be shown

OVMS metrics listmfreeram 4232852mhardware OVMS WIFI BLE BT cores=2 rev=ESP321mmonotonic 3568Secvplatitude 222809vplongitude 114161vpodometer 100000Kmvpsatcount 12vpspeed 0Kphvptrip 0Kmvtalert 0001vthealth 95939674vtpressure 2068432164832757917579kPavttemp 33333438degCvtype DEMO

You can filter the metrics list output for names matching a given substring for example metrics listvolt will show all voltage related metrics

A base OVMS v3 system has more than 100 metrics available (see below) and vehicle modules can add more for theirown uses (see vehicle sections)

In general vehicle modules (and some other system components) are responsible for updating the metrics and serverconnections read those metrics reformat them and send them on to servers and Apps (for eventual display to the user)Status commands (such as STAT) also read these metrics and display them in user-friendly forms

OVMS statNot chargingSOC 500Ideal range 200KmEst range 160KmODO 1000000KmCAC 1600AhSOH 100

40 Chapter 2 User Guide

Open Vehicles

For developer use there are also some other metric commands used to manually modify a metricrsquos value (for testingand simulation purposes) and trace changes

OVMS metrics list Show all metricspersist Show persistent metrics infoset Set the value of a metrictrace METRIC trace framework

Some metrics are presistent across warm reboots This prevents values such as SOC from being lost when firmware isupdated (or in the event of a crash) You can display these with metrics list -p and view general informationabout presistent metrics with metrics persist

291 Standard Metrics

Metric name Example value Descriptionmfreeram 3275588 Total amount of free RAM in bytesmhardware OVMS WIFI BLE BT Base module hardware infommonotonic 49607Sec Uptime in secondsmnetmdmiccid 89490240001766080167 SIM ICCIDmnetmdmmodel 35316B09SIM5360E Modem module hardware infomnetmdmnetwork congstar Current GSM network providermnetmdmsq -101dBm and signal qualitymnetprovider WLAN-214677 Current primary network providermnetsq -79dBm signal qualitymnettype wifi and type (nonemodemwifi)mnetwifinetwork WLAN-214677 Current Wifi network SSIDmnetwifisq -791dBm and signal qualitymserial Reserved for module serial nomtasks 20 Task count (use module tasks to list)mtimeutc 1572590910Sec UTC time in secondsmversion 32005-155-g3133466f Firmware versionmegpioinput 012345679 EGPIO input port state (ports 0 9 present=high)megpiomonitor 89 EGPIO input monitoring portsmegpiooutput 45679 EGPIO output port statesv2connected yes yes = V2 (MP) server connectedsv2peers 1 V2 clients connectedsv3connected yes = V3 (MQTT) server connectedsv3peers V3 clients connectedvb12vcurrent 0A Auxiliary 12V battery momentary currentvb12vvoltage 1229V Auxiliary 12V battery momentary voltagevb12vvoltagealert yes = auxiliary battery under voltage alertvb12vvoltageref 123V Auxiliary 12V battery reference voltagevbctemp 1313 13degC Cell temperaturesvbctempalert 00 0 Cell temperature deviation alert level [0=normal 1=warning 2=alert]vbctempdevmax 143086 -129degC Cell maximum temperature deviation observedvbctempmax 1918 17degC Cell maximum temperaturesvbctempmin 1312 12degC Cell minimum temperaturesvbcvoltage 41054095 4105V Cell voltagesvbcvoltagealert 00 0 Cell voltage deviation alert level [0=normal 1=warning 2=alert]vbcvoltagedevmax 00096-00104 00125V Cell maximum voltage deviation observed

Continued on next page

29 Metrics 41

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvbcvoltagemax 41354125 414V Cell maximum voltagesvbcvoltagemin 38753865 388V Cell minimum voltagesvbcac 907796Ah Calculated battery pack capacityvbconsumption 0Whkm Main battery momentary consumptionvbcoulombrecd 475386Ah Main battery coulomb recovered on tripchargevbcoulombrecdtotal 9475386Ah Main battery coulomb recovered total (life time)vbcoulombused 0406013Ah Main battery coulomb used on tripvbcoulombusedtotal 835406013Ah Main battery coulomb used total (life time)vbcurrent 0A Main battery momentary current (output=positive)vbenergyrecd 269691kWh Main battery energy recovered on tripchargevbenergyrecdtotal 321269691kWh Main battery energy recovered total (life time)vbenergyused 00209496kWh Main battery energy used on tripvbenergyusedtotal 31770209496kWh Main battery energy used total (life time)vbhealth General textual description of battery healthvbplevelavg 95897 Cell level - pack averagevbplevelmax 9641 Cell level - strongest cell in packvbplevelmin 94871 Cell level - weakest cell in packvbplevelstddev 0548 Cell level - pack standard deviationvbptempavg 13degC Cell temperature - pack averagevbptempmax 13degC Cell temperature - warmest cell in packvbptempmin 13degC Cell temperature - coldest cell in packvbptempstddev 0degC Cell temperature - current standard deviationvbptempstddevmax 073degC Cell temperature - maximum standard deviation observedvbpvoltageavg 41V Cell voltage - pack averagevbpvoltagegrad 00032V Cell voltage - gradient of current seriesvbpvoltagemax 4105V Cell voltage - strongest cell in packvbpvoltagemin 409V Cell voltage - weakest cell in packvbpvoltagestddev 000535V Cell voltage - current standard deviationvbpvoltagestddevmax 000783V Cell voltage - maximum standard deviation observedvbpower 0kW Main battery momentary power (output=positive)vbrangeest 99km Estimated rangevbrangefull 508km Ideal range at 100 SOC amp current conditionsvbrangeideal 48km Ideal rangevbrangespeed 216kmh Momentary ideal range gainloss (chargedischarge) speedvbsoc 963 State of chargevbsoh 85 State of healthvbtemp 13degC Main battery momentary temperaturevbvoltage 574V Main battery momentary voltagevc12vcurrent 78A Output current of DCDC-convertervc12vpower 123W Output power of DCDC-convertervc12vtemp 345degC Temperature of DCDC-convertervc12vvoltage 123V Output voltage of DCDC-convertervccharging no yes = currently chargingvcclimit 0A Maximum charger output currentvccurrent 125A Momentary charger output currentvcdurationfull 25Min Estimated time remaing for full chargevcdurationrange -1Min for sufficient rangevcdurationsoc 0Min for sufficient SOCvcefficiency 876 Momentary charger efficiency

Continued on next page

42 Chapter 2 User Guide

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvckwh 26969kWh Energy sum for running chargevckwhgrid 36969kWh Energy drawn from grid during running sessionvckwhgridtotal 25669kWh Energy drawn from grid total (life time)vclimitrange 0km Sufficient range limit for current chargevclimitsoc 80 Sufficient SOC limit for current chargevcmode standard standard range performance storagevcpilot no Pilot signal presentvcpower 125kW Momentary charger input powervcstate done charging topoff done prepare timerwait heating stoppedvcsubstate scheduledstop scheduledstart onrequest timerwait powerwait stopped interruptedvctemp 16degC Charger temperaturevctime 0Sec Duration of running chargevctimermode yes = timer enabledvctimerstart Time timer is due to start seconds since midnight UTCvctype undefined type1 type2 chademo roadster teslaus supercharger ccsvcvoltage 0V Momentary charger supply voltagevdcp yes yes = Charge port openvdfl yes = Front left door openvdfr yes = Front right door openvdhood yes = Hoodfrunk openvdrl yes = Rear left door openvdrr yes = Rear right door openvdtrunk yes = Trunk openvealarm yes = Alarm currently soundingveaux12v yes = 12V auxiliary system is on (base system awake)veawake no yes = Vehicle is fully awake (switched on by the user)vecconfig yes = ECUcontroller in configuration stateveclogin yes = Module logged in at ECUcontrollervecabintemp 20degC Cabin temperaturevecabinfan 100 Cabin fanvecabinsetpoint 24degC Cabin set pointvecabinintake fresh Cabin intake type (fresh recirc etc)vecabinvent feetface Cabin vent type (comma-separated list of feet face screen etc)vecharging12v no yes = 12V battery is chargingvecooling yes = Coolingvedrivemode 33882626 Active drive profile code (vehicle specific)vedrivetime 0Sec Seconds driving (turned on)vefootbrake 0 Brake pedal state []vegear Geardirection negative=reverse 0=neutralvehandbrake yes = Handbrake engagedveheadlights yes = Headlights onveheating yes = Heatingvehvac yes = HVAC activevelocked yes = Vehicle lockedveon no yes = Vehicle is in ldquoignitionrdquo state (drivable)veparktime 49608Sec Seconds parking (turned off)veregenbrake yes = Regenerative braking activeveservrange 12345km Distance to next scheduled maintenanceservice [km]veservtime 1572590910Sec Time of next scheduled maintenanceservice [Seconds]

Continued on next page

29 Metrics 43

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvetemp Ambient temperaturevethrottle 0 Drive pedal state []vevalet yes = Valet mode engagedvggenerating no True = currently delivering powervgclimit 0A Maximum generator input current (from battery)vgcurrent 125A Momentary generator input current (from battery)vgdurationempty 25Min Estimated time remaining for full dischargevgdurationrange -1Min for range limitvgdurationsoc 0Min for SOC limitvgefficiency 876 Momentary generator efficiencyvgkwh 26969kWh Energy sum generated in the running sessionvgkwhgrid 36969kWh Energy sent to grid during running sessionvgkwhgridtotal 25669kWh Energy sent to grid totalvglimitrange 0km Minimum range limit for generator modevglimitsoc 80 Minimum SOC limit for generator modevgmode standard Generator mode (TBD)vgpilot no Pilot signal presentvgpower 125kW Momentary generator output powervgstate done Generator state (TBD)vgsubstate Generator substate (TBD)vgtemp 16degC Generator temperaturevgtime 0Sec Duration of generator runningvgtimermode false True if generator timer enabledvgtimerstart Time generator is due to startvgtype Connection type (chademo ccs )vgvoltage 0V Momentary generator output voltagevitemp Inverter temperaturevipower 427kW Momentary inverter motor power (output=positive)viefficiency 982 Momentary inverter efficiencyvmrpm Motor speed (RPM)vmtemp 0degC Motor temperaturevpacceleration 0ms2 Vehicle accelerationvpaltitude 3278m GPS altitudevpdirection 312deg GPS directionvpgpshdop 13 GPS horizontal dilution of precision (smaller=better)vpgpslock no yes = has GPS satellite lockvpgpsmode AA ltGPSgtltGLONASSgt NADE (NoneAutonomousDifferentialEstimated)vpgpsspeed 0kmh GPS speed over groundvplatitude 513023 GPS latitudevplocation Home Name of current location if definedvplongitude 739006 GPS longitudevpodometer 579131km Vehicle odometervpsatcount 8 GPS satellite count in viewvpspeed 0kmh Vehicle speedvptrip 0km Trip odometervtalert 0001 TPMS tyre alert levels [0=normal 1=warning 2=alert]vthealth 95939674 TPMS tyre health statesvtpressure 20682164 kPa TPMS tyre pressuresvttemp 33333438degC TPMS tyre temperatures

Continued on next page

44 Chapter 2 User Guide

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvtype RT Vehicle type codevvin VF1ACVYB012345678 Vehicle identification number

210 Over The Air (OTA) Updates

OVMS v3 includes 16MB flash storage This is partition as

4MB for factory application image (factory)4MB for the first OTA application image (ota_0)4MB for a second OTA application image (ota_1)1MB for store configuration and scripting storageThe remainder for bootloader generic non-volatile storage and other data

In general the factory application firmware is stored in flash at the factory during module production That firmwareis never changed on production modules and is always kept as a failover backup

That leaves two firmwares for Over The Air (OTA) updates If the currently running firmware is the factory one anOTA updated firmware can be written to either of the OTA partitions If the current running firmware is ota_0 thenany new OTA updates will be written to ota_1 (and similarly if ota_1 is currently running then new OTA updates willbe written to ota_0) In this way the currently running firmware is never modified and is always available as a failoverbackup

You can check the status of OTA with the lsquoota statusrsquo command

OVMS ota statusFirmware 31003-2-g7ea18b4-dirtyfactorymain (build idf v31-dev-453-rarr˓g0f978bcb Apr 7 2018 162657)Server Available 31003Running partition factoryBoot partition factory

That is showing the currently running firmware as a custom image v31003-2-g7ea18b4-dirty running in factorypartition The running currently running partition is factory and the next time the system is booted it will run fromfactory as well

As a convenience if there is currently active wifi connectivity a network lookup will be performed and the currentlyavailable firmware version on the server will be shown In this case that is the standard 31003 release (as shown inthe lsquoServer Availablersquo line)

If we wanted to boot from ota_1 we can do this with lsquoota boot ota_1rsquo

OVMS ota boot ota_1Boot from ota_1 at 0x00810000 (size 0x00400000)

OVMS ota statusFirmware 31003-2-g7ea18b4-dirtyfactorymain (build idf v31-dev-453-rarr˓g0f978bcb Apr 7 2018 162657)Server Available 31003Running partition factoryBoot partition ota_1

If the bootloader fails to boot from the specified OTA firmware it will failover and boot from factory

We can flash firmware to OTA either from a file on VFS (normally sd) or over the Internet (via http) Letrsquos try asimple OTA update over HTTP

210 Over The Air (OTA) Updates 45

Open Vehicles

OVMS ota flash httpCurrent running partition is factoryTarget partition is ota_0Download firmware from apiopenvehiclescomfirmwareotav31mainovms3bin to ota_0Expected file size is 2100352Preparing flash partitionDownloading (100361 bytes so far)Downloading (200369 bytes so far)Downloading (300577 bytes so far)Downloading (1903977 bytes so far)Downloading (2004185 bytes so far)Download complete (at 2100352 bytes)Setting boot partitionOTA flash was successful

Flashed 2100352 bytes from apiopenvehiclescomfirmwareotav31mainovms3binNext boot will be from ota_0

OVMS ota statusFirmware 31003-2-g7ea18b4-dirtyfactorymain (build idf v31-dev-453-rarr˓g0f978bcb Apr 7 2018 162657)Server Available 31003Running partition factoryBoot partition ota_0

Rebooting now (with lsquomodule resetrsquo) would boot from the new ota_0 partition firmware

OVMS ota statusFirmware 31003ota_0main (build idf v31-dev-453-g0f978bcb Apr 7 2018rarr˓131119)Server Available 31003Running partition ota_0Boot partition ota_0

211 Boot Status

OVMS maintains a record of the reason for each boot in RAM that survives a reboot It can show you how long themodule has been running for and the reason for the last reboot

OVMS boot statusLast boot was 2244 second(s) ago

This is reset 9 since last power cycleDetected boot reason SoftResetCrash counters 0 total 0 earlyCPU0 boot reason was 12CPU1 boot reason was 12

If an unexpected (not lsquomodule resetrsquo) reboot occurs within the first 10 seconds of startup (usually during the boot-timeauto-loading of modules scripts etc) the crash counters are incremented If those crash counters reach 5 (without aclean reset in between) then the auto-loading of modules is disabled for the 6th boot

In case of a crash the output will also contain additional debug information ie

Last crash abort() was called on core 1Backtrace

(continues on next page)

46 Chapter 2 User Guide

Open Vehicles

(continued from previous page)

0x40092ccc 0x40092ec7 0x400dbf1b 0x40176ca9 0x40176c6d 0x400eebd9 0x4013aed90x4013b538 0x40139c15 0x40139df9 0x4013a701 0x4013a731

If the module can access the V2 server after the crash reboot it will also store this information along with the crashcounters in the server table ldquo-OVM-DebugCrashrdquo which will be kept on the server for 30 days

Please include this info when sending a bug report along with the output of ldquoota statusrdquo and ndash if available ndash any logfiles capturing the crash event (see Logging to SD CARD) If you can repeat the crash please try to capture a log atldquolog level verboserdquo

212 Events

Internally OVMS raises events whenever significant events occur An event is a lightweight message of a name plusoptionally associated internal binary data Event names are top-down structured (so can be filtered by prefix) andsufficient to identify the source and type of the event Individual vehicle types may also issue their own events andcustom user events are also possible

To bind a script to an event save the script in directory storeeventslteventnamegt (hint directories canbe created using the web UI editor) Whenever events are triggered all the scripts in the corresponding storeeventslteventnamegt directory are executed Event scripts are executed in alphanumerical order of their namesGood practice is to prefix script names with 2-3 digit numbers in steps of 10 or 100 (ie first script named 50-)so new scripts can easily be integrated at a specific place If the event script is written in Javascript be sure to add thesuffix js to the name Other names will be executed using the standard command interpreter

If you want to introduce a custom event (eg for a plugin) prefix the event name by usrltpluginnamegtfollowed by the event purpose Example Foglight

Be aware events are processed in series from a queue so depending on the system load and the list of registeredevent listeners there may be some delay from event generation to eg a script execution

2121 Commands

bull event list [ltkeygt] ndash Show registered listeners for all or events matching a key (part of the name)

bull event trace lton|offgt ndash Enabledisable logging of events at the ldquoinfordquo level Without tracing events arealso logged but at the ldquodebugrdquo level Ticker events are never logged

bull event raise [-dltdelay_msgt] lteventgt ndash Manually raise an event optionally with a delay You canraise any event you like but you shouldnrsquot raise system events without good knowledge of their effects

2122 Standard Events

Event Data Purposeappconnected One or more remote Apps have connectedappdisconnected No remote Apps are currently connectedcanopennodeemcy lteventgt CANopen node emergency receivedcanopennodestate lteventgt CANopen node state change receivedcanopenworkerstart ltworkergt CANopen bus worker task startedcanopenworkerstop ltworkergt CANopen bus worker task stoppingclockHHMM Per-minute local time hour HH minute MM

Continued on next page

212 Events 47

Open Vehicles

Table 2 ndash continued from previous pageEvent Data PurposeclockdayN Per-day local time day N (0=Sun 6=Sat)configchanged Configuration has changedconfigmounted Configuration is mounted and availableconfigunmounted Configuration is unmounted and unavailableegpioinputltportgtltstategt EGPIO input port change (port=0 9 state=highlow)egpiooutputltportgtltstategt EGPIO output port change (port=0 9 state=highlow)gpslockacquired GPS lock has been acquiredgpslocklost GPS lock has been losthousekeepinginit Housekeeping has initialisedlocationalertflatbedmoved GPS movement of parked vehicle detectedlocationenterltnamegt ltnamegt The specified geolocation has been enteredlocationleaveltnamegt ltnamegt The specified geolcation has been leftnetworkdown All networks are downnetworkinterfacechange Network interface change detectednetworkinterfaceup Network connection is establishednetworkmgrinit Network manager has initialisednetworkmgrstop Network managed has been stoppednetworkmodemdown Modem network is downnetworkmodemup Modem network is upnetworkreconfigured Networking has been reconfigurednetworkup One or more networks are upnetworkwifidown WIFI network is downnetworkwifistabad WIFI client has bad signal levelnetworkwifistagood WIFI client has good signal levelnetworkwifiup WIFI network is upnotifylttypegtltsubtypegt An info alert error notification is sentretoolsclearedall RE frame log has been clearedretoolsclearedchanged RE frame change flags clearedretoolscleareddiscovered RE frame discovery flags clearedretoolsmodeanalyse RE switched to analysis moderetoolsmodediscover RE switched to discovery moderetoolsstarted RE (reverse engineering) toolkit startedretoolsstopped RE toolkit stoppedretoolspidscanstart RE OBD2 PID scan startedretoolspidscanstop RE OBD2 PID scan stoppedretoolspidscandone RE OBD2 PID scan completedsdinsert The SD card has just been insertedsdmounted The SD card is mounted and ready to usesdremove The SD card has just been removedsdunmounted The SD card has completed unmountingsdunmounting The SD card is currently unmountingserverv2authenticating V2 server connection is authenticatingserverv2connected V2 server connection established onlineserverv2connecting V2 server connection in progressserverv2connectwait V2 server is pausing before connectionserverv2disconnected V2 server connection has been lostserverv2stopped V2 server has been stoppedserverv2waitnetwork V2 server connection is waiting for networkserverv2waitreconnect V2 server is pausing before re-connection

Continued on next page

48 Chapter 2 User Guide

Open Vehicles

Table 2 ndash continued from previous pageEvent Data Purposeserverv3authenticating V3 server connection is authenticatingserverv3connected V3 server connection established onlineserverv3connecting V3 server connection in progressserverv3connectwait V3 server is pausing before connectionserverv3disconnected V3 server connection has been lostserverv3stopped V3 server has been stoppedserverv3waitnetwork V3 server connection is waiting for networkserverv3waitreconnect V3 server is pausing before re-connectionserverwebsocketclosed ltcntgt Web server lost a websocket clientserverwebsocketopened ltcntgt Web server has a new websocket clientsystemmodemdown Modem has been disconnectedsystemmodemgotgps Modem GPS has obtained locksystemmodemgotip Modem received IP address from DATAsystemmodeminstalled Modem type has been identified driver installedsystemmodemlostgps Modem GPS has lost locksystemmodemmuxstart Modem MUX has startedsystemmodemnetdeepsleep Modem is deep sleeping DATA networksystemmodemnethold Modem is pausing DATA networksystemmodemnetloss Modem has lost DATA networksystemmodemnetsleep Modem is sleeping DATA networksystemmodemnetstart Modem is starting DATA networksystemmodemnetwait Modem is pausing before starting DATAsystemmodempoweredon Modem is powered onsystemmodempoweringon Modem is powering onsystemmodemreceivedussd ltussdgt A USSD message has been receivedsystemmodemstop Modem has been shut downsystemshutdown System has been shut downsystemshuttingdown System is shutting downsystemstart System is startingsystemvfsfilechanged ltpathgt VFS file updated (note only sent on some file changes)systemwifiapstaconnected WiFi access point got a new client connectionsystemwifiapstadisconnected WiFi access point lost a client connectionsystemwifiapstaipassigned WiFi access point assigned an IP address to a clientsystemwifiapstart WiFi access point mode startingsystemwifiapstop WiFi access point mode stoppingsystemwifidown WiFi is shutting downsystemwifiscandone WiFi scan has been finishedsystemwifistaconnected WiFi client is connected to a stationsystemwifistadisconnected WiFi client has disconnected from a stationsystemwifistagotip WiFi client got an IP addresssystemwifistalostip WiFi client lost itrsquos IP addresssystemwifistastart WiFi client mode startingticker1 One second has passed since last tickerticker10 Ten seconds have passedticker300 Five minutes have passedticker3600 One hour has passedticker60 One minute has passedticker600 Ten minutes have passedvehiclealarmoff Vehicle alarm has been disarmed

Continued on next page

212 Events 49

Open Vehicles

Table 2 ndash continued from previous pageEvent Data Purposevehiclealarmon Vehicle alarm has been armedvehiclealert12voff 12V system voltage has recoveredvehiclealert12von 12V system voltage is below alert thresholdvehiclealertbms BMS cellpack voltstemps exceeded thresholdsvehicleasleep Vehicle systems are asleepvehicleawake Vehicle systems are awakevehicleaux12von Vehicle 12V auxiliary system is on (base system awake)vehicleaux12voff Vehicle 12V auxiliary system is offvehiclecharge12vstart Vehicle 12V battery is chargingvehiclecharge12vstop Vehicle 12V battery has stopped chargingvehiclechargefinished Vehicle charge has completed normallyvehiclechargemode ltmodegt Vehicle charge mode has been setvehiclechargepilotoff Vehicle charge pilot signal is offvehiclechargepiloton Vehicle charge pilot signal is onvehiclechargeprepare Vehicle is preparing to chargevehiclechargestart Vehicle has started to chargevehiclechargestate ltstategt Vehicle charge state has changedvehiclechargestop Vehicle has stopped chargingvehiclechargetimermodeoff Vehicle charge timer mode has been switched offvehiclechargetimermodeon Vehicle charge timer mode has been switched onvehicledrivemodeltngt Vehicle drivemode has been set to profile ltngt (vehicle specific)vehiclegearforward Vehicle has been put in forward gearvehiclegearneutral Vehicle has been put in neutral gearvehiclegearreverse Vehicle has been put in reverse gearvehicleheadlightsoff Vehicle headlights are offvehicleheadlightson Vehicle headlights are onvehiclelocked Vehicle has been lockedvehicleoff Vehicle has been switched offvehicleon Vehicle has been switched onvehiclerequiregps A vehicle has indicated it requires GPSvehiclerequiregpstime A vehicle has indicated it requires GPS timevehicletypecleared Vehicle module has been unloadedvehicletypeset lttypegt Vehicle module has been loadedvehicleunlocked Vehicle has been unlockedvehiclevaletoff Vehicle valet mode deactivatedvehiclevaleton Vehicle valet mode activated

213 Geofenced Locations

This section of the manual is still under development

214 Notifications

Notifications can be simple text messages or transport structured data To distinguish by their purpose and originnotifications have a type and a subtype

Notifications are sent by the module via the available communication channels (clientserver connections) If a channelis temporarily down (eg due to a connection loss) the notifications for that channel will be kept in memory until thechannel is available again (Note this message queue does not survive a crash or reboot of the module)

50 Chapter 2 User Guide

Open Vehicles

Channels process notifications differently depending on the way they work For example a v2 server will forward textnotifications as push messages to connected smart phones and email readers a v3 server will publish them under anMQTT topic and the webserver will display the message as a modal dialog See the respective manual sections fordetails

Notification types currently defined

bull info ndash informational text messages

bull alert ndash alert text messages

bull error ndash error code messages

bull data ndash historical data records usually CSV formatted

bull stream ndash live data streaming (high bandwidth) usually JSON formatted

The standard subtypes used are listed below these can be used to filter messages Vehicles may introduce customnotifications and replace standard notifications see the respective user guide section for details

Subtypes by convention are given in lower case with dots lsquorsquordquo as structural separators

Notification channels currently defined

bull ovmsv2 ndash server v2 connection

bull ovmsv3 ndash server v3 connection

bull ovmsweb ndash websocket connections

bull pushover ndash pushover text messaging service

Channels may have multiple active instances (ldquoreadersrdquo) for example you can open multiple websocket connectionsChannels may exclude notification types Currently stream records are only supported on a websocket connectionall other types are supported on all channels

Use notify status to see the currently registered channels (ldquoreadersrdquo) Example

OVMS notify statusNotification system has 3 readers registered

pushover(1) verbosity=1024ovmsv2(2) verbosity=1024ovmsweb(3) verbosity=65535

Notify typesalert 0 entriesdata 0 entrieserror 0 entriesinfo 0 entriesstream 0 entries

The channelrsquos ldquoverbosityrdquo defines the supported maximum length of a textual notification message on that channelNotification senders should honor this but not all may do so If messages exceed this limit they may be truncated

2141 Sending notifications

You can send custom notifications from the shell or command scripts by using the notify raise command Thecommand can send the output of another command an error code (implies type error) or any text you enter Forexample to send a custom text message do

OVMS notify raise text info usrantonwelcome Hello wonderful person

214 Notifications 51

Open Vehicles

In this case the type would be info and the subtype usrantonwelcome The type must match one of thedefined types the subtype can be chosen arbitrarily Please use a unique usr prefix for custom notifications to avoidcollisions

To send a battery status command result do

OVMS notify raise command info batterystatus stat

To send notifications from Duktape scripts use the API call OvmsNotifyRaise()

When a text (infoalert) or error notification is sent (ie has at least one listening channel eg pushover) anevent is raised once when the notification is queued The event will be named notifylttypegtltsubtypegt Forexample the second example above would come with an event notifyinfobatterystatus

2142 Suppress notifications

You can filter the channels to be used for notifications by their subtypes By default no subtypes are filtered on anychannel so all notifications are sent to all clients

To disable (suppress) notifications create a config entry based on the respective subtype that lists the channels toinclude or exclude

OVMS config set notify ltsubtypegt ltchannelsgt

ltchannelsgt options are

a) explicit inclusion eg ovmsv2pushover (only enable these)

b) explicit exclusion eg -ovmsv3-ovmsweb (only disable these)

c) - (dash) to disable all

d) empty to enable all

Example to disable the OTA update notifications on all channels do

OVMS config set notify otaupdate -

52 Chapter 2 User Guide

Open Vehicles

2143 Standard notifications

Type Subtype Purpose Contentalert alarmsounding Vehicle alarm is soundingalert alarmstopped Vehicle alarm has stoppedalert batt12valert 12V Battery criticalalert batt12vrecovered 12V Battery restoredalert battbmsalert Battery packcell alert (critical voltagetemperature deviation)alert battsocalert Battery SOC criticalinfo chargedone stat on charge finishedinfo chargestarted stat on start of chargeinfo chargetoppingoff stat on start of topping off chargephaseinfo chargestopped stat on planned charge stopalert chargestopped stat on unplanned charge stopdata debugcrash Transmit crash backtraces (rarr -OVM-DebugCrash)data debugtasks Transmit task statistics (rarr -OVM-DebugTasks)info drivetripreport Trip driving statistics (see Trip report)alert flatbedmoved Vehicle is being transported while parked - possible theftflatbedinfo heatingstarted stat on start of heating (battery)data loggrid Grid (chargegenerator) history log (see below) (rarr -LOG-Grid)data logtrip Trip history log (see below) (rarr -LOG-Trip)alert modemno_pincode No PIN code for SIM card configuredalert modemwrongpincode Wrong pin codeinfo otaupdate New firmware availabledownloadedinstalledinfo pushover Connection failure message delivery responsestream retoolslistupdate RE toolkit CAN frame list updatestream retoolsstatus RE toolkit general status updateinfo valetdisabled Valet mode disabledinfo valetenabled Valet mode enabledalert valethood Vehicle hood opened while in valet modealert valettrunk Vehicle trunk opened while in valet modealert vehicleidle Vehicle is idling stopped turned on

2144 Grid history log

The grid history log can be used as a source for long term statistics on your charges and typical energy usages and tocalculate your vehicle energy costs

Log entries are created on each change of the charge or generator state (vcstate vgstate)

You need to enable this log explicitly by configuring a storage time via config param notify loggridstoretime (in days) or via the web configuration page Set to 0empty to disable the log Already stored logentries will be kept on the server until expiry or manual deletion

Note the stability of the total energy counters included in this log depends on their source and persistence on thevehicle andor module If they are kept on the module they may lose their values on a power outage

bull Notification subtype loggrid

bull History record type -LOG-Grid

bull Format CSV

bull Archive time config notify loggridstoretime (days)

214 Notifications 53

Open Vehicles

bull Fieldscolumns

ndash pos_gpslock

ndash pos_latitude

ndash pos_longitude

ndash pos_altitude

ndash pos_location

ndash charge_type

ndash charge_state

ndash charge_substate

ndash charge_mode

ndash charge_climit

ndash charge_limit_range

ndash charge_limit_soc

ndash gen_type

ndash gen_state

ndash gen_substate

ndash gen_mode

ndash gen_climit

ndash gen_limit_range

ndash gen_limit_soc

ndash charge_time

ndash charge_kwh

ndash charge_kwh_grid

ndash charge_kwh_grid_total

ndash gen_time

ndash gen_kwh

ndash gen_kwh_grid

ndash gen_kwh_grid_total

ndash bat_soc

ndash bat_range_est

ndash bat_range_ideal

ndash bat_range_full

ndash bat_voltage

ndash bat_temp

ndash charge_temp

ndash charge_12v_temp

54 Chapter 2 User Guide

Open Vehicles

ndash env_temp

ndash env_cabintemp

ndash bat_soh

ndash bat_health

ndash bat_cac

ndash bat_energy_used_total

ndash bat_energy_recd_total

ndash bat_coulomb_used_total

ndash bat_coulomb_recd_total

2145 Trip history log

The trip history log can be used as a source for long term statistics on your trips and typical trip power usages as wellas your battery performance in different environmental conditions and degradation over time

Entries are created at the beginning and end of each ldquoignitionrdquo cycle (veon change) Configure a minimum triplength for logging by the config variable notify logtripminlength or via the web UI If your vehicle doesnot support the vptrip metric set the minimum trip length to 0

The log entry at the beginning of a trip is created to track non-driving SOC changes vampire drains and BMS SOCcorrections that occurred in between If yoursquore just interested in the actual drive results filter the records eg bypos_trip gt 01 or env_drivetime gt 10 (by default log entries will be created 3 seconds after the veonstate change)

You need to enable this log explicitly by configuring a storage time via config param notify logtripstoretime (in days) or via the web configuration page Set to 0empty to disable the log Already stored logentries will be kept on the server until expiry or manual deletion

bull Notification subtype logtrip

bull History record type -LOG-Trip

bull Format CSV

bull Archive time config notify logtripstoretime (days)

bull Fieldscolumns

ndash pos_gpslock

ndash pos_latitude

ndash pos_longitude

ndash pos_altitude

ndash pos_location

ndash pos_odometer

ndash pos_trip

ndash env_drivetime

ndash env_drivemode

ndash bat_soc

ndash bat_range_est

214 Notifications 55

Open Vehicles

ndash bat_range_ideal

ndash bat_range_full

ndash bat_energy_used

ndash bat_energy_recd

ndash bat_coulomb_used

ndash bat_coulomb_recd

ndash bat_soh

ndash bat_health

ndash bat_cac

ndash bat_energy_used_total

ndash bat_energy_recd_total

ndash bat_coulomb_used_total

ndash bat_coulomb_recd_total

ndash env_temp

ndash env_cabintemp

ndash bat_temp

ndash inv_temp

ndash mot_temp

ndash charge_12v_temp

ndash tpms_temp_min

ndash tpms_temp_max

ndash tpms_pressure_min

ndash tpms_pressure_max

ndash tpms_health_min

ndash tpms_health_max

2146 Trip report

The trip report outputs some core statistics of the current or most recent trip (drive cycle) It can be queried any timeusing the stat trip command or be configured to be sent automatically on turning the vehicle off

Use the web UI (Config rarr Notifications) or set config variable notify reporttripenable to yes andoptionally a minimum trip length in notify logtripminlength (defaults to 02 km) If your vehicle doesnot support the vptrip metric set the minimum trip length to 0

The statistics available depend on your vehicle type (ie metrics support of that vehicle adaption) Vehicles also mayoverride the report to provide custom statistics By default a full trip report will contain

bull Trip length

bull Average driving speed

bull Overall altitude difference (start to end point)

56 Chapter 2 User Guide

Open Vehicles

bull Energy consumption in Wh per kmMi

bull Recuperation percentage (in relation to energy used)

bull SOC difference amp new SOC

bull Estimated range difference amp new range

bull Average acceleration amp deceleration

The average driving speed is calculated only from speeds above 5 kph (3 mph) (to exclude slow speed rolling) andthe acceleration amp deceleration averages exclude values below 25 kphs (16 mphs) (constant speed cruising)

215 Time

This section of the manual is still under development

216 SSLTLS

Warning Letrsquos Encrypt root certificate expiration on September 30 2021

To prevent losing TLS connectivity with an LE secured server (like dexters-webde) with module firmwareversions 32016 or earlier you need to install the new root certificate manually Sorry for the inconvenience

See below Letrsquos Encrypt Root Certificate Update

2161 SSLTLS Trusted Certificate Authorities

A default minimal list of trusted certificate authorities (CA) is provided with the firmware you can see the currentloaded list with the tls trust list command

OVMS tls trust listAddTrust External CA Root length 15211521 byte certificate AddTrust External CA Root

cert version 3serial number 01issuer name C=SE O=AddTrust AB OU=AddTrust External TTP Network

rarr˓CN=AddTrust External CA Rootsubject name C=SE O=AddTrust AB OU=AddTrust External TTP Network

rarr˓CN=AddTrust External CA Rootissued on 2000-05-30 104838expires on 2020-05-30 104838signed using RSA with SHA1RSA key size 2048 bitsbasic constraints CA=truekey usage Key Cert Sign CRL Sign

If you want to add to this list you can place the PEM formatted root CA certificate in the storetrustedcadirectory on your config partition using the text editor Then reload the list with

OVMS tls trust reloadReloading SSLTLS trusted CA listSSLTLS has 4 trusted CAs using 5511 bytes of memory

215 Time 57

Open Vehicles

On boot the trusted Certificate Authorities provided in firmware and put in your storetrustedca directorywill be automatically loaded and made available

These trusted certificate authorities are used by the various module in the OVMS system when establishing SSLTLSconnections (in order to verify the certificate of the server being connected to)

2162 How to get the CA PEM for a Server

Download from CA

If you know the CA check their download section

Using a Browser

This only works for https servers

1 Open the website you want to access

2 Open the encryption info (eg Chrome lock icon at URL rarr show certificate)

3 Display the certificate chain (eg Chrome tab ldquoDetailsrdquo first element)

4 Select the last entry before the actual server certificate

5 Export the certificate in PEM format (usually the default)

6 Install the file contents as shown above

Using OpenSSL or GNU TLS CLI

This works for all servers and ports

openssl s_client -connect HOSTNAMEPORT -servername HOSTNAME -showcerts ltdevnull | sed -ne -BEGIN CERTIFICATE--END CERTIFICATE-p

or

gnutls-cli --print-cert --port PORT HOSTNAME ltdevnull | sed -ne -BEGIN CERTIFICATE--END CERTIFICATE-p

Substitute HOSTNAME and PORT accordingly eg https = port 443 The sed just strips the other info from theoutput and can be omitted to check for errors or details

There should be two certificates in the output look for BEGIN and END markers The first one is the server certificatethe second one the CA certificate Copy that second certificate into the editor take care to include the BEGIN andEND lines

2163 Letrsquos Encrypt Root Certificate Update

If running firmware version 32016 or earlier you need to install the new Letrsquos Encrypt root certificate (ldquoISRGRoot X1rdquo) manually to enable encrypted connections to servers secured by a Letrsquos Encrypt certificate

1 Save the certificate text shown below to file storetrustedcaisrgx1

2 Issue command tls trust reload or reboot the module

Certificate text

58 Chapter 2 User Guide

Open Vehicles

-----BEGIN CERTIFICATE-----MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2VhcmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygch77ct984kIxuPOZXoHj3dcKivVqbvYATyjb3miGbESTtrFjRQSa78f0uoxmyF+0TM8ukj13Xnfs7jEvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6UA5TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sWT8KOEUt+zwvo7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hmELNKjD+Jo2FR3qyHB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UCB5iPNgiV5+I3lg02dZ77DnKxHZu8AlJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUvKBds0pjBqAlkd25HN7rOrFleaJ1ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWnOlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTnjh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbwqHyGO0aoSCqI3Haadr8faqU9GYrOPNk3sgrDQoofb4hVC1CLQJ13hef4Y53CIrU7m2Ys6xt0nUW7vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEBwQEAwIBBjAPBgNVHRMBAf8EBTADAQHMB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkqhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaSV9lZLubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ3BebYhtF8GaV0nxvwuo77xPy9auJGpsMiuX1+mvoiBOv2XqkSsisRcOjKKNFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7UrTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l++sKAIuvtd7u+Nxe5AW0wdeRlN8NwdCjNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVcoyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui01lvh+wjChP4kqKOJ2qxq4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9Ut7y0Ff9yi0GE44Za4rF2LN9d11TPAmRGunUHBcnWEvgJBQl9nJEiU0ZsnvgcubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57demyPxgcYxneR44KJ4EBs+lVDR3veyJm+kXQ99b21+jh5Xos1AnX5iItreGCc=-----END CERTIFICATE-----

217 Scripting

2171 Command Scripts

Lists of commands can be entered into a script file and stored in the VFS for execution (in the storescriptsdirectory) These are called lsquocommand scriptsrsquo and are simple sequential lists of OVMS commands A commandscript can be executed with

OVMS ltscriptgtOVMS script run ltscriptgt

Command scripts can also be stored in the storeeventslteventnamegt directory structure Whenever eventsare triggered all the scripts in the corresponding storeeventslteventnamegt directory are executed Eventscripts are executed in alphanumerical order of their names Good practice is to prefix script names with 2-3 digitnumbers in steps of 10 or 100 (ie first script named 50-) so new scripts can easily be integrated at a specificplace

Output of background scripts without console association (eg event scripts) will be sent to the log with tag scriptat ldquoinfordquo level

Note that the developer building firmware can optionally set the OVMS_DEV_SDCARDSCRIPTS build flag If thatis set then the system will also check sdscripts and sdevents for scripts This should not be used forproduction builds as you could hack the system just by plugging in an SD card

217 Scripting 59

Open Vehicles

In addition to command scripts more sophisticated scripting capabilities may be enabled if the JavaScript environmentis enabled in the build This is discussed in the next section of this guide

2172 JavaScripting

OVMS v3 includes a powerful JavaScript engine In addition to the standard relatively fixed firmware flashed tothe module JavaScripting can be used to dynamically load script code to run alongside the standard firmware Thisjavascript code can respond to system events and perform background monitoring and other such tasks

The simplest way of running javascript is to place a piece of javascript code in the storescripts directory withthe file extension js Then the standard mechanism of running scripts can be employed

OVMS ltscriptjsgtOVMS script run ltscriptjsgt

Short javascript snippets can also be directly evaluated with

OVMS script eval ltcodegt

Such javascript code can also be placed in the storeeventslteventnamegt directories to be automaticallyexecuted when the specified event is triggered The script file name suffix must be js to run the Javascript interpreter

Note The scripting engine used is Duktape Duktape supports ECMAScript E5E51 with some additions from laterECMAScript standards Duktape does not emulate a browser environment so you donrsquot have window or documentobjects etc just core Javascript plus the OVMS API and plugins

Duktape builtin objects and functions httpsduktapeorgguidehtmlduktapebuiltins

2173 Persistent JavaScript

When a javascript script is executed it is evaluated in the global javascript context Care should be taken that localvariables may pollute that context so it is in general recommended that all JavaScript scripts are wrapped

(function() user code

)()

It is also possible to deliberately load functions and other code into the global context persistently and have thatcode permanently available and running When the JavaScript engine initialises it automatically runs a special startupscript

storescriptsovmsmainjs

That script can in turn include other code If you make a change to such persistent code and want to reload it you canwith

OVMS script reload

2174 JavaScript Modules

The OVMS JavaScript engine supports the concept of modules (using the nodejs style of exports) Such modules canbe written like this

60 Chapter 2 User Guide

Open Vehicles

exportsprint = function(obj ind) var type = typeof objif (type == object ampamp ArrayisArray(obj)) type = arrayif (ind) ind =

switch (type) case string

print( + objreplace(g ) + )break

case arrayprint([n)for (var i = 0 i lt objlength i++) print(ind + )exportsprint(obj[i] ind + )if (i = objlength-1) print()print(n)

print(ind + ])break

case objectprint(n)var keys = Objectkeys(obj)for (var i = 0 i lt keyslength i++) print(ind + + keys[i] + )exportsprint(obj[keys[i]] ind + )if (i = keyslength-1) print()print(n)

print(ind + )break

defaultprint(obj)

if (ind == ) print(n)

By convention modules such as this are placed in the storescriptslib directory as ltmodulenamegtjsThese modules can be loaded with

JSON = require(libJSON)

And used as

JSONprint(this)

To automatically load a custom module on startup add the MyPlugin = require(libMyPlugin) lineto ovmsmainjs

There are a number of internal modules already provided with the firmware and by convention these are providedunder the intltmodulenamegt namespace The above JSON module is for example provided as intJSON andautomatically loaded into the global context These internal modules can be directly used (so JSONprint(this)works directly)

217 Scripting 61

Open Vehicles

2175 Testing JavaScript Modules

Use the editor (see Tools menu) to test or evaluate arbitrary Javascript code This can be done on the fly ie withoutsaving the code to a file first Think of it as a server side Javascript shell

Testing modules normally involves reloading the engine as the require() call caches all loaded modules untilrestart To avoid this during module development use the following template code This mimics the require() callwithout caching and allows to do tests within the same evaluation run

Load modulemymodule = (function()exports =

insert module code here

return exports)()

Module API testsmymodulemyfunction1()JSONprint(mymodulemyfunction2())

As the module is actually loaded into the global context this way just like using require() anything else using themodule API (eg a web plugin) will also work after evaluation

2176 Heap Memory

Due to limitations of the general esp-idf system memory management Duktape will normally use the custom memorymanager umm_malloc by Ralph Hempel

umm_malloc needs a dedicated chunk of the system memory to work with The default for Duktape is 512 KB(taken from SPIRAM) which is normally sufficient even for extended scripting If you need more RAM the sizecan be changed by config set module duktapeheapsize ltsize_in_KBgt Maximum allowed size is1024 KB The heap size needs to be configured at Duktape startup and cannot be changed while Duktape is runningTo reconfigure the heap size set the new configuration and do a script reload

Call meminfo() to query the current heap memory usage status The function returns an object containing somestandard and some memory library internal info The shell command script meminfo outputs the object in JSONformat Example

OVMS script meminfo

totalBytes 524224usedBytes 273344freeBytes 250880largestFreeBytes 180608memlib ummummTotalEntries 2723ummUsedEntries 2615ummFreeEntries 108ummTotalBlocks 16382ummUsedBlocks 8542ummFreeBlocks 7840ummMaxFreeContiguousBlocks 5644ummUsageMetric 108ummFragmentationMetric 27

62 Chapter 2 User Guide

Open Vehicles

ldquolargestFreeBytesrdquo is the largest block of contiguous memory available Note these values will change by someamount between the garbage collection runs done every 60 seconds the maximum usage will be just before thegarbage collection and the base line just after

ldquomemlibrdquo tells about the memory manager in use the following fields are the internal state variables and statistics ofthat manager (having the memlib name as a name prefix) These can be useful to monitor the memory managementload and performance

If running a firmware configured to use the default system memory manager the output will look like this

OVMS script meminfo

totalBytes 4072176usedBytes 415996freeBytes 3656180largestFreeBytes 3635864memlib syssysMinimumFreeBytes 3653072sysAllocatedBlocks 6013sysFreeBlocks 454sysTotalBlocks 6467

2177 Internal Objects and FunctionsMethods

A number of OVMS objects have been exposed to the JavaScript engine and are available for use by custom scriptsvia the global context

The global context is the analog to the window object in a browser context it can be referenced explicitly as thison the JavaScript toplevel or as globalThis from any context

You can see the global context objects methods functions and modules with the JSONprint(this) method

OVMS script eval JSONprint(this)

performance now function now() [native code]

assert function () [native code] print function () [native code] write function () [native code] meminfo function () [native code] OvmsCommand Exec function Exec() [native code]

OvmsConfig Delete function Delete() [native code] Get function Get() [native code] Instances function Instances() [native code] Params function Params() [native code] Set function Set() [native code]

OvmsEvents Raise function Raise() [native code]

OvmsLocation Status function Status() [native code]

(continues on next page)

217 Scripting 63

Open Vehicles

(continued from previous page)

OvmsMetrics AsFloat function AsFloat() [native code] AsJSON function AsJSON() [native code] Value function Value() [native code]

OvmsNotify Raise function Raise() [native code]

OvmsVehicle ClimateControl function ClimateControl() [native code] Homelink function Homelink() [native code] Lock function Lock() [native code] SetChargeCurrent function SetChargeCurrent() [native code] SetChargeMode function SetChargeMode() [native code] SetChargeTimer function SetChargeTimer() [native code] StartCharge function StartCharge() [native code] StartCooldown function StartCooldown() [native code] StopCharge function StopCharge() [native code] StopCooldown function StopCooldown() [native code] Type function Type() [native code] Unlock function Unlock() [native code] Unvalet function Unvalet() [native code] Valet function Valet() [native code] Wakeup function Wakeup() [native code]

JSON format function () [ecmascript code] print function () [ecmascript code]

PubSub publish function () [ecmascript code] subscribe function () [ecmascript code] clearAllSubscriptions function () [ecmascript code] clearSubscriptions function () [ecmascript code] unsubscribe function () [ecmascript code]

Global Context

bull assert(conditionmessage) Assert that the given condition is true If not raise a JavaScript exceptionerror with the given message

bull print(string) Print the given string on the current terminal If no terminal (for example a backgroundscript) then print to the system console as an informational message

bull write(stringUint8Array) Write the given string or Uint8Array to the current output channel (ieterminalHTTP connection) Use this to transfer binary data to a reader

bull meminfo() Returns an object containing the current heap memory status (see Heap Memory)

bull performancenow() Returns monotonic time since boot in milliseconds with microsecond resolution

64 Chapter 2 User Guide

Open Vehicles

JSON

The JSON module extends the native builtin JSONstringify and JSONparse methods by a format and aprint method to format andor print out a given javascript object in JSON format Both by default insert spacingand indentation for readability and accept an optional false as a second parameter to produce a compact version fortransmission

bull JSONprint(data) Output data (any Javascript data) as JSON readable

bull JSONprint(data false) compact (without spacingindentation)

bull str = JSONformat(data) Format data as JSON string readable

bull str = JSONformat(data false) compact (without spacingindentation)

bull JSONstringify(value[ replacer[ space]]) see MDN JSONstringify

bull JSONparse(text[ reviver]) see MDN JSONparse

Note The JSON module is provided for compatibility with standard Javascript object dumps and for readability Ifperformance is an issue consider using the Duktape native builtins JSONstringify() Duktapeenc() andJSONparse() Duktapedec() (see Duktape builtins and Duktape JSON for explanations of these)

For example Duktapeenc(JC data) is equivalent to JSONformat(data false) except for therepresentation of functions Using the JX encoding will omit unnecessary quotings

Warning All Duktape JSON encoders and decoders have a very high performance penalty and should beavoided for large objects or frequent encodingdecoding with large being any object larger than a handful ofconfiguration or state variables

For general data storage and exchange with the web UI use the CBOR serialization instead

CBOR

CBOR is a binary serialization format and especially with Duktape the better alternative over JSON for storage anddata transmission if human readability isnrsquot required

ldquoCBORrdquo stands for ldquoConcise Binary Object Representationrdquo See httpscborio for details on the specification andavailable implementations CBOR isnrsquot necessarily more compact in storage space but can be encoded and decodedmuch faster and with much less memory overhead as JSON

Duktape implements CBOR support by the builtin CBORencode() and CBORdecode() methods

bull enc = CBORencode(data) Encode data (any Javascript data) to CBOR format (result is an ArrayBuffer)

bull data = CBORdecode(enc) Decode CBOR format (ArrayBufferUint8Array) to Javascript data

CBOR support in Duktape is still considered experimental but the underlying implementation is mature

CBOR also isnrsquot part of the standard browser builtin Javascript APIs yet so the OVMS web framework includes thecbor-js library by Patrick Gansterer (same API as on the Duktape side)

The webserver command API supports binary output from commands amp Javascript API methods and the output canbe passed to CBORdecode() directly

Example

The following scheme shows how to transmit a javascript data object from the module backend into the web frontend

217 Scripting 65

Open Vehicles

Module backendbackendgetdata = function ()

var mydata = pi 3141 fib [ 011235813 ] write(CBORencode(mydata))

Web frontendloadjs( command backendgetdata() output binary )done((stream) =gt

var mydata = CBORdecode(stream))

For full examples see the ldquoAuxBatMonrdquo and ldquoPwrMonrdquo plugins

Note When loading CBOR data via VFSLoad() you need to set the binary option to true so the loader willreturn a Uint8Array instead of a standard string

HTTP

The HTTP API provides asynchronous GET amp POST requests for HTTP and HTTPS Requests can return text andbinary data and follow 301302 redirects automatically Basic authentication is supported (add username amp passwordto the URL) digest authentication is not yet implemented

The handler automatically excludes the request objects from garbage collection until finished (successfailure) so youdonrsquot need to store a global reference to the request

bull req = HTTPRequest(cfg) Perform asynchronous HTTPHTTPS GET or POST request

Pass the request parameters using the cfg object

ndash url standard URLURI syntax optionally including user auth and query string

ndash post optional POST data set to an empty string to force a POST request Note you needto provide this in encoded form If no Content-Type header is given it will default tox-www-form-urlencoded

ndash headers optional array of objects containing key-value pairs of request headers NoteUser-Agent will be set to the standard OVMS user agent if not present here

ndash timeout optional timeout in milliseconds default 120 seconds

ndash binary optional flag true = perform a binary request (see response object)

ndash done optional success callback function called with the response object as argument with thispointing to the request object

ndash fail optional error callback function called with the error string as argument with this point-ing to the request object

ndash always optional final callback function no arguments this = request object

The cfg object is extended and returned by the API (req) It will remain stable at least until the requesthas finished and callbacks have been executed On completion the req object may contain an updatedurl and a redirectCount if redirects have been followed Member error (also passed to the failcallback) will be set to the error description if an error occurred The always callback if present is calledin any case after a done or fail callback has been executed Check thiserror in the alwayscallback to know if an error occurred

On success member object response will be present and contain

66 Chapter 2 User Guide

Open Vehicles

ndash statusCode the numerical HTTP Status response code

ndash statusText the HTTP Status response text

ndash headers array of response headers each represented by an object ltnamegt ltvaluegt

ndash body only for text requests response body as a standard string

ndash data only for binary requests response body as a Uint8Array

Notes any HTTP response from the server is considered success check responsestatusCode forserver specific errors Callbacks are executed without an output channel so all print outputs will bewritten to the system log Hint use JSONprint(this false) in the callback to get a debug logdump of the request

Examples

simple POST ignore all resultsHTTPRequest( url httpsmartpluglocalswitch post state=onampwhen=nowrarr˓ )

fetch and inspect a JSON objectHTTPRequest(

url httpsolarcontrollerlocalstatusfmt=jsondone function(resp)

if (respstatusCode == 200) var status = JSONparse(respbody)if (status[power] gt 5000)OvmsVehicleStartCharge()

else if (status[power] lt 3000)OvmsVehicleStopCharge()

)

override user agent log completed request objectHTTPRequest(

url httpsdexters-webdeftestjsonheaders [ User-Agent Mr What Zit Tooya ]always function() JSONprint(this false)

)

bull HTTPrequest() Legacy alias for HTTPRequest() please do not use

Note SSL requests (https) can take up to 12 seconds on an idle module SSL errors also may not reflect the actualerror for example an empty server response with code 400 may be reported as a general ldquoSSL errorrdquo If you get ldquoSSLerrorrdquo on a valid request you may need to install a custom root CA certificate see SSLTLS

VFS

The VFS API provides asynchronous loading and saving of files on store and sd Text and binary data issupported Currently only complete files can be loaded the saver supports an append mode In any case the data tosaveload needs to fit into RAM twice as the buffer needs to be converted tofrom Javascript

The handler automatically excludes the request objects from garbage collection until finished (successfailure) so youdonrsquot need to store a global reference to the request

217 Scripting 67

Open Vehicles

Loading or saving protected paths (storeovms_config) is not allowed Saving to a path automaticallycreates missing directories

See AuxBatMon 12V History Chart for a complete application usage example

bull req = VFSLoad(cfg) Perform asynchronous file load

Pass the request parameters using the cfg object

ndash path full file path eg sdmydatatelemetryjson

ndash binary optional flag true = perform a binary request returned data will be an Uint8Array)

ndash done optional success callback function called with the data content read as the single argumentthis pointing to the request object

ndash fail optional error callback function called with the error string as argument with this point-ing to the request object

ndash always optional final callback function no arguments this = request object

The cfg object is extended and returned by the API (req) It will remain stable at least until the requesthas finished and callbacks have been executed On success the req object contains a data property (alsopassed to the done callback) which is either a string (text mode) or a Uint8Array (binary mode)

Member error (also passed to the fail callback) will be set to the error description if an error occurredThe always callback if present is called in any case after a done or fail callback has been executedCheck thiserror in the always callback to know if an error occurred

Example

Load a custom telemetry object from a JSON file on SD cardvar telemetryVFSLoad(path sdmydatatelemetryjsondone function(data) telemetry = Duktapedec(jx data) process telemetry

fail function(error) print(Error loading telemetry + error)

)

bull req = VFSSave(cfg) Perform asynchronous file save

Pass the request parameters using the cfg object

ndash data the string or Uint8Array to save

ndash path full file path (missing directories will automatically be created)

ndash append optional flag true = append to the end of the file (also creating the file as necessary)

ndash done optional success callback function called with no arguments this pointing to the requestobject

ndash fail optional error callback function called with the error string as argument with this point-ing to the request object

ndash always optional final callback function no arguments this = request object

The cfg object is extended and returned by the API (req) It will remain stable at least until the requesthas finished and callbacks have been executed

68 Chapter 2 User Guide

Open Vehicles

Member error (also passed to the fail callback) will be set to the error description if an error occurredThe always callback if present is called in any case after a done or fail callback has been executedCheck thiserror in the always callback to know if an error occurred

Example

Save the above telemetry object in JSON format on SD cardVFSSave(

path sdmydatatelemetryjsondata Duktapeenc(jx telemetry)fail function(error)

print(Error saving telemetry + error)

)

Warning File IO especially saving can cause short freezes of the module

Minimize save frequency and if possible avoid saving while the vehicle is in operation (driving charging) byusing a check like

Saving to VFS may cause short blockings so only allow when vehicle is offfunction allowSave()

return OvmsMetricsValue(veon) ampamp OvmsMetricsValue(vccharging)

Note Saving to and loading from SD card

When storing plugin data on an SD card the plugin needs to take care of the SD card being mounted later in the bootprocess than the scripts are loaded Plugins additionally may need to take into account that the user may replace theSD card any time

When trying to save or load from an unmounted SD error will be set to volume not mounted If this happensduring plugin initialization the plugin should subscribe to the SD mount event to retry the loadsave as soon as the SDcard becomes available

Code scheme

var storeFile = sdusrhistorycborvar listen_sdmount = nullvar history =

function loadStoreFile() VFSLoad(path storeFilebinary truedone function(data)

print(storeFile + loadedn)history = CBORdecode(data)startRecording()

fail function(error)

print(storeFile + + thiserror + n)if (listen_sdmount ampamp thiserror == volume not mounted)

retry once after SD mountlisten_sdmount = PubSubsubscribe(sdmounted loadStoreFile)

else

(continues on next page)

217 Scripting 69

Open Vehicles

(continued from previous page)

startRecording()

)

function startRecording() if (listen_sdmount) PubSubunsubscribe(listen_sdmount)listen_sdmount = null

PubSubsubscribe(tickerEvent ticker) for example

if (storeFile) loadStoreFile()

else startRecording()

PubSub

The PubSub module provides access to a Publish-Subscribe framework In particular this framework is used to deliverevents to the persistent JavaScript framework in a high performance flexible manner An example script to print outthe ticker10 event is

var myTicker=function(msgdata) print(Event +msg+n)

PubSubsubscribe(ticker10myTicker)

The above example created a function myTicker in global context to print out the provided event name Then thePubSubsubscribe module method is used to subscribe to the ticker10 event and have it call myTickerevery ten seconds The result is ldquoEvent ticker10rdquo printed once every ten seconds

PubSub interprets events similar to MQTT as hierarchical topics with dots separating the levels It delivers the eventsin multiple passes with each new pass removing the last dotted part of the topic (ie bottom-up) so the most specificsubscriptions will be called first The handler is always called with the original eventtopic name So to eg catchall events vehiclecharge you can simply subscribe to vehiclecharge and inspect the actual eventname in your handler

PubSubsubscribe(vehiclecharge function (event) print(Got charging related event + event)

)

bull id = PubSubsubscribe(topic handler) Subscribe the function handler to messages of thegiven topic Note that types are not limited to OVMS events The method returns an id to be used tounsubscribe the handler

bull PubSubpublish(topic [data]) Publish a message of the given topic All subscribed handlers willbe called with the topic and data as arguments data can be any Javascript data

bull PubSubunsubscribe(id | handler | topic) Cancel a specific subscription all subscriptions ofa specific handler or all subscriptions to a topic

70 Chapter 2 User Guide

Open Vehicles

OvmsCommand

bull str = OvmsCommandExec(command) The OvmsCommand object exposes one method ldquoExecrdquo Thismethod is passed a single parameter as the command to be executed runs that command and then returnsthe textual output of the command as a string For example

print(OvmsCommandExec(boot status))Last boot was 14 second(s) ago

This is reset 0 since last power cycleDetected boot reason PowerOn (114)Crash counters 0 total 0 early

OvmsConfig

bull array = OvmsConfigParams() Returns the list of available configuration parameters

bull array = OvmsConfigInstances(param) Returns the list of instances for a specific parameter

bull string = OvmsConfigGet(paraminstancedefault) Returns the specified parame-terinstance value

bull object = OvmsConfigGetValues(param [prefix]) Gets all param instances matching theoptional prefix with their associated values If a prefix is given the returned property names will havethe prefix removed Note all values are returned as strings you need to convert them as needed

bull OvmsConfigSet(paraminstancevalue) Sets the specified parameterinstance value

bull OvmsConfigSetValues(param prefix object) Sets all properties of the given object asparam instances after adding the prefix Note non-string property values will be converted to their stringrepresentation

bull OvmsConfigDelete(paraminstance) Deletes the specified parameter instance

Beginning with firmware release 32009 a dedicated configuration parameter usr is provided for plugins Youcan add new config instances simply by setting them for example by OvmsConfigSet(usr mypluginlevel 123) or by the config set command

Read plugin configuration example

Set default configurationvar cfg = level 100 enabled no

Read user configurationObjectassign(cfg OvmsConfigGetValues(usr myplugin))

if (cfg[enabled] == yes) print(Im enabled at level + Number(cfg[level]))

Keep in mind to prefix all newly introduced instances by a unique plugin name so your plugin can nicely coexist withothers

OvmsEvents

This provides access to the OVMS event system While you may raise system events the primary use is to raisecustom events Sending custom events is a lightweight method to inform the web UI (or other plugins) about simplestate changes Use the prefix usr on custom event names to prevent conflicts with later framework additions

217 Scripting 71

Open Vehicles

Another use is the emulation of the setTimeout() and setInterval() browser methods by subscribing to adelayed event Pattern

function myTimeoutHandler() raise the timeout event again here to emulate setInterval()

PubSubsubscribe(usrmyplugintimeout myTimeoutHandler)

start timeoutOvmsEventsRaise(usrmyplugintimeout 1500)

bull OvmsEventsRaise(event [delay_ms]) Signal the event optionally with a delay (millisecondsmust be given as a number) Delays are handled by the event system the method call returns immediately

OvmsLocation

bull isatlocation = OvmsLocationStatus(location) Check if the vehicle is currently in a loca-tionrsquos geofence (pass the location name as defined) Returns true or false or undefined if thelocation name passed is not valid

Note to get the actual GPS coordinates simply read metrics vplatitude vplongitude and vpaltitude

OvmsMetrics

bull str = OvmsMetricsValue(metricname [decode]) Returns the typed value (default) or stringrepresentation (with decode = false) of the metric value

bull num = OvmsMetricsAsFloat(metricname) Returns the float representation of the metric value

bull str = OvmsMetricsAsJSON(metricname) Returns the JSON representation of the metric value

bull obj = OvmsMetricsGetValues([filter] [decode]) Returns an object of all metrics match-ing the optional name filtertemplate (see below) by default decoded into Javascript types (ie numericalvalues will be JS numbers arrays will be JS arrays etc) The object returned is a snapshot the valueswonrsquot be updated

The filter argument may be a string (for substring matching as with metrics list) an array of fullmetric names or an object of which the property names are used as the metric names to get The objectwonrsquot be changed by the call see Objectassign() for a simple way to merge objects Passing anobject is especially convenient if you already have an object to collect metrics data

The decode argument defaults to true pass false to retrieve the metrics string representations insteadof typed values

With the introduction of the OvmsMetricsGetValues() call you can get multiple metrics at once and let thesystem decode them for you Using this you can for example do

Get all metrics matching substring vbc (vehicle battery cell)var metrics = OvmsMetricsGetValues(vbc)print(Temperature of cell 3 + metrics[vbctemp][2] + degCn)print(Voltage of cell 7 + metrics[vbcvoltage][6] + Vn)

Get some specific metricsvar ovmsinfo = OvmsMetricsGetValues([mversion mhardware])JSONprint(ovmsinfo)

72 Chapter 2 User Guide

Open Vehicles

This obsoletes the old pattern of parsing a metricrsquos JSON representation using eval() JSONparse() orDuktapedec() you may still find in some plugins Example

var celltemps = eval(OvmsMetricsAsJSON(vbctemp))print(Temperature of cell 3 + celltemps[2] + degCn)

Warning Never use eval() on unsafe data eg user input eval() executes arbitrary Javascript so canbe exploited for code injection attacks

OvmsNotify

bull id = OvmsNotifyRaise(type subtype message) Send a notification of the given type andsubtype with message as contents Returns the message id allocated or 0 in case of failure Examples

send an info notification to the userOvmsNotifyRaise(info usrmypluginstatus Alive and kicking)

send a JSON stream to a web pluginOvmsNotifyRaise(stream usrmypluginupdate JSONformat(streamdatararr˓false))

send a CSV data record to a serverOvmsNotifyRaise(data usrmypluginrecord -MyStatus086400Alive)

OvmsVehicle

The OvmsVehicle object is the most comprehensive and exposes several methods to access the current vehicle Theseinclude

bull str = OvmsVehicleType() Return the type of the currently loaded vehicle module

bull success = OvmsVehicleWakeup() Wakeup the vehicle (return TRUE if successful)

bull success = OvmsVehicleHomelink(buttondurationms) Fire the given homelink button

bull success = OvmsVehicleClimateControl(onoff) Turn onoff climate control

bull success = OvmsVehicleLock(pin) Lock the vehicle

bull success = OvmsVehicleUnlock(pin) Unlock the vehicle

bull success = OvmsVehicleValet(pin) Activate valet mode

bull success = OvmsVehicleUnvalet(pin) Deactivate valet mode

bull success = OvmsVehicleSetChargeMode(mode) Set the charge mode (ldquostandardrdquo ldquostoragerdquo ldquorangerdquo ldquoperformancerdquo)

bull success = OvmsVehicleSetChargeCurrent(limit) Set the charge current limit (in amps)

bull success = OvmsVehicleSetChargeTimer(onoff start) Set the charge timer

bull success = OvmsVehicleStartCharge() Start the charge

bull success = OvmsVehicleStopCharge() Stop the charge

bull success = OvmsVehicleStartCooldown() Start a cooldown charge

bull success = OvmsVehicleStopCooldown() Stop the cooldown charge

217 Scripting 73

Open Vehicles

bull result = OvmsVehicleObdRequest(arguments) Perform OBDUDS request (synchronous)

Pass the request parameters using the arguments object

ndash txid the CAN ID to send the request to (or 0x7df for broadcast)

ndash rxid the CAN ID to expect the response at (or 0 for broadcast)

ndash request the request to send either a hex encoded string or an Uint8Array

ndash bus optional CAN bus device name default ldquocan1rdquo

ndash timeout optional timeout in milliseconds default 3000

ndash protocol optional protocol to use default 0 = ISOTP_STD ndash see vehicleh for other protocols

The result object will have these properties

ndash error 0 = no error else the error code with negative ranges being system errors positive codes areOBDUDS response error codes (NRCs)

ndash errordesc a human readable error description

ndash response only on success the binary response (Uint8Array)

ndash response_hex only on success hex encoded response (string)

Example

Establish diagnostic session with an ECUvar res = OvmsVehicleObdRequest( txid 0x765 rxid 0x7cf request 1003 rarr˓)if (reserror)print(reserrortext)

elseprint(resresponse_hex)

2178 Test Utilities

You can use the web UI editor and shell to edit upload and test script files If you need many test cycles a convenientalternative is to use shell scripts to automate the process

If yoursquove configured ssh public key authentication you can simply use scp to upload scripts and ssh to executecommands

binbash Upload amp execute a script file

FILE=testjsPATH=storescripts

OVMS_HOST=yourovmslocal

SCP=usrbinscp -qSSH=usrbinssh

Upload$SCP $FILE $OVMS_HOST$PATH$FILE

Execute$SSH $OVMS_HOST script run $FILE

74 Chapter 2 User Guide

Open Vehicles

Customize to your needs If you want to test a plugin simply replace the script run command by scriptreload followed by some script eval calls to your plugin API

Note this may be slow as the ssh session needs to be negotiated for every command

A faster option is using the OVMS HTTP REST API The following script uses curl to upload and execute a script

binbash Upload amp execute a script file

FILE=testjsPATH=storescripts

OVMS_HOST=httpyourovmslocalOVMS_USER=adminOVMS_PASS=yourpassword

CURL=usrbincurl -c auth -b authSED=usrbinsedDATE=usrbindate

Loginif [[ -e auth ]] then

AUTHAGE=$(($($DATE +s) - $($DATE +s -r auth)))else

AUTHAGE=3600fiif [[ $AUTHAGE -ge 3600 ]] thenRES=$($CURL $OVMS_HOSTlogin --data-urlencode username=$OVMS_USER --data-

rarr˓urlencode password=$OVMS_PASS 2gtdevnull)if [[ $RES =~ Error ]] thenecho -n LOGIN ERROR echo $RES | $SED -e sltligt([^lt])1grm authexit 1

fifi

UploadRES=$($CURL $OVMS_HOSTedit --data-urlencode path=$PATH$FILE --data-rarr˓urlencode content$FILE 2gtdevnull)if [[ $RES =~ Error ]] thenecho -n UPLOAD ERROR echo $RES | $SED -e sltligt([^lt])1grm authexit 1

fi

Execute$CURL $OVMS_HOSTapiexecute --data-urlencode command=script run $FILE

217 Scripting 75

Open Vehicles

218 Factory Reset

2181 Module Configuration

A standard factory reset erases the configuration store After a factory reset you will be able to access the USBconsole with an empty module password and the ldquoOVMSrdquo wifi access point with the initial password ldquoOVMSinitrdquo Werecommend using the setup wizard to configure the module or restoring a configuration backup as soon as possible1as the module is accessible by anyone knowing the initial password

The standard factory reset does not revert OTA firmware installs See below for methods to switch back to andoptionally replace the factory firmware

Method 1 Command

If you have console command access a factory reset can be accomplished with this command

OVMS module factory resetReset configuration store to factory defaults and lose all configuration data (yn)rarr˓yStore partition is at 00c10000 size 00100000Unmounting configuration storeErasing 1048576 bytes of flashFactory reset of configuration store complete and reboot now

That command will erase all configuration store and reboot to an empty configuration

Note to issue this command from the web shell or a remote shell (App Server ) you need to skip the confirmationstep by adding the option -noconfirm ie

OVMS module factory reset -noconfirm

Method 2 SD card

If you donrsquot have console access you can perform a factory reset by placing an empty file named factoryresettxt in the root directory of an SD card and insert that SD into the (running) module The file will be deleted and themodule will reboot within about 30 seconds

Method 3 Switch S2

You can also open the module case remove any SD card (important) power on the module wait 10 seconds thenpush and hold switch ldquoS2rdquo for 10 seconds ldquoS2rdquo is located here

1 Wait for the SSH key generation to finish after reboot before attempting to restore the backup Trying to run both processes concurrently maycrash the module Key generation takes about 2 minutes look for log message ldquoSSH server key installedrdquo

76 Chapter 2 User Guide

Open Vehicles

Method 4 USB

If you donrsquot have console access and donrsquot have an SD card you can perform a factory reset from a PC via USB usingthe esptoolpy tool from the Espressif ESP-IDF toolkit (see below for installation)

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 erase_region 0xC10000 0x100000

Note the port needs to be changed to the one assigned by your system ie devttyUSB0 on a Linux system orCOMx on Windows After using esptoolpy to manually erase the config region you should go into the console and dothe module factory reset step to properly factory reset

Note Methods 1 2 and 3 need a running system ie will not work if your module cannot boot normally In this casefirst try method 4 If that doesnrsquot help also switch back to the factory firmware as shown below

2182 Module Factory Firmware

You can switch back to factory firmware with this command

OVMS ota boot factoryBoot from factory at 0x00010000 (size 0x00400000)

Or without console access (lost module password) using the esptoolpy from the Espressif ESP-IDF toolkit

218 Factory Reset 77

Open Vehicles

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 erase_region 0xd000 0x2000

Note the device needs to be changed to the one assigned by your system ie devttyUSB0 on a Linux system orCOMx on Windows

2183 Flash Factory Firmware via USB

esptoolpy can also be used to flash a new factory firmware Download the firmware file ovms3bin you wantto flash then issue

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 --before default_reset --after hard_reset write_flash --compress --flash_mode dio --flash_freq 40m --flash_size detect 0x10000 ovms3bin

Note if you were running an OTA partition before you also need to switch back to the factory partition as shownabove

2184 Full Reflash via USB

If you accidentally did an erase_flash or erased the wrong region you will need to do a full reflash of your module(including the boot loader and partitioning scheme)

The need for a full reflash will typically show by the USB output of the module boot being just something like

rst0x10 (RTCWDT_RTC_RESET)boot0x3f (SPI_FAST_FLASH_BOOT)flash read err 1000ets_mainc 371ets Jun 8 2016 002257

To do a full reflash download the three bin files from the release you want to flash eg from

httpsovmsdexters-webdefirmwareotav32edge

Then issue

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 --before default_reset --after hard_reset write_flash --compress --flash_mode dio --flash_freq 40m --flash_size detect 0x1000 bootloaderbin 0x10000 ovms3bin 0x8000 partitionsbin

replacing the port and file paths accordingly for your system

If this fails open a support ticket on httpswwwopenvehiclescom and attach a log of the boot process or install thedeveloper environment and do a make flash

2185 Installing esptoolpy

The esptoolpy package and installation instructions can be found here

httpsgithubcomespressifesptool

78 Chapter 2 User Guide

Open Vehicles

The package normally can be installed without manual download using the python package manager ldquopiprdquo ie onUnixLinux

sudo pip install esptool

Warning You can brick your module using the esptool Only use the commands shown above

219 OBDII ECU

2191 Purpose

The OBDII interface is a connector electrical specification and protocol used for viewing the operation and statusof a car It is mandated in all light duty vehicles sold in North America beginning in 1996 and while the focus ofthe information it provides is for monitoring the emissions of Internal Combustion Engines it has proven to be ahandy port for connecting a variety of aftermarket displays and monitors to a car Electric Vehicles have no need foremissions monitoring so often omit the port from the car thus making the these aftermarket devices incompatibleThe OBDII ECU capability of the OVMS v3 is used to create a simulated OBDII port which can be used to attachmany of these aftermarket devices to the car

2192 Cabling

The cable and OBDII connector are not provided with the OVMSv3 module and can be built using the diagram belowAlternatively you can purchase the OVMS V3 HUD OBD II-F Cable from FastTech

DA26 OBDII Female Signal name6 14 CAN3-L16 6 CAN3-H8 4 amp 5 Chassis amp Signal Ground18 16 +12v switched output to HUDdongle

NB Also place a 120 ohm resistor between OBDII pins 14 amp 6 for bus termination

2193 Setup

From the Web Interface check the ldquoStart OBD2ECUrdquo box and select CAN3 from the dropdown menu (if using thewiring diagram above) This will enable the OBDII ECU Task to run the next time the OVMSv3 module is poweredon or reset Also check the ldquoPower on external 12Vrdquo box in order to feed 12v power through to the device Click onSave at the bottom of the page

From the command line the following commands are available

obdii ecu start can3 Starts the OBDII ECU taskobdii ecu stop Stops the OBDII ECU taskobdii ecu list Displays the parameters being served and their current valueobdii ecu reload Reloads the map of parameters after a config change

power ext12v on Turns on power feed to the devicepower ext12v off Turns off power feed to the device

219 OBDII ECU 79

Open Vehicles

2194 Operation

During operation an OBDII device for example a Head-Up Display (HUD) or OBDII Diagnostic module will makeperiodic requests usually a few times per second for a set of parameters The OVMSv3 module will reply to thoseparameters with the metric if configured to do so on an individual basis These parameters can be common itemssuch as vehicle speed engine RPM and engine coolant temperature but because of the differences between ICE andEV vehicles many of the parameters do not have equivalent values in an EV Speed and engine (motor) RPM can bedirectly mapped but there is typically no ldquoengine coolantrdquo That parameter (in fact most parameters) can be mappedto some other value of interest For example the Engine Coolant display on the HUD can be configured to displaymotor or battery temperature instead Engine Load (PID 4 a percentage value) is mapped by default to battery Stateof Charge (also a percentage) However note that not all vehicle metrics may be supported by all vehicles

Parameters requested by the OBDII device are referred to by ldquoPID valuerdquo Note that each PID has a specific range ofallowed values and that it is not possible to directly represent values outside that range For example PID 5 (Enginecoolant temperature) has a range of -40 to +215 it would not be possible to map the full range of motor RPMs to thisparameter Values outside the allowed range are limited to the range boundary value The complete table of possibleparameters are described here httpsenwikipediaorgwikiOBD-II_PIDsMode_01

Vehicle metrics are referred to by name See the table in Appendix 1 for a list of available metrics which vehiclesreport them and which of those are of a format that can be mapped by the OBDII ECU task

2195 Defaults and customization

By default the following mapping of PID value to OVMSv3 metric is used

PID (Dec) PID (Hex) Requested Parameter Mapped Metric Value Metric Name4 0x04 Engine Load Battery SOC vbsoc5 0x05 Coolant Temp Motor Temp vmtemp12 0x0c Motor RPM Motor RPM vmrpm13 0x0d Vehicle Speed Vehicle Speed vpspeed16 0x10 MAF Air Flow 12v Battery vb12vvoltage

The OBDII ECU task supports the remapping and reporting of PIDs 4-18 31 33 47 and 51 (all decimal) PIDs 0and 32 are used by the OBDII protocol for management and not available for assignment Other PIDs return zero

PIDs requested for which no mapping has been established are ignored by the OBDII ECU task As an aid for discov-ering which PIDs are being requested the configuration parameter lsquoautocreatersquo may be used to populate entries intothe obdii ecu list display (lsquoconfig set obd2ecu autocreate yesrsquo) Such autocreated entries are marked as ldquoUnimple-mentedrdquo and return zero to the device They are not added to the configured (saved) obd2ecumap and get cleared ateach boot or reset They may be mapped to a supported metric if desired using

config set obd2ecumap ltPIDgt ltmetric namegt

Example

OVMS config set obd2ecumap 5 vbtemp(map battery temp to engine coolant temp)

OVMS vfs edit storeobd2ecu10(script for fuel pressure PID see below)

OVMS obdii ecu reloadOBDII ECU pid map reloaded

(continues on next page)

80 Chapter 2 User Guide

Open Vehicles

(continued from previous page)

OVMS obdii ecu list

PID Type Value Metric0 (0x00) internal 00000004 (0x04) internal 95000000 vbsoc5 (0x05) metric 16000000 vbtemp10 (0x0a) script 000000011 (0x0b) unimplemented 000000012 (0x0c) internal 0000000 vmrpm13 (0x0d) internal 0000000 vpspeed16 (0x10) internal 13708791 vb12vvoltage32 (0x20) internal 0000000

Types ldquointernalrdquo means default internal handling of the PID ldquometricrdquo means a user-set mapping of PID to thenamed metric ldquounimplementedrdquo are PIDs requested by the device but for which no map has been set ldquoscriptrdquomeans the user has configured a script to handle the PID

2196 Special handling

Several PIDs are handled specially by the OBDII ECU task

bull PIDs 0 and 32 are bit masks that indicate what other PIDs are being reported by the OBDII ECU task These aremaintained internally based on the default mapped and scripted PID table Note that some OBDII devices usePID 0 as a test for ECU presence and operating mode (standard or extended) and ignore the returned valuesThe OBDII ECU task supports both modes

bull PID 12 Engine RPM is often monitored by the OBDII device to detect when the car is turned off Since anEVrsquos motor is not rotating when the car is stopped a HUD may decide to power down when it sees the RPMdrop below a particular value or if there is no variation (jitter) in its value To prevent this the OBDII ECU taskwill source a fake value of 500 rpm plus a small periodic variation if the car is not moving (vehicle speed isless than 1) To actually let the device turn off see ldquoExternal Power Controlrdquo below

bull PID 16 MAF Air Flow is commonly used by OBDII devices to display fuel flow by measuring the amount ofair entering the engine in support of combustion Since this is irrelevant to an EV the OBDII ECU task mapsthis metric to a simple integer Most HUDs displays limit this to a range of 0-199 literhr which is acceptable todisplay the +12v battery voltage Since the conversion factors are complicated this value is at best approximatein spite of its implied precision

bull Mode 9 PID 2 VIN is used to report the carrsquos DMV VIN to the attached OBDII device Since the rest ofthe parameters reported by the OBDII ECU task are simulated and some OBDII devices may use the VIN fortracking purposes the reporting of the VIN may be turned off by setting the privacy flag to ldquoyesrdquo The commandis lsquoconfig set obd2ecu privacy yesrsquo Setting it to lsquonorsquo which is the default allows the reporting of the VIN

bull Mode 9 PID 10 ECU Name is statically mapped to report the OVMSv3rsquos Vehicle ID field (vehicle name notVIN) This string may be customized to any printable string of up to 20 characters if not used with the OVMSv2 or v3 mobile phone applications (lsquoconfig set vehicle id car_namersquo)

2197 Metric Scripts

Should one desire to return a value not directly available by a single named metric it is possible to map a PID to a shortscript where combinations of metrics constants etc may be used to create a custom value Note that the restrictionson PID value ranges still applies Also note that the special handling for PID 12 (engine RPM) is not applied in theOBDII ECU task so it must be included in the script if driving a HUD

219 OBDII ECU 81

Open Vehicles

Scripts should be placed in the directory storeobd2ecuPID where PID is the decimal value of the PID to be pro-cessed Example for creating a ldquokw per kmrdquo sort of metric

ret1=OvmsMetricsAsFloat(vpspeed)ret2=OvmsMetricsAsFloat(vbpower)out=00if (ret1 gt 0) out=ret2ret1 out

Put this text in a file storeobd2ecu4 to map it to the ldquoEngine Loadrdquo PID See ldquoSimple Editorrdquo chapter for file editingor use lsquovfs appendrsquo commands (tedious) Note however that Vehicle Power (vbpower) is not supported on all cars(which is why this is not the default mapping for this PID)

Warning The error handling of the scripting engine is very rough at this writing and will typically cause a full modulereboot if anything goes wrong in a script

2198 External Power Control

Since the OVMSv3 module remains powered at all times and the normal means for deducing that a car has beenturned off donrsquot work on an EV (see PID 12 above) an external OBDII device needs to be explicitly turned on andoff This is currently done with short event scripts The following commands configure the OVMSv3 to make theexternal 12v feed follow the vehicle onoff state or use the vfs edit command to create or modify the files

vfs mkdir storeeventsvfs mkdir storeeventsvehicleonvfs mkdir storeeventsvehicleoff

vfs append power ext12v on storeeventsvehicleonext12vvfs append power ext12v off storeeventsvehicleoffext12v

220 EGPIO

2201 Hardware

The OVMS has 10 general purpose IO ports provided by a MAX7317 IO expander

The MAX7317 ports can be individually configured as either an open-drain output or an overvoltage-protected Schmittinput Being open-drain you need to add pull-up resistors for input and output switch uses to get a defined high level(eg 10K to 33V) See the datasheet for details on maximum current amp voltage ratings

Depending on your hardware configuration up to 4 ports may be used by the module 6 are generally free to use

Port Signal(s) ExpPin Default usage0 MDM_EN 15 Modem enable1 SW_CTL ndash Ext12V control (SW_12V)2 CAN1_EN + EIO_1 17 CAN1 transceiver enable3 MDM_DTR + EIO_2 19 Modem sleep control4 EIO_3 21 -free-5 EIO_4 20 -free-6 EIO_5 18 -free-7 EIO_6 16 -free-8 EIO_7 14 -free-9 EIO_8 12 -free-

82 Chapter 2 User Guide

Open Vehicles

SW_CTL (port 1) controls a BTS452R power switch which could deliver a nominal output of 25W or 18A and up to40W or 29A short term at the SW_12V pin but the main fuse of the module (located at the corner near the DB9 plug)limits the 12V current total sum of the board plus any external hardware to continuous 075A on a revision 31 boardand 10A on a revision 32 board The unswitched EXT_12V pin is also behind the fuse

The module including modem needs a 12V current share of ~80mA in full operation Calculate with 100mA to beon the safe side That leaves continuous 065A on a revision 31 board and 09A on a revision 32 board for externaldevices and addons powered by the module The fuse has a little headroom but donrsquot rely on that

SW_12V is meant to power auxiliary devices from the OVMS for example head-up displays Of course you can aswell power a standard 12V automotive relay or fan directly from this without additional hardware

The EGPIO (EIO) ports are not connected directly to the DA26 connector but are available atthe internal expansion port To route an EGPIO port to the DA26 connector connect it to oneof the GEP_17 lines at the expansion port either directly or via some additional driver

Fig 1 Expansion Port (Prototype PCB)Fig 2 DA26 Connector

Example to route EIO_8 (port 9) to GEP_7 (pin 21 on the DA26) seta jumper on pins 10+12 on the expansion port

2202 Commands

EGPIO control is provided by the egpio command set

bull egpio output ltportgt ltlevelgt [ltportgt ltlevelgt] ndash set output level(s)

bull egpio input ltportgt [ltportgt ] ndash query inputlevel(s)

bull egpio status ndash show output input amp monitor status

bull egpio monitor lton|offgt [ports] ndash enabledisablemonitoring

bull egpio monitor status ndash show current monitoring status

220 EGPIO 83

Open Vehicles

To configure a port for input it needs to be switched to output levelhigh (1) That is done automatically by the input and monitor com-mands

If you set multiple outputs the ports will be set one at a time so outputlevels will change with a slight delay You can use this behaviour to setdata lines before a clock line eg when sending bits serially into a shiftregister

Note The MAX7317 needs active polling to detect input state changes Monitoring is disabled by default it can beenabled manually or configured to start automatically on module init Without monitoring only manual input querieswill update the input state trigger input events and input metric updates

2203 Configuration

Parameter Instance Descriptionauto egpio yes = Start monitoring on boot (default no)egpio monitorports List of ports to monitor by default (space separated)egpio monitorinterval Polling interval in milliseconds (min 10 default 50)

The default interval of 50 ms (= 20 Hz) means an input signal needs to be at least 50 ms long to be detected Thispolling frequency produces a CPU load of ~05 on core 1 and is normally sufficient to detect even very short buttonpushes

2204 Metrics

Metric name Example value Descriptionmegpioinput 012345679 EGPIO input port state (ports 0 9 present=high)megpiomonitor 89 EGPIO input monitoring portsmegpiooutput 45679 EGPIO output port state

Hint to process these metrics from Javascript read them into an array using eval() and test for the presence of aport number using eg the includes() method in a browser plugin Duktape does not support includes() youcan test indexOf(port) instead

Example

var input = eval(OvmsMetricsAsJSON(megpioinput))if (inputindexOf(9) lt 0)

print(Input port 9 (EIO8) is currently lown)

2205 Events

Event Data Purposeegpioinputltportgtltstategt ndash EGPIO input port change (port=0 9 state=highlow)egpiooutputltportgtltstategt ndash EGPIO output port change (port=0 9 state=highlow)

84 Chapter 2 User Guide

Open Vehicles

Hint to listen to events from Javascript bind to msgevent on a receiver object from browser context or usePubSub from module context

Example

PubSubsubscribe(egpioinput9low function()print(Input port 9 (EIO8) is now lown)

)

221 TPMS

OVMS v3 includes a capability to read and write sets of TPMS wheel sensors IDs from the vehicle TPMS ECU andstore in your configuration Support for this is vehicle-specific and may require optional hardware boards so pleasefollow your individual vehicle guides for further information

The command to read the current TPMS wheel sensor IDs from the car is

OVMS tpms read SET

(replace SET with your own identifier for this set of wheels such as lsquosummerrsquo lsquowinterrsquo etc)

You can check the stored wheel sensor ID sets with

OVMS tpms list

If you change wheels you can write the new wheel IDs to the TPMS ECU in the car with

OVMS tpms write SET

(replace SET with your own identifier for this set of wheels such as lsquosummerrsquo lsquowinterrsquo etc)

Note that in most cases the car must be switched on for the above commands to work Please refer to your vehiclespecific user guide for more information on this

Note also that OVMS doesnrsquot have any radio capable of receiving TPMS signals and cannot read the IDs from thewheel sensors themselves OVMS can only read the IDs from the TPMS ECU in the car itself You can howeverdrop by pretty much any garage (or use any of a large number of TPMS tools) to trigger and read these IDs from thewheels Once your garage gives you the sensor IDs (each expressed as an 8 character hexadecimal ID) you can enterthem into OVMS as

OVMS tpms set SET ID1 ID2 ID3 ID4 (replace SET with your own identifier for this set of wheelsand ID1 with the hexadecimal sensor ID)

222 Optional K-Line Expansion Board

The optional K-Line Expansion Board is available to extend the capabilities of the OVMS system It can be used totalk to vehicle ECUs using K-Line communication standards

221 TPMS 85

Open Vehicles

There are two installation options

1 If you are using a modem module you install the K-Line Expansion Board on top of the modem Unscrew thefour black screws holding the modem in place In your K-Line expansion board kit you will find four brassstand offs with holes at one end and small bolts at the other Use these to screw down the modem Now orientthe K-line Expansion Board so the top left corner (marked with a white triangle) matches the white triangle onthe modem board Carefully push the K-Line Expansion Board into place (making sure that the pins align andare not bent) Once done the four black screws can be used to secure it in place

2 If you are not using a modem module you install the K-Line Expansion Board directly onto the main OVMSboard Screw the provided standoffs into the main board and Carefully attach the provided pin headers intothe main OVMS board Now orient the K-line Expansion Board so the top left corner (marked with a whitetriangle) matches the white triangle on the main OVMS board Carefully push the K-Line Expansion Board intoplace (making sure that the pins align and are not bent) Once done the four black screws can be used to secureit in place

86 Chapter 2 User Guide

Open Vehicles

Next the K-Line expansion board will need to be configured to match your vehiclersquos K-Line bus and ECU hardwarerequirements Refer to your vehicle specific guide for information on what your vehicle requires

bull S1 is used to turn onoff the extra lsquomasterrsquo mode components For most vehicles this should be OFF

bull SW1 is used to select the power source for the K-Line bus It can be 0 (no power connected) 1 (5v powerfrom USB bus) 2 (5v power converted from vehiclersquos 12v power) or 3 (12v power direct from the vehicle)For most vehicles either 2 or 3 is used

The K-Line bus from the vehicle is connected via a vehicle specific cable This connection is usually to pin 1 on theDB9 connector On OVMS modules v32 and later (as well as v31 boards labelled on board as July 2018 or later)this is internally connected to GEP7 (General Expansion Pin 7) This is necessary to bring the K-Line bus up to theinternal expansion pins (for the K-Line Expansion Board to be able to reach it)

If you have an earlier board there is a relatively simply wiring modification that can be made to upgrade to this

1 You will need a soldering iron solder and a small length of insulated wire

2 Pin 1 on the DB9 connector is the K-Line pin from the vehicle

3 Pin 21 on the DA26 connector is GEP 7 (which is also connected to a pin on internal expansion connector)

4 On the underside of the board you can solder a jumper wire between DB9 pin 1 and DA26 pin 21 to makethis connection

Please refer to the vehicle specific guides for further information on this

222 Optional K-Line Expansion Board 87

Open Vehicles

88 Chapter 2 User Guide

CHAPTER 3

Plugins

The OVMS can easily be extended by plugins Plugins may consist of any combination of module scripts (Javascript)and web UI extensions (HTML)

Installation currently needs to be done manually but is simple See below and the plugin documentation on specificsteps and on how to use the plugin functions A plugin store with simplified download and optional automatic updatingwill be provided in the future

This page is intended as an overview of all plugins currently available in the OVMS repository If yoursquore a plugindeveloper and want to add your plugin here please submit a pull request containing your plugin directory Organizeyour files and include a READMErst as shown here

31 ABRP abetterrouteplannercom

Send live data to abetterrouteplannercom

Overview

abetterrouteplanner is probably the best website to plan a route with an EV and optimize the number of stops neededand where to charge your vehicle

Moreover it has a wonderful functionality to update your plan taking into account your live data to adjust withthe real consumption of the vehicle by connecting an obd device and soft like EVNotify or Torque Pro

This plugin sends your live data from the OVMS box

Author David S Arnold

New in version 12 Your own parameters (car model abrp token but also api-url) are now stored as config param-eters you can consult them using the shell with config list usr or modify with config set command

89

Open Vehicles

Contents

bull ABRP abetterrouteplannercom

ndash Installation

ndash Script code

ndash Usage

311 Installation

You can use the embedded website toolsshell and toolseditor of the OVMS box to create the directory and file Thiseditor will allow you to paste the plugin code from the documentation

Files to be created in storescripts

bull ovmsmainjs if not already exists

bull sendlivedata2abrpjs by copying the file below

Next configure your car model API URL amp token

Note ABRP only supports live data feeds for some car models You can request a notification when support has beenadded for your car Do not feed live data using other car models Also ABRP has not yet added this OVMS pluginas a general data source so you need to disguise as ldquoTorquerdquo

If using the ABRP 4 UI

bull Login to abetterrouteplanner

bull Open ldquoSettingsrdquo enable detailed setup

bull Add your car (if ABRP has no live support for your car model it will display ldquoLive data not availablerdquo)

bull Click ldquoLink Torquerdquo click ldquoNextrdquo 3 times

bull Set the ldquoWebserver URLrdquo by config set usr abrpurl Note according to Iterniothe URL httpapiiterniocom1tlmsend should generally be used here instead of theTorque specific one displayed

bull Set the ldquoUser Email Addressrdquo (API token) by config set usr abrpuser_token

If using ABRP classic UI

bull Login to abetterrouteplanner in classic view

bull In Settingsmore Settings therersquos an item lsquoLive Car Connectionrsquo with 2 buttons lsquoSetuprsquo and lsquoView livedatarsquo

bull Click on Setup (if there is no Setup button live data support isnrsquot available for your car model)

bull Click on Torque

bull Set the ldquoWebserver URLrdquo by config set usr abrpurl

bull Set the ldquoUser Email Addressrdquo (API token) by config set usr abrpuser_token

Determine your car model code

bull Open API car models list

90 Chapter 3 Plugins

Open Vehicles

bull To improve readability optionally paste the page into JSONlintcom

bull Search for your car brand and model the code is the field following the car specification for examplerenaultzoe2052r110

bull Set the code by config set usr abrpcar_model

Finally reboot your OVMS module This was a one-time configuration

Yoursquore now ready Test it with the shell page in the embedded web server using the command script eval abrpinfo() and then with the command script eval abrponetime() You can also do it with the mobile app

312 Script code

This is a javascript code to extract in the file sendlivedata2abrpjs

Warning note the minimum firmware version 32008-147

1 2 storescriptssendlivedata2abrpjs3 4 Module plugin5 Send live data to a better route planner6 This version uses the embedded GSM of OVMS so theres an impact on data

rarr˓consumption7 requires OVMS firmware version 32008-147 minimum (for HTTP call)8 9 Version 13 2020 inf0mike (forum httpswwwopenvehiclescom)

10 11 Enable12 - install at above path13 - add to storescriptsovmsmainjs14 abrp = require(sendlivedata2abrp)15 - script reload16 17 Usage18 - script eval abrpinfo() =gt to display vehicle data to be sent to abrp19 - script eval abrponetime() =gt to launch one time the request to abrp server20 - script eval abrpsend(1) =gt toggle send data to abrp21 - (0) =gt stop sending data22 - script eval abrpresetConfig() =gt reset configuration to defaults23 24 Version 13 updates25 - Fix for rounding of fractional SOC causing abrp to report SOC off by 126 - Fix for altitude never being sent27 - New convenience method to reset config to defaults28 29 Version 12 updates30 - based now on OVMS configuration to store user token car model and url31 - review messages sent during charge32 - send a message when vehicle is on before moving to update abrp33 34 Version 11 fix and update35 - fixed the utc refreshing issue36 - send notifications37 - send live data only if necessary

(continues on next page)

31 ABRP abetterrouteplannercom 91

Open Vehicles

(continued from previous page)

38 39

40

41

42 43 Declarations44 CAR_MODEL find your car model here httpsapiiterniocom1tlmget_carmodels_

rarr˓listapi_key=32b2162f-9599-4647-8139-66e9f952837045 OVMS_API_KEY API_KEY to access to ABRP API given by the developer46 MY_TOKEN Your token (corresponding to your abrp profile)47 TIMER_INTERVAL to subscribe to a ticker event48 URL url to send telemetry to abrp following httpsiterniocomindexphp

rarr˓iternio-telemetry-api49 CR Carriage Return for console prints50 51 objTLM JSON object containing data read52 objTimer timer object53 54

55 const CAR_MODEL = 56 const OVMS_API_KEY = 32b2162f-9599-4647-8139-66e9f952837057 const MY_TOKEN = ----58 const TIMER_INTERVAL = ticker60 every minute59 const EVENT_MOTORS_ON = vehicleon60 const URL = httpapiiterniocom1tlmsend61

62 const DEFAULT_CFG = 63 url URL64 user_token MY_TOKEN65 car_model CAR_MODEL66 67

68 const CR = n69

70 var objTLM71 var objTimer objEvent72 var sHasChanged = 73 var bMotorsOn = false74

75 initialise from default76 var abrp_cfg = JSONparse(JSONstringify(DEFAULT_CFG))77

78 check if json object is empty79 function isJsonEmpty(obj) 80 for(var key in obj) 81 if(objhasOwnProperty(key))82 return false83 84 return true85 86

87 Read amp process config88 function readConfig() 89 check if config exist90 var read_cfg = OvmsConfigGetValues(usr abrp)91 print(JSONstringify(read_cfg) + CR)92 if (isJsonEmpty(read_cfg) == true)

(continues on next page)

92 Chapter 3 Plugins

Open Vehicles

(continued from previous page)

93 no config yet set the default values94 OvmsConfigSetValues(usrabrpabrp_cfg)95 else 96 config existing97 abrp_cfgurl = read_cfgurl98 abrp_cfguser_token = read_cfguser_token99 abrp_cfgcar_model = read_cfgcar_model

100 101 102

103 Make json telemetry object104 function InitTelemetryObj() 105 return 106 utc 0107 soc 0108 soh 0109 speed 0110 car_model abrp_cfgcar_model111 lat 0112 lon 0113 alt 0114 ext_temp 0115 is_charging 0116 batt_temp 0117 voltage 0118 current 0119 power 0120 121 122

123 Fill json telemetry object124 function UpdateTelemetryObj(myJSON) 125 if(myJSON)126 if the data object is undefined or null then return early127 return false128 129 var read_num = 0130 var read_str = 131 var read_bool = false132

133 sHasChanged = 134

135 if (bMotorsOn) 136 sHasChanged = _MOTORS-ON137 bMotorsOn = false138 139

140 using Mathfloor avoids rounding up of 5 values to next whole number141 as some vehicles report fractional values Abrp seems to only support integer

rarr˓values142 read_num = Mathfloor(Number(OvmsMetricsValue(vbsoc)))143 if (myJSONsoc = read_num) 144 myJSONsoc = read_num145 sHasChanged += _SOC + myJSONsoc + 146 147

148 read_num = Number(OvmsMetricsValue(vbsoh))(continues on next page)

31 ABRP abetterrouteplannercom 93

Open Vehicles

(continued from previous page)

149 if (myJSONsoh = read_num) 150 myJSONsoh = read_num151 sHasChanged += _SOH + myJSONsoh + 152 153

154 if ( (myJSONsoh + myJSONsoc) == 0 ) 155 Sometimes the canbus is not readable and abrp doesnt like 0 values156 print(canbus not readable reset module and then put motors on + CR)157 return false158 159

160 myJSONlat = OvmsMetricsAsFloat(vplatitude)toFixed(3)161 above code line works except when value is undefined after reboot162

163 read_num = OvmsMetricsAsFloat(vplatitude)164 read_num = read_numtoFixed(3)165 if (myJSONlat = read_num) 166 myJSONlat = read_num167 sHasChanged += _LAT + myJSONlat + deg168 169

170 read_num = Number(OvmsMetricsAsFloat(vplongitude))171 read_num = read_numtoFixed(3)172 if (myJSONlon = read_num) 173 myJSONlon = read_num174 sHasChanged += _LON + myJSONlon + deg175 176

177 read_num = Number(OvmsMetricsAsFloat(vpaltitude))178 read_num = read_numtoFixed(1)179 if (read_num lt= (myJSONalt - 2) || read_num gt= (myJSONalt + 2)) 180 myJSONalt = read_num181 sHasChanged += _ALT + myJSONalt + m182 183

184 read_num = Number(OvmsMetricsValue(vbpower))185 myJSONpower = read_numtoFixed(1)186

187 myJSONspeed=Number(OvmsMetricsValue(vpspeed))188 myJSONbatt_temp=Number(OvmsMetricsValue(vbtemp))189 myJSONext_temp=Number(OvmsMetricsValue(vetemp))190 myJSONvoltage=Number(OvmsMetricsValue(vbvoltage))191 myJSONcurrent=Number(OvmsMetricsValue(vbcurrent))192

193 myJSONutc = Mathtrunc(Datenow()1000)194 myJSONutc = OvmsMetricsValue(mtimeutc)195

196 read_bool = Boolean(OvmsMetricsValue(vccharging))197 vccharging is also on when regen =gt not wanted here198 read_str = OvmsMetricsValue(vcstate)199 if ( (read_str == charging) || (read_str == topoff) ) 200 myJSONis_charging = 1201 read_str = OvmsMetricsValue(vcmode)202 if (sHasChanged = ) 203 sHasChanged += _CHRG + read_str + ( + OvmsMetricsValue(vccharging)

rarr˓+ )204 print(Charging in mode + read_str + CR)

(continues on next page)

94 Chapter 3 Plugins

Open Vehicles

(continued from previous page)

205 206 else 207 myJSONis_charging = 0208 209

210 myJSONcar_model = abrp_cfgcar_model211

212 return (sHasChanged == )213 214

215 Show available vehicle data216 function DisplayLiveData(myJSON) 217 var newcontent = 218 newcontent += altitude = + myJSONalt + m + CR GPS altitude219 newcontent += latitude = + myJSONlat + deg + CR GPS latitude220 newcontent += longitude= + myJSONlon + deg + CR GPS longitude221 newcontent += ext temp = + myJSONext_temp + degC + CR Ambient

rarr˓temperature222 newcontent += charge = + myJSONsoc + + CR State of charge223 newcontent += health = + myJSONsoh + + CR State of health224 newcontent += bat temp = + myJSONbatt_temp + degC + CR Main battery

rarr˓momentary temperature225 newcontent += voltage = + myJSONvoltage + V + CR Main battery

rarr˓momentary voltage226 newcontent += current = + myJSONcurrent + A + CR Main battery

rarr˓momentary current227 newcontent += power = + myJSONpower + kW + CR Main battery

rarr˓momentary power228 newcontent += charging = + myJSONis_charging + CR yes = currently

rarr˓charging229 print(newcontent)230 231

232 function InitTelemetry() 233 objTLM = InitTelemetryObj()234 sHasChanged = 235 236

237 function UpdateTelemetry() 238 var bChanged = UpdateTelemetryObj(objTLM)239 if (bChanged) DisplayLiveData(objTLM) 240 return bChanged241 242

243 function CloseTelemetry() 244 objTLM = null245 sHasChanged = 246 247

248 http request callback if successful249 function OnRequestDone(resp) 250 print(response=+JSONstringify(resp)+CR)251 OvmsNotifyRaise(info usrabrpstatus ABRP + sHasChanged)252 253

254 http request callback if failed255 function OnRequestFail(error)

(continues on next page)

31 ABRP abetterrouteplannercom 95

Open Vehicles

(continued from previous page)

256 print(error=+JSONstringify(error)+CR)257 OvmsNotifyRaise(info usrabrpstatus ABRP + JSONstringify(error))258 259

260 Return full url with JSON telemetry object261 function GetUrlABRP() 262 var urljson = abrp_cfgurl263 urljson += 264 urljson += api_key= + OVMS_API_KEY265 urljson += amp266 urljson += token= + abrp_cfguser_token267 urljson += amp268 urljson += tlm= + encodeURIComponent(JSONstringify(objTLM))269 print(urljson + CR)270 return urljson271 272

273 Return config object for HTTP request274 function GetURLcfg() 275 var cfg = 276 url GetUrlABRP()277 done function(resp) OnRequestDone(resp)278 fail function(err) OnRequestFail(err)279 280 return cfg281 282

283 function SendLiveData() 284 if (UpdateTelemetry()) 285 HTTPRequest( GetURLcfg() )286 287 288

289 function Reactivate_MotorsOn() 290 bMotorsOn = true291 SendLiveData()292 293

294 function InitTimer() 295 objTimer = PubSubsubscribe(TIMER_INTERVAL SendLiveData)296 objEvent = PubSubsubscribe(EVENT_MOTORS_ON SendLiveData)297 298

299 function CloseTimer() 300 PubSubunsubscribe(objEvent)301 PubSubunsubscribe(objTimer)302 objEvent = null303 objTimer = null304 305

306 API method abrponetime()307 Read and send data but only once no timer launched308 exportsonetime = function() 309 readConfig()310 InitTelemetry()311 SendLiveData()312 CloseTelemetry()

(continues on next page)

96 Chapter 3 Plugins

Open Vehicles

(continued from previous page)

313 314

315 API method abrpinfo()316 Do not send any data just read vehicle data and writes in the console317 exportsinfo = function() 318 readConfig()319 InitTelemetry()320 UpdateTelemetry()321 CloseTelemetry()322 323

324 API method abrpresetConfig()325 Resets stored config to default326 exportsresetConfig = function() 327 OvmsConfigSetValues(usrabrp DEFAULT_CFG)328 print(JSONstringify(abrp_cfg))329 OvmsNotifyRaise(info usrabrpstatus ABRPconfig changed)330 331

332 API method abrpsend()333 Checks every minut if important data has changed and send it334 exportssend = function(onoff) 335 if (onoff) 336 readConfig()337 if (objTimer = null) 338 print(Already running + CR)339 return340 341 print(Start sending data + CR)342 InitTelemetry()343 SendLiveData()344 InitTimer()345 OvmsNotifyRaise(info usrabrpstatus ABRPstarted)346 else 347 if (objTimer == null) 348 print(Already stopped + CR)349 return350 351 print(Stop sending data + CR)352 CloseTimer()353 CloseTelemetry()354 OvmsNotifyRaise(info usrabrpstatus ABRPstopped)355 356

313 Usage

How to make it run

bull install as described in lsquoInstallationrsquo

bull add to storescriptsovmsmainjs abrp = require(sendlivedata2abrp)

bull script reload

With command lines in the OVMS android or iOS app in the messages part

31 ABRP abetterrouteplannercom 97

Open Vehicles

bull script eval abrpinfo() =gt to display vehicle data to be sent to abrp

bull script eval abrponetime() =gt to launch one time the request to abrp server

bull script eval abrpsend(1) =gt toggle send data to abrp

bull script eval abrpsend(0) =gt stop sending data

bull script eval abrpresetConfig() =gt reset configuration to defaults

Also in the messages part configuration can be updated with

bull config set usr abrpcar_model ltvaluegt

bull config set usr abrpurl ltvaluegt

bull config set usr abrpuser_token ltvaluegt

32 AuxBatMon 12V History Chart

Web chart showing last 24 hours of 12V battery metrics (similar to Android App)

Version 23 by Michael Balzer ltdexterdexters-webdegt

The module plugin records the relevant 12V battery metrics (voltage reference voltage current charger and environ-ment temperatures) once per minute for up to 24 hours by default

The web plugin renders these recordings into a time series chart and continues feeding live updates into the chart Thechart is zoomable and can be panned along the X axis

Since version 20 metrics history data is stored in a file and restored automatically on rebootreload This needsOVMS firmware gt= 32008-235 to work (will fallback to no saving on earlier versions)

98 Chapter 3 Plugins

Open Vehicles

Version 23 changes the file and transfer encoding from JSON to CBOR Upgrading is strongly recommended asthis has a substantial performance gain for both the module (scripting engine) and the web user interface (loading thechart)

321 Installation

1 Save auxbatmonjs as storescriptslibauxbatmonjs

2 Add line to storescriptsovmsmainjs

bull auxbatmon = require(libauxbatmon)

3 Issue script reload or evaluate the require line

4 Install auxbatmonhtm web plugin recommended setup

bull Type Page

bull Page usrauxbatmon

bull Label 12V History

bull Menu Tools

bull Auth Cookie

322 Configuration

No live config currently You can customize the sample interval (default 60 seconds) and the history size (default24 hours) by changing the constants in the code Take care to match a customization in both the module and the webplugin

The persistent history storage file is storeusrauxbatmoncbor by default It needs ~30 kB with the defaultconfiguration If space is tight on your store partition you can change the file location to sd in the sourcecode

323 Plugin API

auxbatmondump(CBOR) -- dump recorded history data in CBOR format (binary)auxbatmondump() -- dump recorded history data in JSON formatauxbatmondump() -- get a copy of the history data object

33 ChgInd Charge State Indicator

Control three LEDs to indicate charging amp SOC level

Version 10 by Michael Balzer ltdexterdexters-webdegt

Following an idea by ldquogreen_foxrdquo on the german Twizy forum (not limited to the Twizy) to implement an externallyvisible charge indicator

Use a red a green and a blue LED to signal charge state

bull OFF = not charging

bull RED = charging SOC below 20

33 ChgInd Charge State Indicator 99

Open Vehicles

bull YELLOW (RED+GREEN) = charging SOC 20 80

bull GREEN = charging SOC above 80

bull BLUE = fully charged (held for 15 minutes)

This plugin uses three EGPIO lines to control the three LEDs (KISS) By using a shift register this could be reducedto two lines by using a serial protocol to one line The latter would need protocol support in the EGPIO (todo)

331 Installation

1 Save chgindjs as storescriptslibchgindjs

2 Add line to storescriptsovmsmainjs

bull chgind = require(libchgind)

3 Issue script reload or evaluate the require line

332 Configuration

EGPIO ports to useconst LED_red = 4 EIO_3const LED_green = 5 EIO_4const LED_blue = 6 EIO_5

Time to hold BLUE state after charge stopconst holdTimeMinutes = 15

333 Plugin API

chgindset(state) -- set LED state (offredyellowgreenblue)

34 Edimax Smart Plug Control

Smart Plug control for Edimax models SP-1101W SP-2101W et al

Version 20 by Michael Balzer ltdexterdexters-webdegt

Note may need HTTPrequest() digest auth support to work with newer Edimax firmware (untested)

The smart plug can be bound to a defined location Automatic periodic recharging or charge stop can be configuredvia main battery SOC level andor 12V battery voltage level The plugin can also switch off power at the charge stopevent of the main andor 12V battery

341 Installation

1 Save edimaxjs as storescriptslibedimaxjs

2 Add line to storescriptsovmsmainjs

bull edimax = require(libedimax)

3 Issue script reload

100 Chapter 3 Plugins

Open Vehicles

4 Install edimaxhtm web plugin recommended setup

bull Type Page

bull Page usredimax

bull Label Edimax Smart Plug

bull Menu Config

bull Auth Cookie

5 Install edimax-statushtm web plugin recommended setup

bull Type Hook

bull Page status

bull Hook bodypost

The edimax-statushtm plugin adds power control to the Status pagersquos vehicle panel

342 Configuration

Use the web frontend for simple configuration

Param Instance Descriptionusr edimaxip Edimax IP addressusr edimaxuser username admin by defaultusr edimaxpass password 1234 by defaultusr edimaxlocation optional restrict auto switch to this locationusr edimaxsoc_on optional switch on if SOC atbelowusr edimaxsoc_off optional switch off if SOC ataboveusr edimaxchg_stop_off optional yes = switch off on vehiclechargestopusr edimaxaux_volt_on optional switch on if 12V level atbelowusr edimaxaux_volt_off optional switch off if 12V level ataboveusr edimaxaux_stop_off optional yes = switch off on vehiclecharge12vstop

343 Usage

script eval edimaxget()script eval edimaxset(on | off)script eval edimaxinfo()

Note get() amp set() do an async update (if the location matches) the result is logged Use info() to show thecurrent state

344 Events

usredimaxonusredimaxoffusredimaxerror

34 Edimax Smart Plug Control 101

Open Vehicles

35 Foglight Speed Adaptive Foglight

Automatic speed adaptive fog light using OVMS GPIO port

bull foglightjs ndash module script

bull foglighthtm ndash web dashboard extension

Details httpsdocsopenvehiclescomenlatestcomponentsovms_scriptdocsfoglighthtml

36 PwrMon Trip Power Chart

Web chart showing average speed power amp energy use on the road

Version 12 by Michael Balzer ltdexterdexters-webdegt

The plugin calculates average speed (kph) power (kW) amp energy use (Wpk = Whkm) from the odometer altitudeand energy counters (metrics vbenergyused amp vbenergyrecd) so the vehicle needs to provide thesewith reasonable precision amp resolution

The optional module plugin continuously records and stores the metrics history so the chart can load the last 20 km(by default) when opened The chart will then continue to add live metrics data Without the module plugin the chartwill only display live data

The chart is zoomable and can be panned along the X axis The four data series can be selected and shownhidden asusual by clicking on the series names in the legend click into the chart to highlight a specific data point

The live data may be more accurate than the data stored by the module plugin as it will react directly to the odometerchange while the module plugin can only check the odometer once per second

Version 12 changes the file and transfer encoding from JSON to CBOR Upgrading is strongly recommended asthis has a substantial performance gain for both the module (scripting engine) and the web user interface (loading thechart)

102 Chapter 3 Plugins

Open Vehicles

361 Installation

1 Install pwrmonhtm web plugin recommended setup

bull Type Page

bull Page usrpwrmon

bull Label Trip Power Chart

bull Menu Tools

bull Auth Cookie

2 Optionally

bull Save pwrmonjs as storescriptslibpwrmonjs

bull Add line to storescriptsovmsmainjs

ndash pwrmon = require(libpwrmon)

bull Issue script reload or evaluate the require line

362 Configuration

No live config currently You can customize the sample interval (default 03 km) and the history size (default 20 km)by changing the constants in the code The storage file and interval (1 km) can also be changed

On the web plugin you can customize the live sample interval (default 03 km doesnrsquot need to match the moduleplugin) and the initial zoom (default 8 km)

The persistent history storage file is storeusrpwrmoncbor by default It needs ~10 kB with the defaultconfiguration If space is tight on your store partition you can change the file location to sd in the sourcecode or disable the file by setting an empty string as the filename

363 Plugin API

pwrmondump(CBOR) -- dump recorded history data in CBOR format (binary)pwrmondump() -- dump (print) recorded history data in JSON formatpwrmondata() -- get a copy of the history data object

37 RegenMon Regen Brake Monitor

Live monitoring for regenerative brakelight amp acceleration level

bull regenmonhtm

Details httpsdocsopenvehiclescomenlatestcomponentsovms_webserverdocsregenmonhtml

38 REPIDScan OBD2 PID Scanner UI

Web UI for the OVMS3 RE toolkitrsquos OBD2 PID scanner

Version 21 by Michael Balzer ltdexterdexters-webdegt

37 RegenMon Regen Brake Monitor 103

Open Vehicles

bull 10 Initial release

bull 20 Highlight differences between scan results

bull 21 PID step support

This is a web frontend for the re obdii scan commands

Some basic usage notes are included but you really should have some knowlegde of how accessing ECU and otheronboard devices via OBD-IIUDS works Some pointers to get started

bull httpsenwikipediaorgwikiOBD-II_PIDs

bull httpsenwikipediaorgwikiUnified_Diagnostic_Services

You will need OVMS firmware release 32015-324 or higher to be able to use all features

The UI allows to easily define and keep multiple scans along with notes Scan results of two successive runs can becompared directly The UI checks if vehicle NONE is loaded and shows a button to switch to that otherwise The CANbuses can be started from the UI as well

Scan results are shown in plain text form as delivered by the underlying commands

Feel free to improve and extend (and submit your results)

381 Installation

1 Install repidscanhtm web plugin recommended setup

104 Chapter 3 Plugins

Open Vehicles

bull Type Page

bull Page usrrepidscan

bull Label RE PID Scanner

bull Menu Tools

bull Auth Cookie

382 Usage

Warning The scanner allows to use any poll type Requests will be sent with PIDs only though but somedevices may fail to validate the request length so be careful not to use any write or control poll types

The OBD2 PID scanner performs a series of OBDUDS requests for a range of PIDs and displays the results OnlyPIDs with positive results (responses) will be shown in the results

Enter all values hexadecimal (case irrelevant) Default RXID is TXID+8 try RXID range 500-7FF if you donrsquot knowthe responding ID To send broadcast requests set TXID to 7DF and RXID to 7E8-7EF The PID range must matchthe poll type PID constraints (816 bit)

Click ldquoStartrdquo to run a scan Only one scan can be active at a time but you donrsquot need to stop a scan to start anotherrun

Scan results will be shown automatically when the scan has been completed Scanning a large range of PIDs may takesome time to get intermediate results click ldquoStatusrdquo You can also start the scan do something else and return to thetool later

Differences between two scans are highlighted in both result tabs with added PIDs being marked green (yellow innight mode) and byte value changes being marked red No highlighting is applied if the scans donrsquot share any PIDs

On the next scanner start the previous results (if any) will be copied to the ldquoPreviousrdquo tab You can switch tabs by themouse or keyboard to compare them and look for differences eg after having changed some control on the car

All inputs and outputs can be saved to and loaded from files on the module or SD card Use this to define your areasof interest so you can easily re-run a previously defined scan the next day File format is plain readable JSON so youcan continue analysis or prepare scans offline

Notes to avoid clashing of scan polls with vehicle polls use the scanner only with the vehicle module NONE TheCAN bus to use needs to have been started in active mode The scanner does not send session or tester presencemessages if you need these use the re obdii tester tool or the obdii canX request command

39 Renault Twizy

391 Dashboard-Tuneslider

Add recuperation control to the dashboard

bull dashboard-tunesliderhtm

Details httpsdocsopenvehiclescomenlatestcomponentsovms_webserverdocsplugin-twizydashboard-tunesliderhtml

39 Renault Twizy 105

Open Vehicles

392 eDriver BMS Monitor

Status monitor for the Twizy custom eDriver BMS by Pascal Ripp

Version 20 by Michael Balzer ltdexterdexters-webdegt

This is a simple web page plugin to display the standard battery cell info along with the additional custom data providedby the eDriver BMS on one page

Additional custom data

bull Main state

bull Error state

bull BMS internal temperature

bull AUX relay state

bull Cell balancing states

Note these are read from their respective custom metrics xrtbms see Custom Metrics

Overall SOC voltage current and coulombenergy counters are also shown to simplify battery capacity and currentsensor calibration

Check out the eDriver BMS Manual for details or contact Pascal in case of questions

Installation

1 Install edrvmonhtm web plugin recommended setup

bull Type Page

bull Page usredrvmon

bull Label eDriver BMS Monitor

bull Menu Vehicle

bull Auth Cookie

106 Chapter 3 Plugins

Open Vehicles

History

bull V20 ndash Added cell balancing time totals + SOC amp voltage usecharge range

bull V10 ndash Initial release

393 Page-Command

only command options as UI

Version 02 Matthias Greiling ltmatthiasgreilingdegt

Details

This view only presents commands to OVMS While driving you can choose between different drive modes Thecoloured area indicates the active drive mode Activate an other mode by touching or clicking the grey bordered areaTo change again simply click or touch again the same or another ares Furthermore you can limit the speed online topredefined values The speed limit signs are common in germany and display kmh Just activate the sign you want tobe limited to - another touch will deactivates the limit of the chosen one

Installation

1 Install page-commandhtml web plugin recommended setup

bull Type Page

bull Page usrcommand

bull Label

bull Menu Main

bull Auth Cookie

39 Renault Twizy 107

Open Vehicles

History

bull V02 ndash Simplfy backgrounds icons of command row

bull V01 ndash Initial release

394 WifiConsole

Backend for WifiConsole hardware extension

bull WifiConsolejs

Details httpsgithubcomdexterbgWifiConsole

310 VW e-Up Mii Citigo

3101 ECUToolkit VW e-Up ECU Access

Library and web UI for diagnostics and configuration of the e-Up Mii Citigo ECUs

bull Library version 05 by Michael Balzer ltdexterdexters-webdegt

bull Web UI version 01 by Michael Balzer ltdexterdexters-webdegt

108 Chapter 3 Plugins

Open Vehicles

You will need OVMS firmware release 32016-226 or higher to be able to use this

The library is meant as a general tool to access the VW ECUs It provides means to simplify sending OBDUDScommands to ECUs by ID and to automate diagnostic session loginlogout It provides methods to set the workshopcode (WSC) do security authorization do scans and codings

The web UI allows to open multiple tools for different ECUs and saveload the current setup including the tool states

Feel free to improve and extend (and submit your results)

Warning

Warning Use at your own risk This ECU toolkit is based on reverse engineering I havenrsquot had access to anyofficial documentation Itrsquos only been used and tested on few vehicles chances are there will be issues with othervehicle configurations

Note If yoursquore interested in a fully featured VW ECU tool consider buying the excellent third party tools VCDS(httpswwwross-techcomvag-com) or OBDeleven (httpsobdelevencom) which fully support all VW vehiclesincluding of course the e-Up These tools also can decode most DTCs and provide detailed information on faultconditions

310 VW e-Up Mii Citigo 109

Open Vehicles

Installation

1 Save xvu-ecujs as storescriptslibxvu-ecujs

bull Add to storescriptsovmsmainjs

ndash xvu = ecu require(libxvu-ecu)

ndash or in case you already have the xvu namespace object just add the ecu part

bull Issue script reload or evaluate the require line

2 Install xvu-ecu-toolhtm web plugin recommended setup

bull Type Page

bull Page xvuecutoolkit

bull Label ECU Toolkit

bull Menu Vehicle

bull Auth Cookie

Usage

You can use the toolkit without ignition on if you just want to review some stored backup or dry run some coding tests

The web UI shows the list of known ECUs on the left side (or upper side on mobile devices) The list can be filteredto only show ECUs installed in the car by clicking the ldquordquo button this will need ignition on so the library can accessthe CAN gateway

Open a tool by selecting the ECU to investigate then clicking the tool button below the list To switch between toolsclick on the tool tab title To close a tool click the cross mark on the tool tabrsquos title

You can save the toolkit state (ie all open tools including their data) to a file on the OVMS SD card or store partitionLoading replaces the current toolkit state by the one loaded so discards any unsaved content

Click the menu box title to collapse or expand the box Loading will automatically collapse the menu box on mobiledevices

Enable the debug log messages to see which OBDUDS commands are performed The log will be shown in the panelfooter The read only mode inhibits OBDUDS commands doing PID changes DTC clearing or security accessesThey will still be logged so you can see what would be done

If you encounter issues send me a debug log

Scan tool

The Scan tool is considered to be safe as no write operations are involved

Scan results include the current hardware amp software versions the codings and DTCs so are useful as a backup forlater reference

To do a scan turn the ignition on select the ECU to scan and click the Scan button A new tab will open and thescan will start immediately Scans take from 5 - 15 seconds depending on the number of subsystems and other systemactivity The results will be shown in the tab

110 Chapter 3 Plugins

Open Vehicles

Coding tool

The Coding tool allows to change the ECU configuration ECUs may accept invalid codings that possibly can causehardware damage so be cautious ECUs will record all your write operations Even though the toolkit reuses the lastworkshop code found in the ECU by default there still will be a log entry carrying the date of the change

Use the full coding input field to copy amp paste codings for backups amp restores eg from a former scan result Afterpasting click outside the field to validate the coding and update the bits

Subsystem codings are included in the ECU coding other than in the scan result where they are shown at the respectivesubsystem You can paste amp write only the main coding the subsystem will then not be changed

Select a byte position to view and change the individual bits of that byte Only labels for bits known to work onthe VW e-Up models have been added up to now source of this is the german GoingElectric forum amp wiki (httpswwwgoingelectricde)

To submit a changed coding to the ECU click ldquoWriterdquo Most codings donrsquot need a security code so leave the fieldempty unless ldquoWriterdquo aborts with a security clearance error Security codes can be found in the forums and officialrepair manuals

Library API

Documentation on the API methods is in preparation

As this is currently an alpha release the API is work in progress and likely to change

If yoursquore interested in using whatrsquos considered stable now or possibly even contribute please read the source andcontact me

311 Installing Module Plugins

A module plugin normally consists of a single Javascript file that needs to be placed in the storescriptslibdirectory The plugin is then loaded by a require() call which can be done manually as needed or automaticallyon boot by adding it to the storescriptsovmsmainjs file

1 Menu Tools rarr Editor

2 Cancel the open dialog

3 Paste the plugin source into the editor

4 Save as rarr storescriptslib using the name as shown in the plugin documentation

5 Open rarr (one level up) rarr ovmsmainjs

6 Add the require() call as shown in the plugin documentation

7 Save

8 Reload JS Engine

The plugin is now installed and activated

Hint you can now try out the commands provided by the plugin directly from the editor Clear the editor fill in thecommand or Javascript snippet click Evaluate JS The output will be shown below the input field

To deactivate a plugin comment out the require() call by prefixing the line with and do another JS enginereload To remove a plugin remove the require() call and delete the file using vfs rm storescriptslib

311 Installing Module Plugins 111

Open Vehicles

312 Installing Web Plugins

A web plugin normally consists of a single HTML file Web plugins can be meant to render new pages or to hook intoan existing page They need an initial registration to work

1 Menu Config rarr Web Plugins

2 (add)

3 Set type and name as suggested in the plugin documentation

4 Save

5 Edit

6 Set attributes as suggested in the plugin documentation

7 Paste the plugin source into the content area

8 Save

The plugin is now installed and activated

Hint you can use the text editor (tools menu) to change or update an already installed web plugin Simply edit theplugin file in folder storeplugin directly the system will reload the plugin as soon as you save it

To deactivate a web plugin set the state to ldquooffrdquo To remove a plugin click rarr Save

112 Chapter 3 Plugins

CHAPTER 4

BMW i3 i3s

Vehicle Type BMWI3

This vehicle type supports the BMW i3 and i3s models All model years should be supported

The OVMS support was developed Jan 2021

It was developed against the authorrsquos 2018 120Ah i3s BEV I would welcome engagement from the owner of a REXtype to further develop metrics related to the REX engine Testing by drivers of LHD models as well as those withthe smaller batteries will also be helpful

As of this release this vehicle support is read-only and cannot send commands to the car

41 Support Overview

ldquotbardquo item are still on the to-do list and are not currently supported

113

Open Vehicles

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable OBD-II cable left-handed cable worked best in my RHD carGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (or any compatible antenna)SOC Display YesRange Display YesCabin Pre-heatcool Control tbaGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display tbaCharge Status Display YesCharge Interruption Alerts YesCharge Control tbaLockUnlock Vehicle tbaValet Mode Control NoOthers 12v battery voltagecurrent battery true SOC etc

42 WARNINGS

421 Alarm behaviour

As standard the i3 will sound the alarm if anything is left connected to the OBD-II port when the car is locked

A tool like Bimmercode will allow you to disable this Alternatively you will need to disconnect the OVMS unit beforelocking the car

A future version may add a command to allow you to disable this alarm directly from your OVMS shell

422 12V Battery drain

The i3 has a small 20Ah AGM 12v battery Whilst care has been taken to minimize OVMSrsquo power usage OVMScould eventually drain this battery if the car is left unplugged and locked OVMS will also send an alert if 12V dropsunder 12V alert threshold (See 12V Calibration section)

HOWEVER If you are going to leave the car for a fews days it is recommended to unplug OVMS

43 Car status

The car is accessible over the OBD-II port when it is running (ignition on) and for a short time (40 seconds or so) afterit is turned off or the car is ldquotweakedrdquo (lock button pushed connected-drive command received etc)

Unfortunately this means that when your car is standing or charging OVMS only has intermittent access to data fromthe car

By observation whilst the car is charging it wakes up now and then (seems to be every 30 minutes) So at those timeswe can update our SOC etc

114 Chapter 4 BMW i3 i3s

Open Vehicles

Metrics ldquoveawakerdquo tells you if the car is awake or not Metric ldquoxi3sagerdquo will tell you how many minutes have passedsince we last received data from the car

You may also refer to metric xi3spollermode as follows

Mode Meaning0 Car is asleep - no OBD-II data traffic1 Car OBD-II is awake - we are seeing data traffic2 Car is ready to drive or driving3 Car is charging

44 Custom metrics

Metric name Example value Descriptionxi3sage 5Min How long since we last got data from the carxi3spollermode 0 OBD-II polling mode as explained abovexi3vbpocvavg 40646V Main battery pack - average open-circuit voltagexi3vbpocvmax 4067V Main battery pack - highest open-circuit voltagexi3vbpocvmin 4063V Main battery pack - lowest open-circuit voltagexi3vbrangebc 245km Available range per trip computer (based on current driving mode and style)xi3vbrangecomfort 217km Available range if you use Comfort modexi3vbrangeecopro 245km Available range if you use EcoPro modexi3vbrangeecoproplus 247km Available range if you use EcoPro+ modexi3vbsocactual 85 Actual physical state-of-charge of the main battery packxi3vbsocactualhighlimit 937 Highest physical charge level permitted (shown as 100 SOC)xi3vbsocactuallowlimit 105 Minimum physical charge level permitted (shown as 0 SOC)xi3vcchargecablecapacity 0A Maximum power capacity of connected charge cable per the charging interfacexi3vcchargeledstate 0 Colour of the ldquoring lightrdquo on the charging interfacexi3vcchargeplugstatus Not connected Charging cable connectedxi3vccurrentdc 0A Power flowing on the DC side of the AC chargerxi3vccurrentdclimit 0100003A Limitxi3vccurrentdcmaxlimit 16A Maximum limitxi3vccurrentphase1 0A Power being drawn on AC phase 1xi3vccurrentphase2 0A Power being drawn on AC phase 2xi3vccurrentphase3 0A Power being drawn on AC phase 3xi3vcdcchargevoltage 0V Voltage seen on the DC charger inputxi3vcdccontactorstatus open DC contactor state (closed implies we are DC charging)xi3vcdccontrolsignals 0 DC charger control signals (always see 0)xi3vcdcinprogress no DC charging in progressxi3vcdcplugconnected no Is DC charger plug connected (doesnrsquot seem to work)xi3vcderatingreasons 0 Reasons why charging rate is deratedxi3vcerror 0 Charging error codesxi3vcfailsafetriggers 0 Failsafe trigger reasonsxi3vcinterruptionreasons 0 Charging interruption reasonsxi3vcpilotsignal 0A Charge rate pilot signal being received from EVSExi3vcreadytocharge no Are we ready to chargexi3vctempgatedriver 40degC Charger gatedrive mosfet temperaturexi3vcvoltagedc 84V Charger output DC voltage being seen (for AC charging not DC)xi3vcvoltagedclimit 420V Maximum permitted DC voltge

Continued on next page

44 Custom metrics 115

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxi3vcvoltagephase1 0V Voltage seen on AC charger input phase 1xi3vcvoltagephase2 0V Voltage seen on AC charger input phase 2xi3vcvoltagephase3 0V Voltage seen on AC charger input phase 3xi3vdchargeportdc no Is the charger port DC cover open (doesnrsquot seem to work)xi3veautorecirc no Ventilation is in ldquoauto-recirculaterdquo modexi3veobdtraffic no Are we seeing OBD-II frames from the carxi3vptripconsumption 127Whkm Average consumption for the current or most recent tripxi3vpwheel1_speed 0kmh Wheel 1 speedxi3vpwheel2_speed 0kmh Wheel 2 speedxi3vpwheel3_speed 0kmh Wheel 3 speedxi3vpwheel4_speed 0kmh Wheel 4 speedxi3vpwheel_speed 0kmh Average wheel speed

45 To be researched

Can we startstop charging

Can we pre-heat

Can we lockunlock the car

Can we disable the OBD-II alarm

Still looking for the trip regen kWh

Can we get the voltage state of each individual cells rather than just the battery min max average

116 Chapter 4 BMW i3 i3s

CHAPTER 5

DBC Based Vehicles

Vehicle Type DBC

The DBC based vehicle reads a specified DBC file describing CAN bus messages and produces vehicle metrics fromthat It is under development experimental and not generally available

51 Support Overview

Function Support StatusHardware This is vehicle specific The DBC vehicle module can be configured to use any or all of

the 3 CAN busesVehicle Cable Vehicle specificGSM Antenna Standard GSM antennaGPS Antenna Vehicle specific Standard OVMS GPS supportedSOC Display Yes if DBC maps itRange Display Yes if DBC maps itGPS Location Yes if DBC maps it otherwise OVMS GPSSpeed Display Yes if DBC maps itTemperature Display Yes if DBC maps itBMS v+t Display Not currently supportedTPMS Display Yes if DBC maps itCharge Status Display Yes if DBC maps itCharge InterruptionAlerts

Yes if DBC maps it

Charge Control Not supported by DBC format maybe by extensionCabin Pre-heatcoolControl

Not supported by DBC format maybe by extension

LockUnlock Vehicle Not supported by DBC format maybe by extensionValet Mode Control Not supported by DBC format maybe by extensionOthers None

117

Open Vehicles

52 Contents

521 DBC Introduction

DBC is a CAN data description file format introduced by Vector Informatik GmbH DBC files are text files so can becreated and edited using a simple text editor like the one built into the OVMS web UI

DBC files can be used to support vehicles that donrsquot have a dedicated native adaption yet This is done using thegeneric DBC vehicle type which can use DBC files to translate CAN data into metrics

This section tries to show you how to create and use a DBC specification on the OVMS Of course yoursquoll need to knowhow to decode your vehiclersquos CAN frames first You can use the OVMS RE (reverse engineering) toolkit to identifywhich messages are on the bus and which changes correlate to actions and status on the car

Therersquos also a very good general introduction to DBC from CSS Electronics including an explanatory video httpswwwcsselectronicscomscreenpagecan-dbc-file-database-introlanguageen

DBC files only specify the passive (reading) part they donrsquot provide a means to define transmissions If you need tosend frames to request certain information you can still use the OVMS DBC engine to decode the results (instead ofdoing the decoding in C++ code) So a DBC file can be used as a base for a real vehicle module To request OBD2data during development you can use the re obdii commands

Basic Example

Warning The DBC support is usable but considered to be an alpha release The way it works may change in thefuture

This example is taken from the Twizy which sends some primary BMS status data at CAN ID 0x155 (341) Note theTwizy module actually does not use DBC this is just an example how you would decode this message if using DBC

Message example 05 96 E7 54 6D 58 00 6F

bull Byte 0 charge current limit [A] scaled by 5 no offset 05rarr 25A

bull Bytes 1+2 momentary battery current [A] big endian lower 12 bits scaled by -025 offset +500 _6 E7 rarr5825A

bull Bytes 4+5 SOC [] big endian scaled by 00025 no offset 6D 58rarr 6998

These can be translated to metrics directly

bull Charge current limit vcclimit

bull Momentary battery current vbcurrent

bull Battery SOC vbsoc

Create DBC File

Copy amp paste the following into a new editor window

VERSION DBC Example 10

BS_ 500000 00

BO_ 341 BMS_1 8 Vector__XXX

(continues on next page)

118 Chapter 5 DBC Based Vehicles

Open Vehicles

(continued from previous page)

SG_ v_c_climit 7|80+ (50) [0|35] A Vector__XXXSG_ v_b_current 11|120+ (-025500) [-500|1000] A Vector__XXXSG_ v_b_soc 39|160+ (000250) [0|100] Vector__XXX

What does this mean

bull BS_ defines the bus speed (500 kbit in this example) and bit timings (unused)

bull BO_ defines the data object a CAN frame of length 8 with ID 341 (0x155) (ldquoBMS_1rdquo is just an arbitrary name)

bull SG_ lines define the signals (values) embedded in the object (see below)

bull Vector__XXX is just a placeholder for any senderreceiver (currently unused by the OVMS)

Signals are defined by their

bull Name (= metric name with replaced by _)

bull Start position (bit position) and bit length (7|8)

bull Endianness 0 = big endian (most significant byte first) 1 = little endian (least significant byte first) (Note theDBC format documentation is wrong on this)

bull Signedness + = unsigned - = signed

bull Scaling and offset (-025500) =gt real value = raw value -025 + 500

bull Minimummaximum [-500|1000] = valid real values are in the range -500 to 1000

bull Unit eg A (ignoredirrelevant defined by the metric)

The metric to set can be given as the name of the signal You may use the metric name directly on the OVMS but toconform to the DBC standard replace the dots by _

Bit positions are counted from byte 0 upwards by their significance regardless of the endianness The first messagebyte has bits 0 7 with bit 7 being the most significant bit of the byte The second byte has bits 8 15 with bit 15being the MSB and so on

[ 7 6 5 4 3 2 1 0 ] [ 15 14 13 12 11 10 9 8 ] [ 23 22 21 20 `----- Byte 0 ----acute `------- Byte 1 --------acute `----- Byte 2

For big endian values signal start bit positions are given for the most significant bit For little endian values the startposition is that of the least significant bit

Note On endianness ldquobig endianrdquo means a byte sequence of 0x12 0x34 decodes into 0x1234 (most significantbyte first) ldquolittle endianrdquo means the same byte sequence decodes into 0x3412 (least significant byte first) ldquoBigendianrdquo is the natural way of writing numbers ie with their most significant digit coming first ldquolittle endianrdquo isvice versa Endianness only applies to values of multiple bytes single byte values are always written naturally ldquobigendianrdquo

Use DBC File

Save the DBC example as storedbctwizy1dbc (the directory will be created by the editor)

Open the shell To see debug logs issue log level debug dbc-parser and log level debug v-dbc

Note the DBC parser currently isnrsquot graceful on errors a wrong DBC file may crash the module So you shouldonly enable automatic loading of DBC files on boot when yoursquore done developing and testing it

52 Contents 119

Open Vehicles

So letrsquos first try if the DBC engine can parse our file The dbc autoload command loads all DBC files from thestoredbc directory

OVMS dbc autoloadAuto-loading DBC filesD (238062) dbc-parser VERSION parsed as DBC Example 10D (238062) dbc-parser BU_ parsed 1 nodesD (238062) dbc-parser BO_ parsed message 341D (238072) dbc-parser SG_ parsed signal v_c_climitD (238072) dbc-parser SG_ parsed signal v_b_currentD (238082) dbc-parser SG_ parsed signal v_b_soc

Looks good dbc list can tell us some statistics

OVMS dbc listtwizy1 DBC Example 10 1 message(s) 3 signal(s) 56 coverage 1 lock(s)

The coverage tells us how much of our CAN data bits are covered by signal definitions

Now letrsquos load the file into the DBC vehicle

OVMS config set vehicle dbccan1 twizy1Parameter has been set

OVMS vehicle module NONEI (1459922) v-none Generic NONE vehicle module

OVMS vehicle module DBCI (249022) v-dbc Pure DBC vehicle moduleI (249022) v-dbc Registering can bus 1 as DBC twizy1

Nice Letrsquos simulate receiving our test frame and check the decoded metrics

OVMS can can1 rx standard 155 05 96 E7 54 6D 58 00 6FOVMS me li vbsocvbsoc 6998OVMS me li vbcurrentvbcurrent 5825AOVMS me li vcclimitvcclimit 25A

So the decoding apparently works

To configure DBC mode for autostart we now just need to set the DBC vehicle mode to be loaded on vehicle startupand to enable autoloading of the DBC files from storedbc You can do so either by using the user interface pageConfig rarr Autostart (check ldquoAutoload DBC filesrdquo and set the vehicle type to ldquoDBCrdquo) or from the shell by

OVMS config set auto dbc yesOVMS config set auto vehicletype DBC

Try a reboot to see if everything works

You can now add more objects and signals to your DBC file

Note During development of a DBC file yoursquoll need to reload the file frequently The DBC engine locks the currentlyused vehicle so yoursquoll need to unload the DBC vehicle (vehicle module NONE) then reload the DBC file (dbcautoload) then reactivate the DBC vehicle (vehicle module DBC)

120 Chapter 5 DBC Based Vehicles

CHAPTER 6

DEMO Vehicle

Vehicle Type DEMO

The demonstration vehicle can be used to verify module functionality but is mostly used for development purposesThe vehicle itself updates system metrics with simulated data It can respond to charge and other similar commands

61 Support Overview

Function Support StatusHardware Demonstration data only no vehicle connectionVehicle Cable None not required (other than power)GSM Antenna Standard GSM antennaGPS Antenna None not requiredSOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display YesBMS v+t Display Not currently supportedTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control YesCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle YesValet Mode Control YesOthers None

121

Open Vehicles

122 Chapter 6 DEMO Vehicle

CHAPTER 7

Fiat 500e

Vehicle Type FT5E

The Fiat 500e vehicle support will be documented here

71 Support Overview

Function Support StatusHardware tbaVehicle Cable tbaGSM Antenna tbaGPS Antenna tbaSOC Display tbaRange Display tbaGPS Location tbaSpeed Display tbaTemperature Display tbaBMS v+t Display tbaTPMS Display tbaCharge Status Display tbaCharge Interruption Alerts tbaCharge Control tbaCabin Pre-heatcool Control tbaLockUnlock Vehicle tbaValet Mode Control tbaOthers tba

123

Open Vehicles

124 Chapter 7 Fiat 500e

CHAPTER 8

Hyundai Ioniq vFL

Hyundai Ioniq Electric (28 kWh)

bull Vehicle Type HIONVFL

bull Log tag v-hyundaivfl

bull Namespace xhi

bull Maintainers Michael Balzer

bull Sponsors Henri Bachmann

bull Credits EVNotify

125

Open Vehicles

81 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display NoGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display PartialBMS v+t Display YesSOH Display YesTPMS Display NoCharge Status Display YesCharge Interruption Alerts YesCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

82 Custom Metrics

Metric name Example value Descriptionxhibsocbms 785 Internal BMS SOCxhicstate 128 Charge state flags

83 Debug Logs

To see all PID poll results in your log set log level verbose for component v-hyundaivfl

126 Chapter 8 Hyundai Ioniq vFL

CHAPTER 9

Jaguar IPace

Vehicle Type IPace

Support for Jaguar IPace is provided by this module (c) 2021 by Didier Ernotte

91 Support Overview

Function Support StatusHardwareVehicle CableGSM AntennaGPS AntennaSOC Display YesRange DisplayGPS Location (not yet)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display (not yet)Charge Interruption AlertsCharge ControlCabin Pre-heatcool ControlLockUnlock Vehicle NoValet Mode Control NoOthers

127

Open Vehicles

92 Custom Metrics

xji_v_bat_capacity_soh_min xji_v_bat_capacity_soh_max xji_v_bat_power_soh xji_v_bat_power_soh_minxji_v_bat_power_soh_max xji_v_bat_max_regen

128 Chapter 9 Jaguar IPace

CHAPTER 10

Kia e-Niro

Vehicle Type KN

The Kia e-Niro vehicle support will be documented here

101 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable 9658635 Kia OBD-II to DB9 Data Cable for OVMSGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display Yes (based on consumption of past 20 trips longer than 1km)GPS Location YesSpeed Display Not currently supportedTemperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control Not currently supportedCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle YesValet Mode Control Not currently supportedOthers ODO Not currently supported

129

Open Vehicles

102 OBD-II cable

The Kia e-Niro have one CAN-bus available on the OBD-II port D-can You can use the standard OBD-II to DB9cable from Fasttech

In case you want to build your own cable herersquos the pinout

J1962-M DB9-F Signal4 3 Chassis Power GND6 7 CAN-0H (C-can High)14 2 CAN-0L (C-can Low)16 9 +12V Vehicle Power

A simple approach is to buy an OBDII (J1962-M) pigtail and solder the DB9-F connector end appropriately

103 Configuration

TODO Configuration is quite similar to the Kia Soul so please check that out Please use the Web based configuration

104 Estimated Range

Currently there is no known way to get the estimated range directly from the car so the estimated range is calculatedby looking at the consumption from the last 20 trips that are longer than 1 km

105 12V battery drain

OVMS will eventually drain the 12V battery but steps have been taken to minimize the drain However if you aregoing to leave the car for a fews days it is recommended to unplug OVMS OVMS will send an alert if 12V dropsunder 12V alert threshold See 12V Calibration section

130 Chapter 10 Kia e-Niro

CHAPTER 11

Kia Soul EV

Vehicle Type KS

The Kia Soul EV vehicle support will be documented here

111 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable 9658635 Kia OBD-II to DB9 Data Cable for OVMSGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display Temperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control Not currently supportedCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle YesValet Mode Control Not currently supportedOthers

131

Open Vehicles

112 OBD-II cable

The Kia Soul EV have two different CAN-busses available on the OBD-II port C-can and M-can

C-can is the main can-bus and M-can is the multimedia bus The latter one is not necessary for OVMS but somemetrics are fetched from the M-bus and these metrics will be empty if you donrsquot have the proper cable The standardOBD-II to DB9 cable from Fasttech supports only C-can so make sure you buy the Kia Soul specific one

In case you want to build your own cable herersquos the pinout

J1962-M DB9-F Signal1 5 CAN-1H (M-can High)4 3 Chassis Power GND6 7 CAN-0H (C-can High)9 4 CAN-1L (M-can Low)14 2 CAN-0L (C-can Low)16 9 +12V Vehicle Power

A simple approach is to buy an OBDII (J1962-M) pigtail and solder the DB9-F connector end appropriately

113 Configuration

There are a few Kia Soul EV specific settings that you have to consider in order to get the most out of OVMS Theseare battery size real life ideal range remote command pincode and charge port remote control

114 Battery size

Up until the 2018 version of Kia Soul all models had a 27kWh battery The 2018-version have a 30kWh batteryOVMS is by default set up with 27000Wh but you can change this configuration to fit your car using this commandin the OVMS-shell

config set xks cap_act_kwh 27000

NB Even though it says cap_act_kwh the number must be in Wh

115 Real life ideal range

Even though the Kia Soul EV is equipped with a pretty good and conservative GOM most experienced drivers knowhow far the car can go on a charge This is what we call the ideal range You can set the ideal range in kilometersexperienced at 20 degrees celsius by using this command

config set xks maxrange 160

This setting is set to 160 km by default and matches the author driving a 2015 Kia Soul Classic in 20 degrees insouthern Norway Your mileage may vary so please set it accordingly

The ideal range as shown in the OVMS APP are then derived from this number multiplied by the state of charge andadjusted using a combination of the outside temperature and the battery temperature

132 Chapter 11 Kia Soul EV

Open Vehicles

116 Open charge port using key fob

By default OVMS listens for the the third button on the key fob and opens the charge port if Pressed If you donrsquotwant this behaviour you can disable it by using this command

config set xks remote_charge_port 0

117 Security pin code for remote commands

Remote commands like lock and unlock doors among others require a pin code This pin code can be set using theweb configuration or using this command

config set password pin 1234

Please set this pin as soon as possible

118 Soul specific metrics

NB Not all metrics are correct or tested properly This is a work in progress

There are a lot of extra metrics from the Kia Soul Herersquos the current ones

Metric Descriptionxksbcellvoltmax The highest cell voltagexksbcellvoltmaxno The cell number with the highest voltagexksbcellvoltmin The lowest cell voltagexksbcellvoltminno The cell number with the lowest voltagexksbcelldetmax The highest registered cell deterioration in percentxksbcelldetmaxno The cell with the highest registered deteriorationxksbcelldetmin The lowest registered cell deterioration in percentxksbcelldetminno The cell with the lowest registered deteriorationxksbmintemp The lowest temperature in the batteryxksbmaxtemp The highest temperature in the batteryxksbinlettemp The air temperature at the air inlet to the batteryxksbheat1temp The temperature of the battery heater 1xksbheat2temp The temperature of the battery heater 2xksbbmssoc The internal state of charge from BMSxkscpower Charge power in kWxkscspeed The charge speed in kilometer per hourxksldcoutvolt The voltage out of the low voltage DC converterxksldcinvolt The voltage into the low voltage DC converterxksldcoutamps The power drawn from the low voltage DC converterxksldctemp The temperature of the LDCxksobcpilotduty The duty cycle of the pilot signalxkselowbeam Low beam onoffxksehighbeam High beam onoffxkseinsidetemp Actual cabin temperaturexkseclimatetemp Climate temperature settingxkseclimatedriveronly Climate is set to driver onlyxkseclimateresirc Climate is set to recirculate

Continued on next page

116 Open charge port using key fob 133

Open Vehicles

Table 1 ndash continued from previous pageMetric Descriptionxkseclimateauto Climate is set to autoxkseclimateac Air condition onoffxkseclimatefanspeed Climate fan speedxkseclimatemode Climate modexksepreheattimer1enabled Preheat timer 1 enableddisabledxksepreheattimer2enabled Preheat timer 2 enableddisabledxksepreheating Preheating onoffxkseposdisttodest Distance to destination (nav unit)xkseposarrivalhour Arrival time hour part (nav unit)xkseposarrivalminute Arrival time minute part(nav unit)xkseposstreet Current street Or Next streetxksvseatbeltdriver Seat belt sensorxksvseatbeltpassenger Seat belt sensorxksvseatbeltbackright Seat belt sensorxksvseatbeltbackleft Seat belt sensorxksvtractioncontrol Traction control onoffxksvcruisecontrolenabled Cruise control enableddisabledxksvemergencylights Emergency lights enableddisabledxksvsteeringmode Steering mode Sport comfort normalxksvpowerusage Power usage of the carxksvtripconsumptionkWh100km Battery consumption for current tripxksvtripconsumptionkmkWh Battery consumption for current trip

Note that some metrics are polled at different rates than others and some metrics are not available when car is off Thismeans that after a restart of the OVMS some metrics will be missing until the car is turned on and maybe driven forfew minutes

Climate and navigation-metrics are fetched from navigation unit and needs the Kia Soul compatible OBDII-cable

119 Soul specific shell commands

There are a few shell commands made for the Kia Soul Some are read only others can enable functions and some areused to write directly to a ECU and must therefore be used with caution

1191 Read only commands

xks trip

Returns info about the last trip from you put the car in drive (D or B) and til you parked the car

xks tpms

Shows the tire pressures

xks aux

Prints out the voltage level of the auxiliary battery

xks vin

134 Chapter 11 Kia Soul EV

Open Vehicles

Prints out some more information taken from the cars VIN-number Not complete

1192 Active Commands

xks trunk ltpin codegt

Opens up the trunk

xks chargeport ltpin codegt

Opens up the charge port

xks ParkBreakService ltonoffgt

Not yet working

xks IGN1 ltonoffgtltpingt

Turn on or off IGN1-relay Can be used to wake up part of the car

xks IGN2 ltonoffgtltpingt

Turn on or off IGN2-relay Can be used to wake up part of the car

xks ACC ltonoffgtltpingt

Turn on or off ACC-relay Can be used to wake up part of the car

xks START ltonoffgtltpingt

Turn on or off START-relay Can be used to wake up part of the car

xks headlightdelay ltonoffgt

Turn onoff the ldquofollow me homerdquo head light delay function

xks onetouchturnsignal lt0=Off 1=3 blinks 2=5 blinks 3=7 blinksgt

Configure one touch turn signal settings

xks autodoorunlock lt1=Off 2=On vehicle off 3=On shift to P 4=On driver doorunlockgt

Configure auto door unlock settings

xks autodoorlock lt0=Off 1=On speed 2=On shiftgt

Configure auto door unlock settings

119 Soul specific shell commands 135

Open Vehicles

1193 ECU-write commands

These commands are for the extra playful people Use with caution

xks sjb ltb1gtltb2gtltb3gt

Send command to smart junction box

xks bcm ltb1gtltb2gtltb3gt

Send command to body control module

1110 12V battery drain

OVMS will eventually drain the 12V battery but steps have been taken to minimize the drain However if you aregoing to leave the car for a fews days it is recommended to unplug OVMS

136 Chapter 11 Kia Soul EV

CHAPTER 12

Maxus eDeliver3

Vehicle Type MED3

The Maxus eDeliver3 will be documented here

121 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display NoTemperature Display Yes (External Temp and Battery)BMS v+t Display NoTPMS Display NoCharge Status Display NoCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

137

Open Vehicles

138 Chapter 12 Maxus eDeliver3

CHAPTER 13

Mercedes-Benz B250E W242

Vehicle Type SE

The Mercedes-Benz B-Klasse Electric Drive will be documented here

131 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display NoRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display NoBMS v+t Display NoTPMS Display NoCharge Status Display NoCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

139

Open Vehicles

132 Contents

1321 Standard Metrics

Metric name Notesms_v_mot_rpmms_v_env_throttle Resolution of 04 ms_v_pos_speed Resolution of 01 kmhms_v_pos_odometerResolution of 01 kmms_v_bat_12v_voltageResolution of 01 Vms_v_bat_power Car reports percents so the kW is just calculated by multiplying by 132 kW Negative side is

saturated to -50 kW This is just guess workms_v_bat_range_estms_v_bat_consumptionInstantious consumption Whkmms_v_tpms__pms_v_env_cabinsetpointThere are two figures left and right Using just one for now

1322 Custom Metrics

Metric name Example value Descriptionxmbvdisplaytripreset 27332km Dashbord Trip value since Resetxmbvdisplaytripstart 175km Dashbord Trip value since Start (today)xmbvdisplayconsumptionstart 259 kWh Dashbord Trip consumption since Start (today)xmbvdisplayaccel 89 Eco score on acceleration over last 6 hoursxmbvdisplayconst 18 Eco score on constant driving over last 6 hoursxmbvdisplaycoast 100 Eco score on coasting over last 6 hoursxmbvdisplayecoscore 69 Eco score shown on dashboard over last 6 hoursxmbvfl_speed 3783 kmh Front Left wheel speedxmbvfr_speed 3785 kmh Front Right wheel speedxmbvrl_speed 3780 kmh Rear Left wheel speedxmbvrr_speed 3782 kmh Rear Right wheel speed

140 Chapter 13 Mercedes-Benz B250E W242

CHAPTER 14

MG EV

Vehicle Types MG EV (UKEU) amp MG EV (TH)

These vehicle types support the MG ZS EV (2019-) MG5 is not yet supported in this build

141 Variants

MG ZS EVs sold in different countries seem to possess different behaviours This is why we have developed 2 differentvehicle types to support the different requirements

1411 Known Countries

Coun-try

Zombiemode

Requires GWM authenti-cation

Poll BCM causesalarm

Suggested vehicle type touse

UKEU Y N Y UKEUThai-land

N Y N TH

Aus-tralia

N N N TH

Zombie mode is when the gateway module (GWM) enters the locked state and no PIDs can be accessed This happens for UKEU cars when

1 Charger is plugged in without power car is locked and goes to sleep

2 Charger is then powered on and car starts charging

GWM authentication is required for Thai cars as GWM will be locked and no PIDs can be accessed (simiarly toZombie mode but this happens all the time rather than just during the above scenario) Note GWM authenticationdoes not work as a mitigation for UKEUrsquos Zombie mode

When the BCM is polled UKEU carsrsquo alarm (horn) can go off so this is disabled in the UKEU code

141

Open Vehicles

1412 Other Countries

For cars from other countries to decide which vehicle type you should use start off by trying the MG EV (TH) typefirst because Zombie mode mitigation has its side effects (see module notes below) and polling the BCM allows theOVMS to get more data from the car

You can follow these steps to see which variant may be suitable for your car

1 Select MG EV (TH) and use the car as you would normally Keep an eye on shell for log prints to see ifany problems occur

2 If the alarm goes off sometimes (like when doors are locked using remote) try switch to MG EV (UKEU)

3 If you do not get any alarm try put the car into Zombie mode

4 If OVMS is unable to get data (like no charging details appear on the app) try switch to MG EV (UKEU)

142 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 2019-Vehicle Cable Right hand OBDII cable (RHD) Left hand OBDII cable (LHD)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (or any compatible antenna)SOC Display YesRange Display Yes (BMS calculated and WLTP range from SoC)Cabin Pre-heatcool Control NoGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control NoLockUnlock Vehicle NoValet Mode Control NoOthers Daytime Running Light Control

143 Shell Commands

softver Get software version of ECUsdrl [on | off] Turn onoff daytime running lightsdrln [on | off] Turn onoff daytime running lights without doing BCM authentication first (for de-

bugging purposes)auth [all | gwm |bcm]

Authenticate with specified ECU lsquoauth allrsquo will authenticate GWM then BCM

142 Chapter 14 MG EV

Open Vehicles

144 Module notes

The code for each vehicle type has these behaviours

Vehicle type Zombie mode mitigation GWM authentication Poll BCMUKEU Y N NTH N Y Y

The MG EV module now monitors (and automatically calibrates) the 12V status and will automatically start pollingthe car for data when the 12V battery voltage is equal to or greater than 129V When it is below 129V it willautomatically stop polling (after a 50s delay) to not drain the 12V battery

Poll states

0 Lis-tenOnly

the OVMS module is quiet and stops sending polls

1 Charg-ing

the OVMS module sends charging specific queries

2 Driving the OVMS module sends driving specific queries3 Backup the OVMS module cannot get data from the car when it is charging so just retries SoC queries

This is unused in TH code

1441 UKEU spec

The car is accessible over the OBD port when it is running (ignition on) and for around 40 seconds after it is turnedoff or the car is ldquotweakedrdquo (lock button pushed etc)

The OBD port may be kept awake by using the ldquotester presentrdquo message to the gateway ECU This keeps a lot ofsystems awake and draws roughly 5A on the 12V bus so itrsquos not a good idea to do

The Gateway (GW GWM) is the keeper of all the data of the car and will enter a locked state when it is woken by thecar starting charging and the car is locked This we have called ldquoZombie Moderdquo and we have developed an overridefor this

This override however causes a few strange things to happen

bull If Zombie mode override is active the car will not unlock the charge cable To fix this dusrupt the chargeand wait 50s for OVMS to go back to sleep and the cable should release (or unplug OVMS)

bull Zombie mode override resets the ldquoAccumulated Total Triprdquo on the Cluster

bull Zombie mode override sets the gearshift LEDs switch on

145 Development notes

Developers welcome Follow the developerrsquos guide on httpswwwopenvehiclescomdevelopers to get started Joinour slack group (see below) to discuss the nerdy details

146 Community channels

Forum httpswwwmgevscom

144 Module notes 143

Open Vehicles

Slack httpsmgevhackersslackcom

144 Chapter 14 MG EV

CHAPTER 15

Mitsubishi Trio

Vehicle Type MI

This should be used to support the Mitsubishi i-Miev (Citroen C-Zero Peugeot iOn) vehicles

151 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display NoBMS v+t Display YesTPMS Display Not currently supportedCharge Status Display YesCharge Interruption Alerts YesCharge Control NoCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle Not currently supportedValet Mode Control Not currently supportedOthers

145

Open Vehicles

152 Trio specific metrics

NB Not all metrics are correct or tested properly This is a work in progress

Metric Descriptionxmibpowermin The battery minimum power usagexmibpowermax The battery maximum power usagexmielowbeam Low beam light statusxmiehighbeam High beam light statusxmiefrontfog Front fog light statusxmierearfog Rear fog light statusxmierightblinker Right blinker statusxmieleftblinker Left blinker statusxmiewarninglight Warning light statusxmickwhdc Charge energy on DC side in kWhxmickwhac Charge energy on AC side in kWhxmicefficiency Charge efficiency (DCAC)xmicpowerac Charge power on AC side in kWxmicpowerdc Charge power on DC side in kWxmictime Charge time (hmmss)xmicsocstart Charge start soc in xmicsocstop Charge stop soc in xmieheatingamp Heating energy usage in Axmieheatingwatt Heating energy usage in Wxmieheatingtempreturn Heater return water temperaturexmieheatingtempflow Heater flow water temperaturexmieacamp AC energy usage in Axmieacwatt AC energy usage in Wxmietrippark Trip start odometer in kmxmietripparkenergyused Energy used in kWhxmietripparkenergyrecuperated Recuperated energy in kWhxmietripparkheatingkwh Heater energy usage on trip in kWhxmietripparkackwh AC energy usage on trip in kWhxmietripparksocstart Trip start socxmietripparksocstop Trip stop socxmietripcharge Trip start odometer in km since chargexmietripchargeenergyused Energy used in kWh since chargexmietripchargeenergyrecuperated Recupe energy in kWh since chargexmietripchargeheatingkwh Heating usage in kWh since chargexmietripchargeackwh AC energy usage in kWh since chargexmietripchargesocstart Trip start soc since chargexmietripchargesocstop Trip stop soc since charge

Note that some metrics are polled at different rates than others and some metrics are not available when car is off Thismeans that after a restart of the OVMS some metrics will be missing until the car is turned on and maybe driven forfew minutes

146 Chapter 15 Mitsubishi Trio

Open Vehicles

153 Custom Commands

1531 Read only commands

xmi trip

Returns info about the last trip from you start the car with key

xmi tripc

Returns info about the trip since last charge

xmi aux

Prints out the voltage level of the auxiliary battery

xmi vin

Prints out some more information taken from the cars VIN-number

154 Trio Regen Brake Light Hack

1541 Parts required

bull 1x DA26 Sub-D 26HD Plug amp housing Note housings for Sub-D 15 fit for 26HD eg Assmann-WSW-A-HDS-26-LL-Z Encitech-DPPK15-BK-K-D-SUB-Gehaeuse

bull 1x 12V Universal Car Relay + Socket eg Song-Chuan-896H-1CH-C1-12V-DC-Kfz-Relais GoodSky-Relaissockel-1-St-GRL-CS3770

bull 1x 1 Channel 12V Relay Module With Optocoupler Isolation 12V 1 channel relay module with OptocouplerIsolation

Car wire-tap connectors car crimp connectors 05 mm2 wires zipties shrink-on tube tools

Note if you already use the switched 12V output of the OVMS for something different you can use one of the freeEGPIO outputs That requires additionally routing an EGPIO line to the DA26 connector at the expansion slot (egusing a jumper) and using a relay module (2b relay shield) with separate power input instead of the standard carrelay

I use 2b (relay shield) variant Be aware the MAX71317 outputs are open drain so you need a pull up resistor to eg+33 According to the data sheet the current should stay below 6 mA

Inside OVMS Box Connect JP1 Pin10 (GEP7) to Pin12 (EGPIO_8) with jumper

In DA26 connector

pin 24(+33) ----- [ 680 Ohms ] ---+--- [ Relay board IN ]|

pin 21 (EGPIO_8)pin 9 ----- [Relay board DC+]pin 8 ----- [Relay board DC-][Relay board COM] ----- Brake pedal switch one side[Relay board NO] ----- Brake pedal switch other side

153 Custom Commands 147

Open Vehicles

1542 Configuration

See OVMS web user interface menu Trio rarr Brake Light

Set the port as necessary and the checkbox to enable the brakelight

For monitoring and fine tuning use the bdquoregenmonldquo web plugin httpsgithubcomopenvehiclesOpen-Vehicle-Monitoring-System-3blobmastervehicleOVMSV3componentsovms_webserverdevregenmonhtm

148 Chapter 15 Mitsubishi Trio

Open Vehicles

154 Trio Regen Brake Light Hack 149

Open Vehicles

150 Chapter 15 Mitsubishi Trio

CHAPTER 16

Nissan Leafe-NV200

Vehicle Type NL

This vehicle type supports the Nissan Leaf (24kWh amp 30kWh) and Nissan e-NV200 (24kWh amp 40kWh)

161 Support Overview

1611 Hardware

Item Support StatusModule Any OVMS v3 (or later) module Vehicle support 2011-2017 (24kWh amp 30kWh LEAF 24kWh amp

40KWh e-Nv200 amp custom battery eg Muxsan)VehicleCable

1779000 Nissan Leaf OBD-II to DB9 Data Cable for OVMS

GSM An-tenna

1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)

GPS An-tenna

1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)

1612 Controls

Function Support StatusCharge Control Start and stop chargeCabin Pre-heatcool Control Yes1 (see info below)LockUnlock Vehicle Yes3 (see info below)Valet Mode Control Not currently supported

1 OVMS currently supports 2011-2017 Nissan LEAF and all models of Nissan e-NV2003 LockUnlock will work if CAR can bus is awake this can be activated by turning on AC

151

Open Vehicles

1613 Additional Features

Fea-ture

Description

BMSCellMon-itor

Allows to monitor individual battery cells in a configurable chart Can be accessed from web user interfaceaccessible over WiFi

ChargetoLimit

Allows to automatically stop the charge when target SOC (state of charge) andor range is reached Allparameters can be controlled trough metrics or web user interface Meanwhile Range and SOC can becontrolled from the app as well by adjusting fields 10 (SOC) and 11 (range) in feature section accessibletrough app settings

1614 Metrics

Item Support StatusSOC Yes (by default based on GIDS)4

Range Yes (by default based on GIDS)GPS Location Yes (from modem module GPS)Speed Yes (from vehicle speed PID)Cabin Temperature Yes (from vehicle temperature PIDs)Ambient Temperature Yes (from vehicle temperature PIDs)SetPoint Temperature Yes (from vehicle hvac PIDs)2

HVAC Fan Speed Yes (from vehicle hvac PIDs)2

HVAC HeatingCooling Status Yes (from vehicle hvac PIDs)2

HVAC On Status Yes (from vehicle hvac PIDs)2

HVAC Temperature Setpoint Yes (from vehicle hvac PIDs)2

HVAC Ventilation Mode Yes (from vehicle hvac PIDs)2

BMS v+t YesTPMS Yes (If hardware available)Charge Status YesCharge Interruption Alerts Yes

162 Remote Climate Control

1621 2014-2022 e-NV200 models

OVMS remote climate support will lsquojust workrsquo on e-Nv200 VisiaAcenta which donrsquot have a Nissan satnav headunitFor Tekna models which are fitted with a Nissan satnav headunit follow the instructions below for a 2013-2016 LEAFto unplug the TCU

IMPORTANT for remote climate to work on the e-NV200 the model year in OVMS should be set to 2015 regardlessof the the actual model year of the vehicle CAN writing also needs to be enabled

The model year can be set in the web interface or via the command

4 ZE0 (2011-2013) vehicles are required to choose SoC display from ldquorelative to fixed valuerdquo ldquodashboard displayrdquo SoC method does not workwith these vehicles

2 Some HVAC Status Items have been only verified with 2013-2016 MY cars and will only work if the year is set in configuraiton Also HVACneeds to be in ON position before powering down the vehicle for the metrics to work during pre-heat

152 Chapter 16 Nissan Leafe-NV200

Open Vehicles

config set xnl modelyear 2015

1622 2011-2012 LEAF models (ZE0)

Gen1 LEAFs (ZE0 2011-2012) require a hardware modification to enable remote climate control if the vehicle is notplugged in and charging If you are ok with this you donrsquot need to do anything further

If you want to to enable remote climate control once the charge has finished or if the vehicle is not plugged in youneed to do the following hardware modification A cable wired to the pin 11 of Nissan TCU (Telematics Control Unit)needs to receive +12V so that ldquoEV System Activation Request Signalrdquo can be generated which in turn allows to triggerclimate control independently This can be achieved by wiring the pin 18 (Ext 12V) from the OVMS DA26 socket tothe cable going to pin 11 of the TCU by using a standard single conductor wire The connection on the OVMS DA26side can be made by using dedicated DA26 connector or a standard round 1mm jumper cable Herersquos how to wire itup

Meanwhile on the TCU side the cable can be soldered or spliced in to by using a connector of your choice Whendone the original TCU can be left unplugged See this page for additional pictures

162 Remote Climate Control 153

Open Vehicles

If you have a ldquosmartrdquo EVSE (or one connected to a ldquosmartrdquo outlet you can sometimes wake up the EV system byturning it off then back on This obviously only helps if your vehicle is plugged in but may be useful for some users

1623 2013-2016 LEAF models (AZE0-01)

To use OVMS to activate remote climate the Nissan TCU (Telematics Control Unit) module must be unplugged iffitted eg satnav headunit (only on Acenta and Tekna models) The TCU is located behind the glovebox on LHD carsor on the right hand side of the drivers foot well on RHD cars The large white plug on the rear of the TCU should beunplugged push down tab in the middle and pull to unplug see video for RHD cars and this page for LHD cars

Note Unplugging the TCU will disable Nissan EV connect CARWINGS features eg Nissan mobile app All othercar functions will not be effected eg GPS maps radio Bluetooth microphone all work just the same as beforeOVMS can be used to more than substitute the loss of Nissan Connect features The TCU can be plugged back in atany point in the future if required

OVMS remote climate support will lsquojust workrsquo on LEAF Visia models and VisiaAcenta e-NV200 since these modelsdo not have a TCU fitted In the US these base models are called S

Note If you prefer not to unplug the Nissan TCU all OVMS functions appart from remote climate will function justfine alongside the Nissan TCU

1624 2016-2017 LEAF models (AZE0-2)

Remote climate control will only work when plugged in and actively charging on LEAF 2016-2017 models Thisis because in 2016 Nissan moved the TCU from the EV CAN bus to the CAR CAN bus

Set the model year as follows and if necessary configure 30 kWh model

config set xnl modelyear 2016

or

154 Chapter 16 Nissan Leafe-NV200

Open Vehicles

config set xnl modelyear 2017

Note in latest OVMS fimware version model year and battery size can be set via the web config interface

1625 2018+ models (ZE1)

2018+ 4062kWh LEAF is not yet supported Please get in touch if your interested in helping to add support Relevant2018 CANbus messages have already been decoded and documented see MyNissanLEAF thread

1626 Specific battery configs

For models with a 30 kWhr battery pack set the capacity manually with

config set xnl maxGids 356 config set xnl newCarAh 79

For models with a 40 kWhr battery pack set the capacity manually with

config set xnl maxGids 502 config set xnl newCarAh 115

For models with a 62 kWhr battery pack set the capacity manually with

config set xnl maxGids 775 config set xnl newCarAh 176

Note In latest OVMS firmware version model year and battery size can be set via the web config interface This iseasier and also the preferred method

Note 2 OVMS fully supports battery upgraded LEAFs just set the capacity according to what battery is currentlyinstalled

163 Range Calculation

The OVMS uses two configuration options to calculate remaining range whPerGid (default 80Whgid) and km-PerKWh (default 71kmkWh) The range calculation is based on the remaining gids reported by the LBC and atthe moment does not hold 5 in reserve like LeafSpy Feedback on this calculation is welcomed

164 Resources

bull Nissan LEAF support added by Tom Parker see his wiki for lots of documentation and resources Some info isoutdated eg climate control now turns off automatically

bull Nissan LEAF features are being added by Jaunius Kapkan see his github profile to track the progress

bull MyNissanLEAF thread for Nissan CANbus decoding discussion

bull Database files (DBC) for ZE0 and AZE0 Leaf can be found here Github LEAF Canbus database files

Assistance is appreciated as I havenrsquot had time to try to override the TCU using the OVMS or find an alternativesolution to prevent the TCU overriding the messages while still allowing the hands free microphone to work

163 Range Calculation 155

Open Vehicles

156 Chapter 16 Nissan Leafe-NV200

CHAPTER 17

OBDII Vehicles

Vehicle Type O2

Support for generic OBDII is provided by this module

157

Open Vehicles

171 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support Not widely tested but should be all that

support OBDII standard PIDs over CAN busVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display Yes (based on fuel level PID)Range Display NoGPS Location Yes (from modem module GPS)Speed Display Yes (from vehicle speed PID)Temperature Dis-play

Yes (from vehicle temperature PIDs)

BMS v+t Display NoTPMS Display NoCharge Status Dis-play

No

Charge Interrup-tion Alerts

No

Charge Control NoCabin Pre-heatcool Control

No

LockUnlockVehicle

No

Valet Mode Con-trol

No

Others VIN and RPMs should be available

158 Chapter 17 OBDII Vehicles

CHAPTER 18

Renault Twizy

Vehicle Type RT

159

Open Vehicles

181 Support Overview

Function Support StatusHardware No specific requirements (except for regen brake light

control see below)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right

or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any

compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or

any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display YesBMS v+t Display YesTPMS Display NoCharge Status Display YesCharge Interruption Alerts YesCharge Control Current limit stop SOCrange limitCabin Pre-heatcool Control NoLockUnlock Vehicle Mapped to dynamic speed lockValet Mode Control Mapped to odometer based speed lockOthers

bull Battery amp motor power amp energy monitoringbull Battery health amp capacitybull SEVCON monitoring amp tuning (Note tuning

only SC firmware lt= 07120002 ~072016)bull Kickdownbull Auto power adjustbull Regen brake lightbull Extended trip amp GPS logging

Note regarding the Twizy V3 works very similar to V2 All telemetry data tables and tuning profiles are fullycompatible and the commands are very similar Therefore the basic descriptions and background info from the V2manual are valid for V3 as well

bull V2 FAQ (english)

bull V2 FAQ (german)

bull V2 documents directory

bull V2 user manual (PDF)

182 Hints on V3 commands vs V2

bull V3 commands need to be in lower case

bull When accessing via USB terminal first issue enable (login)

bull V3 commands are similar to V2 commands just structured slightly different

160 Chapter 18 Renault Twizy

Open Vehicles

bull Try help and xrt Twizy commands are subcommands of xrt

bull TAB only works via USB SSH Shortcuts can be used generally eg mo t instead of module tasks

bull A usage info is shown if a command syntax is wrong or incomplete

183 Contents

1831 Configuration

The Twizy configuration is stored in the OVMS config parameter (section) xrt To list the current values issue

config list xrt

For reference the following table includes the equivalent OVMS V2 feature or parameter number amp bit value whereapplicable You may use the parameter amp feature editors on the App (values are mapped) the commands have beenmerged into the config command in V3

183 Contents 161

Open Vehicles

Config instancename

Examplevalue

V2FP

Description

autopower yes F158 Bool SEVCON automatic power level adjustment (Default yes)autoreset yes F152 Bool SEVCON reset on error (Default yes)aux_charger_port 0 ndash EGPIO port to control auxiliary charger (Default 0 = disabled)aux_fan_port 0 ndash EGPIO port to control auxiliary charger fan (Default 0 = disabled)canwrite yes F151 Bool CAN write enabled (Default no)cap_act_prc 822288 F13 Battery actual capacity level [] (Default 1000)cap_nom_ah 108 ndash Battery nominal capacity [Ah] (Default 1080)chargelevel 0 F7 Charge power level [1-7] (Default 0=unlimited)chargemode 0 F6 Charge mode 0=notify 1=stop at sufficient SOCrange (Default 0)console no F1516 -unused- (reserved for possible V3 SimpleConsole presence)dtc_autoreset no ndash Reset DTC statistics on every drivecharge start (Default no)gpslogint 5 (F8) Seconds between RT-GPS-Log entries while driving (Default 0 =

disabled)kd_compzero 120 F2 Kickdown pedal compensation (Default 120)kd_threshold 35 F1 Kickdown threshold (Default 35)kickdown yes F154 Bool SEVCON automatic kickdown (Default yes)lock_on 6 ndash Speed limit [kph] to engage lock mode at (Default undefined = off)maxrange 55 F12 Maximum ideal range at 20 degC [km] (Default 80)motor_rpm_rated 2050 ndash Powermap V3 control rated speed [RPM] (Default 0 = V2)mo-tor_trq_breakdown

210375 ndash Powermap V3 control breakdown torque [Nm] (Default 0 = V2)

profileNN XaZwt5ehZQ (P16-21)

Tuning profile NN [NN=01 99] base64 code

profileNNlabel PWR ndash button labelprofileNNtitle Power ndash titleprofile_buttons 0123 ndash Tuning drivemode button configurationprofile_cfgmode 2 ndash Tuning profile last loaded in config (pre-op) modeprofile_user 2 P15 Tuning profile last loaded in user (op) modesuffrange 0 F11 Sufficient range [km] (Default 0=disabled)suffsoc 80 F10 Sufficient SOC [] (Default 0=disabled)type ndash ndash Twizy custom SEVCONGearbox type [SC80GB45SC45GB80]

(Default - = auto detect)valet_on 123456 ndash Odometer limit [km] to engage valet mode at (Default undefined =

off)

1832 Custom Metrics

Metric name Example value Descriptioncocan1nd1emcycode SEVCON emergency codecocan1nd1emcytype SEVCON emergendy typecocan1nd1state Operational SEVCON state (preopop)xrtbusocmax 7052 Current tripcharge pack SOC maxxrtbusocmin 508 Current tripcharge pack SOC minxrtbutempmax 20degC Current tripcharge pack temp maxxrtbutempmin 181429degC Current tripcharge pack temp minxrtbuvoltmax 55V Current tripcharge pack volt maxxrtbuvoltmin 502V Current tripcharge pack volt min

Continued on next page

162 Chapter 18 Renault Twizy

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxrtbmsbalancing 248101314 Custom BMS cell balancing statusxrtbmserror 0 Custom BMS error statusxrtbmsstate1 4 Custom BMS main statexrtbmsstate2 1 Custom BMS auxiliary statexrtbmstemp 52degC Custom BMS internal temperaturexrtbmstype 1 Custom BMS type (0=VirtualBMS 1=eDriver BMS 7=Standard)xrtcfgapplied yes Tuning working set has been applied to SEVCONxrtcfgbase 2 Tuning base profile (preop mode params)xrtcfgprofile 144110111182 Tuning profile paramsxrtcfgtype Twizy80 Tuning vehicle typexrtcfgunsaved yes Tuning working set has unsaved changesxrtcfguser 2 Tuning userlive profile (op mode params)xrtcfgws 0 Tuning profile last loaded into working setxrticuract 0A SC monitor motor current levelxrtifrqoutput 0 SC monitor motor output frequencyxrtifrqslip 0 SC monitor motor slip frequencyxrtipwract 0kW SC monitor motor power levelxrtitrqact 0 SC monitor motor torque levelxrtitrqdemand 0 SC monitor motor torque demandxrtitrqlimit 0 SC monitor motor torque limitxrtivltact 0V SC monitor output voltage level (motor)xrtivltbat 0 SC monitor input voltage level (battery)xrtivltcap 0A SC monitor capacitor voltage levelxrtivltmod 0 SC monitor motor modulation factorxrtmversion 124 Sep 17 2019 OVMS Twizy component versionxrtpstatsaccdist 06267km Power stats accelerating distancexrtpstatsaccrecd 130133e-05kWh Power stats accelerating energy recoveredxrtpstatsaccspdavg 27kmhs Power stats accelerating speed averagexrtpstatsaccused 017692kWh Power stats accelerating energy usedxrtpstatscstdist 05331km Power stats coasting distancexrtpstatscstrecd 423289e-05kWh Power stats coasting energy recoveredxrtpstatscstspdavg 2618kmh Power stats coasting speed averagexrtpstatscstused 009703kWh Power stats coasting energy usedxrtpstatsdecdist 05436km Power stats decelerating distancexrtpstatsdecrecd 00140886kWh Power stats decelerating energy recoveredxrtpstatsdecspdavg 26kmhs Power stats decelerating speed averagexrtpstatsdecused 00379027kWh Power stats decelerating energy usedxrtpstatsldndist 02km Power stats downwards distancexrtpstatsldnhsum 3m Power stats downwards height sumxrtpstatsldnrecd 000300565kWh Power stats downwards energy recoveredxrtpstatsldnused 00356104kWh Power stats downwards energy usedxrtpstatslupdist 131km Power stats upwards distancexrtpstatsluphsum 66m Power stats upwards height sumxrtpstatsluprecd 0010866kWh Power stats upwards energy recoveredxrtpstatslupused 0263831kWh Power stats upwards energy usedxrtsbpwrdrv SC monitor virtual dyno drive power levelsxrtsbpwrrec SC monitor virtual dyno recup power levelsxrtsmtrqdrv SC monitor virtual dyno drive torque levelsxrtsmtrqrec SC monitor virtual dyno recup torque levels

Continued on next page

183 Contents 163

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxrtvbalert12v no Display service indicator 12V alertxrtvbalertbatt no Display service indicator Battery alertxrtvbalerttemp no Display service indicator Temperature alertxrtvbstatus 0 Internal BMS status (CAN frame 628)xrtvcstatus 0 Internal Charger status (CAN frame 627)xrtvistatus 0 Internal SEVCON status (CAN frame 629)xrtvelockedspeed 0 Speed limit [kph] set for Twizy lock modexrtvevaletodo 0 Odometer limit [km] set for Twizy valet mode

1833 Events

The Renault Twizy module emits these specific events additionally to the general OVMS events

Event Data Purposevehiclechargesubstatescheduledstop Charge stopped by user request (command)vehiclectrlcfgmode SEVCON in configuration mode (preop)vehiclectrlloggedin SEVCON session establishedvehiclectrlrunmode SEVCON in normal mode (op)vehicledrivemodechanged SEVCON tuning profile changedvehicledtcpresent ltdtc_descrgt OBD2 DTC (diagnostic trouble code) presentvehicledtcstored ltdtc_descrgt OBD2 DTC storedvehiclefaultcode ltcodegt SEVCON fault code receivedvehiclekickdownengaged Kickdown detected drive power changedvehiclekickdownreleased Kickdown mode end normal power restoredvehiclekickdownreleasing Kickdown mode about to end

1834 Custom Commands

Note This is currently just a brief overview to feed the search engine See each commandrsquos usage info and whereapplicable corresponding V2 manual entries on details

bull V3 commands need to be in lower case

bull When accessing via USB terminal first issue enable (login)

bull V3 commands are similar to V2 commands just structured slightly different

bull Try help and xrt Twizy commands are subcommands of xrt

bull TAB only works via USB SSH Shortcuts can be used generally eg mo t instead of module tasks

bull A usage info is shown if a command syntax is wrong or incomplete

OVMS xrt batt Battery monitorca Charge attributescfg SEVCON tuningdtc Show DTC report clear DTCmon SEVCON monitoringobd OBD2 toolspower Powerenergy info

164 Chapter 18 Renault Twizy

Open Vehicles

Battery Monitor

OVMS xrt batt data-cell Output cell recorddata-pack Output pack recordreset Reset alerts amp watchesstatus Status reporttdev Show temperature deviationstemp Show temperaturesvdev Show voltage deviationsvolt Show voltages

Note Also see standard BMS commands (bms )

Charge Attributes

OVMS xrt ca Usage xrt ca [R] | [ltrangegt] [ltsocgt] [Llt0-7gt] [S|N|H]

Note Also see standard charge control commands (charge )

SEVCON Tuning

OVMS xrt cfg brakelight Tune brakelight trigger levelsclearlogs Clear SEVCON diag logsdrive Tune drive power levelget Get tuning profile as base64 stringinfo Show tuning profileload Load stored tuning profileop Leave configuration mode (go operational)power Tune torque power amp current levelspre Enter configuration mode (pre-operational)querylogs Send SEVCON diag logs to serverramplimits Tune max pedal reactionramps Tune pedal reactionread Read registerrecup Tune recuperation power levelsreset Reset tuning profilesave Save current tuning profileset Set tuning profile from base64 stringshowlogs Display SEVCON diag logssmooth Tune pedal smoothingspeed Tune max amp warn speedtsmap Tune torquespeed mapswrite Read amp write registerwriteonly Write register

183 Contents 165

Open Vehicles

Show DTC Report Clear DTC

OVMS xrt dtc clear Clear stored DTC in carreset Reset OVMS DTC statisticsshow Show DTC report

SEVCON Monitoring

OVMS xrt mon reset Reset monitoringstart Start monitoringstop Stop monitoring

OBD2 Tools

OVMS xrt obd request Send OBD2 request output responseOVMS xrt obd request bms Send OBD2 request to BMSbroadcast Send OBD2 request as broadcastcharger Send OBD2 request to charger (BCB)cluster Send OBD2 request to cluster (display)device Send OBD2 request to a device

PowerEnergy Info

OVMS xrt power report Trip efficiency reportstats Generate RT-PWR-Stats entrytotals Power totals

1835 Notifications

The Renault Twizy module sends the custom or customized notifications described here additionally to the systemnotifications

See Notifications for general info on notifications

166 Chapter 18 Renault Twizy

Open Vehicles

Type Subtype Purpose Contentalert batterystatus Battery packcell alert status report (alerts amp watches)alert bmsstatus Battery management system alert (for custom BMS only)info chargestatussufficient Sufficient charge reached (SOCrange as configured)alert valetmodeodolimit Odometer limit reached speed reduction engagedalert vehicledtc OBD2 DTC (diagnostic trouble code) alertdata xrtbatterylog Battery packcell monitoring logdata xrtgpslog Extended GPS logdata xrtobdclusterdtc OBD2 DTC log for cluster (displayUCH)data xrtpowerdyno SEVCON live monitoring (virtual dyno) datadata xrtpowerlog Power statisticsinfo xrtpowertotals Current usage cycle power totalsdata xrttriplog Trip history loginfo xrttripreport Trip energy usage reportalert xrtsevconfault SEVCON fault condition detecteddata xrtsevconlog SEVCON faults amp events logsinfo xrtsevconprofilereset A tuning RESET has been performedinfo xrtsevconprofileswitch Tuning profile switch result

Trip history log

The trip history log can be used as a source for long term statistics on your trips and typical trip power usages as wellas your battery performance in different environmental conditions and degradation over time

Entries are created at the end of a trip and on each change in the charge state so you can also see where chargesstopped or how long they took and how high the temperatures got

bull Notification subtype xrttriplog

bull History record type RT-PWR-Log

bull Format CSV

bull Maximum archive time 365 days

bull Fieldscolumns

ndash odometer_km

ndash latitude

ndash longitude

ndash altitude

ndash chargestate

ndash parktime_min

ndash soc

ndash soc_min

ndash soc_max

ndash power_used_wh

ndash power_recd_wh

ndash power_distance

183 Contents 167

Open Vehicles

ndash range_estim_km

ndash range_ideal_km

ndash batt_volt

ndash batt_volt_min

ndash batt_volt_max

ndash batt_temp

ndash batt_temp_min

ndash batt_temp_max

ndash motor_temp

ndash pem_temp

ndash trip_length_km

ndash trip_soc_usage

ndash trip_avg_speed_kph

ndash trip_avg_accel_kps

ndash trip_avg_decel_kps

ndash charge_used_ah

ndash charge_recd_ah

ndash batt_capacity_prc

ndash chg_temp

Extended GPS log

The extended GPS log contains additional details about power and current levels the BMS power limits and theautomatic power level adjustments done by the OVMS You can use this to create detailed trip power charts and toverify your auto power adjust settings

The log frequency is once per minute while parkingcharging and controlled by config xrt gpslogint (web UITwizy rarr Features) while driving Logging only occurs if logged metrics have changed

bull Notification subtype xrtgpslog

bull History record type RT-GPS-Log

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash odometer_mi_10th

ndash latitude

ndash longitude

ndash altitude

ndash direction

ndash speed

168 Chapter 18 Renault Twizy

Open Vehicles

ndash gps_fix

ndash gps_stale_cnt

ndash gsm_signal

ndash current_power_w

ndash power_used_wh

ndash power_recd_wh

ndash power_distance

ndash min_power_w

ndash max_power_w

ndash car_status

ndash max_drive_pwr_w

ndash max_recup_pwr_w

ndash autodrive_level

ndash autorecup_level

ndash min_current_a

ndash max_current_a

Battery packcell monitoring log

The extended GPS log contains additional details about power and current levels the BMS power limits and theautomatic power level adjustments done by the OVMS You can use this to create detailed trip power charts and toverify your auto power adjust settings

The standard log frequency is once per minute logging only occurs if logged metrics have changed Additionalrecords are created on battery alert events Note an entry consists of a pack level record (RT-BAT-P) and up to 16(for LiFePO4 batteries) cell entries (RT-BAT-C)

bull Notification subtype xrtbatterylog

bull History record type RT-BAT-P (pack status)

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash packnr

ndash volt_alertstatus

ndash temp_alertstatus

ndash soc

ndash soc_min

ndash soc_max

ndash volt_act

ndash volt_min

183 Contents 169

Open Vehicles

ndash volt_max

ndash temp_act

ndash temp_min

ndash temp_max

ndash cell_volt_stddev_max

ndash cmod_temp_stddev_max

ndash max_drive_pwr

ndash max_recup_pwr

ndash bms_state1

ndash bms_state2

ndash bms_error

ndash bms_temp

bull Notification subtype xrtbatterylog

bull History record type RT-BAT-C (cell status)

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash cellnr

ndash volt_alertstatus

ndash temp_alertstatus

ndash volt_act

ndash volt_min

ndash volt_max

ndash volt_maxdev

ndash temp_act

ndash temp_min

ndash temp_max

ndash temp_maxdev

ndash balancing

ndash been_balancing

ndash balancetime

Power statistics

The power statistics are the base for the trip reports and can be used to analyze trip sections regarding speed andaltitude changes and their respective effects on power usage The log is also written when charging that data can beused to log changes in the charge current for example triggered externally by some solar charge controller

Log frequency is once per minute logging only occurs if metrics have changed

170 Chapter 18 Renault Twizy

Open Vehicles

bull Notification subtype xrtpowerlog

bull History record type RT-PWR-Stats

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash speed_const_dist

ndash speed_const_use

ndash speed_const_rec

ndash speed_const_cnt

ndash speed_const_sum

ndash speed_accel_dist

ndash speed_accel_use

ndash speed_accel_rec

ndash speed_accel_cnt

ndash speed_accel_sum

ndash speed_decel_dist

ndash speed_decel_use

ndash speed_decel_rec

ndash speed_decel_cnt

ndash speed_decel_sum

ndash level_up_dist

ndash level_up_hsum

ndash level_up_use

ndash level_up_rec

ndash level_down_dist

ndash level_down_hsum

ndash level_down_use

ndash level_down_rec

ndash charge_used

ndash charge_recd

OBD2 cluster DTC log

This server table stores DTC occurrences for one week This is mostly raw data and the DTCs are internal Renaultvalues that have not yet been decoded

See httpswwwtwizy-forumdeovms86362-liste-df-codes-dtc

bull Notification subtype xrtobdclusterdtc

183 Contents 171

Open Vehicles

bull History record type RT-OBD-ClusterDTC

bull Format CSV

bull Maximum archive time 7 days

bull Fieldscolumns

ndash EntryNr

ndash EcuName

ndash NumDTC

ndash Revision

ndash FailPresentCnt

ndash G1

ndash G2

ndash ServKey

ndash Customer

ndash Memorize

ndash Bt

ndash Ef

ndash Dc

ndash DNS

ndash Odometer

ndash Speed

ndash SOC

ndash BattV

ndash TimeCounter

ndash IgnitionCycle

SEVCON faults amp events

These logs are created on request only eg by the SEVCON logs tool in the Android App or by using the xrt cfgquerylogs command The command queries the SEVCON (inverter) alerts faults events and statistics (SEVCONneeds to be online) The results are then transmitted to the server using the following records

bull Notification subtype xrtsevconlog

bull History record type RT-ENG-LogKeyTime

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash KeyHour

ndash KeyMinSec

bull Notification subtype xrtsevconlog

172 Chapter 18 Renault Twizy

Open Vehicles

bull History record type RT-ENG-LogAlerts

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash Code

ndash Description

ndash TimeHour

ndash TimeMinSec

ndash Data1

ndash Data2

ndash Data3

bull Notification subtype xrtsevconlog

bull History record type RT-ENG-LogSystem

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash Code

ndash Description

ndash TimeHour

ndash TimeMinSec

ndash Data1

ndash Data2

ndash Data3

bull Notification subtype xrtsevconlog

bull History record type RT-ENG-LogCounts

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash Code

ndash Description

ndash LastTimeHour

ndash LastTimeMinSec

ndash FirstTimeHour

ndash FirstTimeMinSec

ndash Count

bull Notification subtype xrtsevconlog

183 Contents 173

Open Vehicles

bull History record type RT-ENG-LogMinMax

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash BatteryVoltageMin

ndash BatteryVoltageMax

ndash CapacitorVoltageMin

ndash CapacitorVoltageMax

ndash MotorCurrentMin

ndash MotorCurrentMax

ndash MotorSpeedMin

ndash MotorSpeedMax

ndash DeviceTempMin

ndash DeviceTempMax

SEVCON live monitoring

These records store the measurement results of the virtual dyno included in the SEVCON live monitor (Twizy rarrSEVCON Monitor) The virtual dyno records a torquepower profile from the actual car performance during drivingThe profile has four data sets

bull Maximum battery drive power over speed (metric xrtsbpwrdrv unit kW)

bull Maximum battery recuperation power over speed (metric xrtsbpwrrec unit kW)

bull Maximum motor drive torque over speed (metric xrtsmtrqdrv unit Nm)

bull Maximum motor recuperation torque over speed (metric xrtsmtrqrec unit Nm)

Power is measured at the battery so you can derive the efficiency Speed is truncated to integer the value arrays takeup to 120 entries (0 119 kph)

These datasets are visualized by the web UI using a chart and transmitted to the server on any monitoring ldquostoprdquo orldquoresetrdquo command in the following records

bull Notification subtype xrtpowerdyno

bull History record types RT-ENG-BatPwrDrv RT-ENG-BatPwrRec RT-ENG-MotTrqDrvRT-ENG-MotTrqRec

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns max 120 values for speed levels beginning at 0 kph

1836 Twizy Regen Brake Light Hack

174 Chapter 18 Renault Twizy

Open Vehicles

Why

The Twizy recuperation levels are very low by default regenerative braking is so weak it doesnlsquot need to trigger thebrake light ndash so a regen braking indication has been omitted by Renault The Twizy can be tuned to one pedal drivingthough with high neutral braking power

The SEVCON normally can generate a regen braking signal itself That signal can be configured using the xrt cfgbrakelight tuning command Pin 11 on the SEVCON main connector will go to GND on activation The problemis that pin is not connected on the Twizy using it needs modification of the connector To my knowledge this hasnlsquotbeen done successfully up to now so we donlsquot even know if the Twizy SEVCON firmware includes that functionality

How does it work

The OVMS generates a secondary regen braking signal itself That signal is used to control a relay to provide powerto the brake light independant of the brake pedal

Integration is simple and does not require to change the existing connections

The Twizy UCHdisplay recognizes the regen brake light activation despite the foot brake being pushed and turns onthe SERV indicator Depending on your preferences you may see this as a problem or as an indicator for the regenbraking

Switching the 65A line does not avoid the SERV indicator (tested) Most probably the brake light is monitored by thecurrent flowing at the fuse box so the SERV indicator cannot be avoided without changing that system

Parts required

1 1x DA26 Sub-D 26HD Plug amp housing

bull Note housings for Sub-D 15 fit for 26HD

bull eg Assmann-WSW-A-HDS-26-LL-Z

183 Contents 175

Open Vehicles

bull Encitech-DPPK15-BK-K-D-SUB-Gehaeuse

2 1x 12V Universal Car Relay + Socket

bull eg Song-Chuan-896H-1CH-C1-12V-DC-Kfz-Relais

bull GoodSky-Relaissockel-1-St-GRL-CS3770

3 Car wire-tap connectors car crimp connectors 05 mm2 wires zipties shrink-on tube tools

Note if you already use the switched 12V output of the OVMS for something different you can use one of the freeEGPIO outputs That requires additionally routing an EGPIO line to the DA26 connector at the expansion slot (egusing a jumper) and using a relay module (relay shield) with separate power input instead of the standard car relay

Build

1 Solder ~ 40 cm two-core wire to the DA26 plug pins 8 (GND) and 18 (+12V switched) use shrink-on tubes toprotect the terminals mount the housing

2 Crimp 63mm sockets to the other ends of the wire isolate using shrink-on tube crimp 63mm plugs to the relaycoil (pins 85 + 86) isolate using shrink-on tube

176 Chapter 18 Renault Twizy

Open Vehicles

3 Extend the relay switch terminals by ~ 30 cm wires crimp on plugs for the tap connectors

4 Unmount the Twizy glovebox locate the red wire on the right above the parking brake

183 Contents 177

Open Vehicles

5 Crimp a tap connector onto the red wire and connect it to the relay (pin 30)

178 Chapter 18 Renault Twizy

Open Vehicles

6 Connect switched +12V likewise to pin 87 of the relay

bull +12V may be taken from the radio or 12V aux socket to simplify things

bull the dedicated brake light supply is fuse no 23 which is very hard to reach without dismounting the whole fuseholder

7 Place the relay in the free area on the upper left of the fuse holder (not below the door dampener that may crushthe relay) secure the relay using a ziptie

8 Pull the OVMS DIAG cable through the glovebox bottom hole and connect it to the relay inputs (pins 8586polarity doesnlsquot matter)

9 Do a test plug in the OVMS (Note the relay switches on during the first OVMS boot) switch on the Twizyissue commands

bull egpio output 1 1 should activate the brakelight

bull egpio output 1 0 should deactivate the brakelight

bull Note if youlsquore using another EGPIO port use the according port number (3-9) instead

10 Mount the glovebox and youlsquore done

Configuration

See OVMS web user interface menu Twizy rarr Brake Light

183 Contents 179

Open Vehicles

Set the port as necessary and the checkbox to enable the brakelight

For monitoring and fine tuning use the regenmon web plugin

httpsgithubcomopenvehiclesOpen-Vehicle-Monitoring-System-3blobmastervehicleOVMSV3componentsovms_webserverdevregenmonhtm

1837 Auxiliary Charge Fan

The builtin Elips 2000W chargerrsquos officially specified temperature operation range is -20+50 degC This is exceededby the Twizy easily even on moderate summer days The charger temperature can easily rise above 60 degC and this is

180 Chapter 18 Renault Twizy

Open Vehicles

possibly the main reason why Twizy chargers eventually die It also leads to the Twizy reducing the maximum chargepower available resulting in charges taking much longer than usual

A counter measure can be to add an additional fan to cool the charger and switch that fan on as necessary (seebelow) The fan can be controlled using one of the OVMS EGPIO output ports (see EGPIO) The easiest way is to usethe switched 12V supply available at the DA26 expansion plug without additional hardware The 12V port can delivera nominal output of 25W or 18A and up to 40W or 29A short term so can be used to power many auxiliary fansdirectly

To enable the auxiliary fan simply configure the EGPIO to be used in config parameter xrt aux_fan_port Forexample to use the switched 12V port = EGPIO port 1 do

OVMS config set xrt aux_fan_port 1

Set the port to 0 to disable the feature

Mode of operation

bull The OVMS continously monitors the charger temperature It turns on the fan when the charger temperaturerises above 45 degC (gt= 46 degC) and off when the temperature drops below 45 degC (lt= 44 degC)

bull After end of charge (Twizy system switched off) the OVMS does not get temperature updates so it keeps thefan running for another 5 minutes

The fan control works during charging and driving as during driving the charger also has to supply +12V by thebuiltin DCDC converter (heating up the charger) and a trip may start with an already hot charger

1838 Auxiliary Charger

The Elips 2000W (as the name says) does only charge with ~2 kW thus needing 3-35 hours to charge the originalTwizy battery Thatlsquos quite slow and gets worse when replacing the battery by a larger one

The Elips is running a special Renault firmware and also taking a crucial role in the Twizy system communication forexample to control the BMS So it cannot easily be replaced by a third party charger

But a third party charger can run in parallel to the Elips to boost the charge power This can be done best fromthe ldquorear endrdquo ie using the battery main connector as the power input (like the SEVCON does during regenerativebraking)

Some documented examples of additional chargers

bull httpswwwtwizy-forumdewerkstatt-twizy84935-twizy-schnelllader

bull httpswwwtwizy-forumdeprojekte-twizy83603-schnell-lader-extern

bull httpswwwtwizy-forumdetipps-und-tricks-twizy80814-twizy-schnellladen-die-wave-kann-kommen

The caveat to avoid damaging the battery additional charge power should not be supplied when the battery is nearlyfull So the additional charger needs to be switched off before the main charger finishes

The OVMS can automate switching the additional charger both on and off Any of the available EGPIO output ports(see EGPIO) can be used for this task If the charger has no digital power control input a convenient way is to use theswitched 12V supply available at the DA26 expansion plug without additional hardware The 12V port can deliver anominal output of 25W or 18A and up to 40W or 29A short term so can be used to power a standard automotiverelay directly

Configuration

Simply set the EGPIO to be used in config parameter xrt aux_charger_port For example to use the switched12V port = EGPIO port 1 do

183 Contents 181

Open Vehicles

OVMS config set xrt aux_charger_port 1

Set the port to 0 to disable the feature

Mode of operation

bull The port is switched ON when the Twizy charges is below 94 SOC is still within the CC phase (ie nottopping off balancing) and the charge current is not under user control

bull The port is switched OFF when the Twizy stops charging reaches 94 SOC or enters the topping off phase(whichever comes first) or when you set a custom charge current

Charge current control

If you set the charge current to level 7 (35 A) only the original charger will run but at full power You can set levels6 1 (30 5 A) to reduce the charge power only using the Elips charger Setting the current to level 0 (no chargethrottling) will allow maximum charge current from the Elips charger and additionally enable the second charger

182 Chapter 18 Renault Twizy

CHAPTER 19

Renault Zoe

Vehicle Type RZ

This vehicle type supports the Renault Zoe(PH1) and Kangoo(2011 - ~2019) The newer Zoe ph2 and Kangoo are notsupported yet

191 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display Yes (External Temp and Battery)BMS v+t Display YesTPMS Display Zoe Yes (pressure only)TPMS Display Kangoo NoCharge Status Display YesCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

After selecting the Renault ZoeKangoo vehicle module the corresponding settings have to be made in the web inter-face via the ldquoRenault ZoeKangoordquo menu under ldquoFeaturesrdquo

183

Open Vehicles

184 Chapter 19 Renault Zoe

CHAPTER 20

Smart ED Gen3

Vehicle Type SE

The Smart ED will be documented here

201 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display NoCharge Status Display YesCharge Interruption Alerts YesCharge Control Current limitCabin Pre-heatcool Control When charging and CAN-Bus ActiveLockUnlock Vehicle NoValet Mode Control NoOthers

185

Open Vehicles

202 Contents

2021 Custom Metrics

Metric name Example value DescriptionxsemybmsHWrev 12380 BMS hardware-revision year week patchlevelxsemybmsSWrev 12351 BMS soft-revision year week patchlevelxsemybmsadccvoltsmax 4171 maximum cell voltages in mV add offset +1500xsemybmsadccvoltsmean 4165 average cell voltage in mV no offsetxsemybmsadccvoltsmin 4145 minimum cell voltages in mV add offset +1500xsemybmsadcvoltsoffset 103 calculated offset between RAW cell voltages and ADCref about 90mVxsemybmsamps 65483A battery current in ampere (x32) reported by by BMSxsemybmsamps2 204634A battery current in ampere read by live data on CAN or from BMSxsemybmsbattvin WME4513901K661441 VIN stored in BMSxsemybmsdcfault 0 Flag to show DC-isolation faultxsemybmshv total voltage of HV system in Vxsemybmshvcontactcyclesleft 281991 counter related to ONOFF cyles of the carxsemybmshvcontactcyclesmax 300000 static seems to be maxiumum of contactor cyclesxsemybmsisolation 10239 Isolation in DC path resistance in kOhmxsemybmspower 794186kW power as product of voltage and amps in kWxsevbccapacity 184911853618536 Cell capacity [As]xsevbccapacitydevmax 451901901 Cell maximum capacity deviation observed [As]xsevbccapacitymax 184911853618536 Cell maximum capacity [As]xsevbccapacitymin 184911853618536 Cell minimum capacity [As]xsevbenergyusedreset 1634kWh Energy used Reset (Dashbord)xsevbenergyusedstart 169kWh Energy used Start (Dashbord)xsevbhvactive no HV Batterie Statusxsevbpcapacityasaverage 18625 cell capacity statistics from BMS measurement cyclexsevbpcapacityasmaximum 19193 cell capacity statistics from BMS measurement cyclexsevbpcapacityasminimum 18843 cell capacity statistics from BMS measurement cyclexsevbpcapacityavg 184459 Cell capacity - pack average [As]xsevbpcapacitycombinedquality 0515328 some sort of estimation factor constantly updatedxsevbpcapacitymax 18670 Cell capacity - strongest cell in pack [As]xsevbpcapacitymaxcell 9 Cell capacity - number of strongest cell in packxsevbpcapacitymin 18229 Cell capacity - weakest cell in pack [As]xsevbpcapacitymincell 59 Cell capacity - number of weakest cell in packxsevbpcapacityquality 0742092 some sort of estimation factor after measurement cyclexsevbpcapacitystddev 908 Cell capacity - current standard deviation [As]xsevbpcapacitystddevmax 908 Cell capacity - maximum standard deviation observed [As]xsevbphvlowcurrent 0Sec counter time of no current reset eg with PLC heater or drivingxsevbphvofftime 0Sec HighVoltage contactor off time in secondsxsevbplastmeasdays 13 days elapsed since last successful measurementxsevbpocvtimer 2676Sec counter time in seconds to reach OCV statexsevbpvoltagemaxcell 1 Cell volatage - number of strongest cell in packxsevbpvoltagemincell 5 Cell volatage - number of weakest cell in packxsevbrealsoc 978 real state of chargexsevbusawake no CAN-Bus Statusxsevcactive no Charging Statusxsevdisplaytime 738Min Dashbord Timexsevdisplaytripreset 27332km Dashbord Trip value at Reset

Continued on next page

186 Chapter 20 Smart ED Gen3

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxsevdisplaytripstart 175km Dashbord Trip value at Startxsevnlg6ampscablecode 0A Onboard Charger Ampere Cablexsevnlg6ampschargingpoint 0A Onboard Charger Ampere xsevnlg6ampssetpoint 41A Onboard Charger Ampere setpointxsevnlg6dccurrent 0A Onboard Charger LV current Amperexsevnlg6dchv 0V Onboard Charger HV Voltagexsevnlg6dclv 135V Onboard Charger LV Voltagexsevnlg6mainamps 000A Onboard Charger main Phasen Amperexsevnlg6mainvolts 000V Onboard Charger main Phasen Voltagexsevnlg6pnhw 4519820621 Onboard Charger Hardware Serial Noxsevnlg6present no Onboard Charger OBL or NLG6 presentxsevnlg6tempcoolingplate 0degC Onboard Charger coolingplate Temperaturexsevnlg6tempreported 0degC Onboard Charger reported Temperaturexsevnlg6tempsocket 0degC Onboard Charger socket Temperaturexsevnlg6temps Onboard Charger Temperaturesxsevposodometerstart 41940km Odo at last Ignition on For Trip calc Valuexsevdisplayaccel 89 Eco score on acceleration over last 6 hoursxsevdisplayconst 18 Eco score on constant driving over last 6 hoursxsevdisplaycoast 100 Eco score on coasting over last 6 hoursxsevdisplayecoscore 69 Eco score shown on dashboard over last 6 hours

2022 Custom Commands

xse trip

show last Trip value

xse recu up

xse recu down

set Rekuperation up or down Works only if Rekuperation is enabled in car

xse charge

set charge and leave Time

Example

xse charge 7 15 off

set Time at 715 clock with pre climate off

xse charge 9 55 on

set Time at 955 clock with pre climate on

2023 BMS Diagnose Tool

xse rptdata get a Battery Status Report

xse bmsdiag get Battery Diagnose Report

Original Tool ED BMSdiag

description DE

description EN

202 Contents 187

Open Vehicles

188 Chapter 20 Smart ED Gen3

CHAPTER 21

Smart EDEQ Gen4 (453)

Vehicle Type SQ

The Smart EDEQ Gen4 will be documented here

211 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display Yes (External Temp and Battery)BMS v+t Display only Cell Volts atmTPMS Display NoCharge Status Display YesCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

189

Open Vehicles

190 Chapter 21 Smart EDEQ Gen4 (453)

CHAPTER 22

Tesla Model 3

Vehicle Type T3

At present support for the Tesla Model 3 in OVMS is experimental and under development This vehicle type shouldnot be used by anyone other than those actively involved in development of support for this vehicle

221 Support Overview

Function Support StatusHardware tbaVehicle Cable tbaGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna tbaSOC Display tbaRange Display tbaGPS Location tbaSpeed Display tbaTemperature Display tbaBMS v+t Display tbaTPMS Display tbaCharge Status Display tbaCharge Interruption Alerts tbaCharge Control tbaCabin Pre-heatcool Control tbaLockUnlock Vehicle tbaValet Mode Control tbaOthers tba

191

Open Vehicles

192 Chapter 22 Tesla Model 3

CHAPTER 23

Tesla Model S

Vehicle Type TS

At present support for the Tesla Model S in OVMS is experimental and under development This vehicle type shouldnot be used by anyone other than those actively involved in development of support for this vehicle

231 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support Not widely tested but should be

allVehicle Cable 9665972 OVMS Data Cable for Early TeslasGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna None not requiredSOC Display YesRange Display YesGPS Location Yes (from carrsquos built in GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display Not currently supportedCharge Status Display YesCharge Interruption Alerts YesCharge Control Not currently supportedCabin Pre-heatcool Con-trol

Not currently supported

LockUnlock Vehicle Not currently supportedValet Mode Control Not currently supportedOthers Adhesive velcro strips useful for vehicle attachment

193

Open Vehicles

232 TPMS Option

Reading and writing TPMS wheel sensor IDs fromto the Baolong TPMS ECU is supported by OVMS in Tesla ModelS cars using the Baolong system (vehicles produced up to around August 2014) You can easily tell if you have thisTesla Model S Baolong TPMS system as Tesla doesnrsquot support displaying tyre pressures in the instrument cluster Bycontrast the later Continental TPMS system does show the pressures in the instrument cluster

OVMS directly supports the Baolong TPMS in Tesla Model S cars without any extra hardware required You simplyneed the usual OVT1 cable

To read the current wheel sensor IDs from the Baolong TPMS ECU ensure that the car is ON (simplest is to wake thecar up and put in drive) and issue the lsquotpms readrsquo command in OVMS

Similarly to write wheel sensor IDs to the Baolong TPMS ECU ensure that the car is ON and issue the lsquotpms writersquocommand in OVMS

194 Chapter 23 Tesla Model S

CHAPTER 24

Tesla Roadster

Vehicle Type TR

The Tesla Roadster support in OVMS is perhaps the most mature in the project All versions (1x 2x and 3x) aresupported for both North American and other variants

241 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 1x 2x and 30 roadsters (all

markets)Vehicle Cable 9665972 OVMS Data Cable for Early TeslasGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna None not requiredSOC Display YesRange Display YesGPS Location Yes (from carrsquos built in GPS)Speed Display YesTemperature Display YesBMS v+t Display Not currently supportedTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control YesCabin Pre-heatcool Con-trol

Not currently supported

LockUnlock Vehicle YesValet Mode Control YesOthers Adhesive velcro strips useful for vehicle attachment

195

Open Vehicles

242 Module Installation in the vehicle

The OVMS module is connected to your Roadster via the CAN bus diagnostic port connector which is located in thepassenger footwell It is made of plastic that is wrapped in grey foam as shown in the photo Typically the connectoris wedged into the front wall near the center console so it wonrsquot rattle Pull the connector out and note the orientationof the pins especially the void above the +12V and Ground pins

The OVMS Data Cable for Tesla Roadster can then be plugged in connecting the car to the OVMS module Makesure to tighten the screws holding the module-side DB9 connector

At this point check the car Tap on the VDS in the centre console and make sure it turns on Insert the key turn on thecar and make sure everything works as expected If you see any problems at all with the car disconnect the OVMSmodule and contact Open Vehicles support for assistance

WarningIf when you plug the OVMS into the car you see any interference to or strange behaviour of car systemsimmediately unplug the module and contact Open Vehicles for assistance Never leave a module connected in suchcircumstances

The OVMS Module is best secured to the front wall of the passenger footwell using adhesive velcro tape With themodule connected to the car diagnostics port connector experiment with various placements until you find a suitablespot For the velcro attachment to work yoursquoll want to choose a spot on the front wall thatrsquos flat for the entire size ofthe module (hint avoid the big round black plastic plug)

Mounting is straightforward

1 Ensure that both velcro strips are fixed together

2 Remove the adhesive backing from one side fasten it to the back of the OVMS module

3 Using a clean dry cloth clean the area of the car passenger footwell wall to which you are going to attach themodule

4 Remove the adhesive backing from the side of the velcro strip facing the car and then firmly push the OVMSmodule into place - holding it still for a few seconds to allow the adhesive to work

5 You can then remove and reinstall the OVMS module as desired via the velcro

196 Chapter 24 Tesla Roadster

Open Vehicles

243 Antenna Installation

You will find the performance of this antenna fantastic - and much better than even your cellphone but proper place-ment is essential Since it has a very long cable you can place the antenna just about wherever you want but pleaseensure it is high-up on the car and away from any metal objects that might interfere with the signal

Possible areas include the bottom of the windscreenwindshield on the passenger side the top of the windscreen onthe passenger side (hidden by the sun visor) behind the passenger on the side pillar in the rear window or under thedashboard (for the brave and experienced at dismantling Tesla Roadster dashboards)

The antenna is connected to the port marked GSM on the OVMS v3 module The GPS port is not used on the TeslaRoadster (as your car already has GPS installed and we can read that positioning information off the CAN bus directly)

2431 Antenna beside rear passenger headrest

The antenna cable is long enough to reach back to the area around the left side seat head This approach is generallyeasiest The module is placed in the left seat footwell near the diagnostic port connector From there the antennacable is routed through the base of the waterfall under the door sill and up the side of the door frame

The door sill is held in place by velcro and is easily removed You may have to loosen the waterfall (held in place byfour screws around the fuse box area) The antenna cable can then be placed on top of the metal of the chassis sillbetween the velcro strips and routed up through the existing plastic trunking At this point the door sill can then beput back in place

2432 Antenna on windshieldwindscreen

To route the antenna cable up to the front windshieldwindscreen you will need to remove the fuse-box cover (onescrew that needs to be turned 90 degrees) then two screws from the box below the fuse box (these screws should becompletely removed in order to be able to remove the box and access the compartment beneath) You do not need toadjust anything in the fuse box - you only need the cover removed to make it easier to route the cable

Start with the cable at the windscreenwindshield and route it down the side of the left side door front pillar Theplastic corner can be pulled back slightly and you can push the cable through into the open bottom compartmentPull the cable through there so that the antenna is where you want it and there is no loose cable outside the box Theantenna itself can be mounted to the windscreenwindshield by first cleaning the area with a clean dry cloth removingthe adhesive backing tape then firmly pushing the antenna against the glass and waiting a few seconds for the adhesiveto stick

Now for the tricky bit You need to get the cable through to the passenger footwell but it is tight It is much easier toget a guide wire up into the fuse box compartment than to get the antenna cable down into the passenger footwell Sowe recommend you use a small (12 inches 30 cm or so) piece of stiff wire to use as a guide and push it up from thearea marked by the green arrow on the bottom right of the picture below Once the guide wire is in the fuse box pushit down into the lower compartment you opened and wrap it around the antenna cable You can then pull the guidewire back down into the passenger footwell bringing the antenna cable with it

The antenna cable can then be screwed in to the OVMS module You can then tidy up any loose cable and screw-backthe lower compartment box (two screws) and fuse box cover (one screw 90 degrees to lock)

244 Configuration Options

The Tesla Roadster specific configuration options are in configuration parameter xtr

243 Antenna Installation 197

Open Vehicles

Instance Default Descriptiondigitalspeedo no Set to yes to enable digital speedometer (2x cars only)digitalspeedoreps 3 Number of CAN bus repeat transmissionscooldowntimelimit 60 Number of minutes after which cooldown is stoppedcooldowntemplimit 31 Temperature (in Celcius) after which cooldown is stoppedprotectlock yes Refuse to lock vehicle when switched on

245 Tesla Roadster Notes

1 In general the OVMS module in a Tesla Roadster acts exactly like the little VDS screen We should be able todo anything that screen can do but no more Here are some notes

2 The lockunlock and valet functions rely on a PIN code This is the same PIN code you enter into the vehicleusing the VDS screen when activating valet mode If you donrsquot know the PIN code either try the default 1234or contact Tesla for assistance

3 While OVMS can lockunlock the doors of all Tesla Roadster models cars outside North America are fitted withan immobiliser and neither OVMS nor the VDS will disarmarm that The OVMS lockunlock functionality onlyapplies to the doors not the alarm in vehicles sold outside North America

4 OVMS v3 can calculate an overall battery health metric This metric is calculated using our own algorithm andis in no way approved by Tesla Battery health is dependent on many factors and hard to bring down to just onesimple number

5 The Tesla Roadster requires the ignition key to be on and manual switches turned to coolheat the cabin It isnot technically possible to do this remotely via OVMS

The digital speedometer function replaces the AMPS display in the dashboard instrument cluster with the vehiclespeed It is only supported on v2x cars (not v15) This is an experimental feature and works 99 of the time butsometimes the car wins and displays AMPS for a split second A better solution is to use the HUD functionality ofOVMS v3 and install an external Heads Up Display in the car

246 TPMS Option

Reading and writing TPMS wheel sensor IDs fromto the Baolong TPMS ECU is supported in v2x Tesla Roadstersusing the optional OVMS K-Line Expansion Board You will need a v32 module (or v31 module labelled on boardas July 2018 or later with K-line pin connected) and an OVT1 vehicle cable (clearly labelled with ldquoOVT1rdquo on thecable)

The optional OVMS K-line Expansion Board should be configured with SW1 set to position 2 (LDO 5v) and S1 into OFF position (away from the ON label)

To read the current wheel sensor IDs from the Baolong TPMS ECU ensure that the ignition switch is ON (so instru-ment panel lights are on) and issue the lsquotpms readrsquo command in OVMS

Similarly to write wheel sensor IDs to the Baolong TPMS ECU ensure that the ignition switch is ON (so instrumentpanel lights are on) and issue the lsquotpms writersquo command in OVMS

Note that this functionality will not work with v15 Tesla Roadsters (that use a different TPMS ECU to the v2x cars)

198 Chapter 24 Tesla Roadster

Open Vehicles

247 Thanks

There are so many people to thank for Tesla Roadster support in OVMS WPetefish for sourcing the car connectorFuzzylogic for the original hardware and software design and demonstration of it working Scott451 for figuring outmany of the Roadster CAN bus messages Tom Saxton for v15 Roadster testing Michael Thwaite for pictures ofantenna installation Bennett Leeds for wordsmithing the manual Mark Webb-Johnson for CAN bus hacking andwriting the vehicle module support Sonny Chen for beta testing and tuning and many others for showing that thiskind of thing can work in the real world

247 Thanks 199

Open Vehicles

200 Chapter 24 Tesla Roadster

CHAPTER 25

Toyota RAV4 EV

Vehicle Type TYR4

At present support for the 2012-2014 Toyota RAV4 EV in OVMS is experimental and under development Thisvehicle type can be used by early adopters as long as you understand the limitations The current release only showsinformation from the Tesla CAN bus not the Toyota CAN bus and is read-only

201

Open Vehicles

251 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support All 2012-2014 RAV4 EV are identical

and no other years are supportedVehicle Cable A custom cable is required to connect at the left rear of the vehicle Tesla and Toyota CAN

buses are available at the Gateway ECUGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA)SOC Display Yes (Tesla BMS value)Range Display Not currently supportedGPS Location YesSpeed Display YesTemperature Dis-play

Yes

BMS v+t Display YesTPMS Display Not currently supportedCharge Status Dis-play

Yes

Charge InterruptionAlerts

Yes

Charge Control Not currently supportedCabin Pre-heatcool Control

Not currently supported

LockUnlock Vehi-cle

Not currently supported

Valet Mode Control Not currently supportedOthers

The Tesla CAN bus already had decodes available so those were implemented already The primary focus goingforward will be decoding the Toyota CAN bus to replicate SafetyConnect connected features like Remote Climatebefore the 3G shutdown ends that manufacturer provided functionality

The file xr4monhtm should be installed as a Page type Web Plugin to display detailed information about the carrsquosstatus

202 Chapter 25 Toyota RAV4 EV

CHAPTER 26

Tracking Vehicles

Vehicle Type XX

The track vehicle will be documented here

261 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support Not widely tested but should be allVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left) or any cable

proving powerGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display NoRange Display NoGPS Location Yes (from modem module GPS)Speed Display Yes (from modem module GPS)Temperature Display NoBMS v+t Display NoTPMS Display NoCharge Status Display NoCharge InterruptionAlerts

No

Charge Control NoCabin Pre-heatcoolControl

No

LockUnlock Vehicle NoValet Mode Control NoOthers None

203

Open Vehicles

204 Chapter 26 Tracking Vehicles

CHAPTER 27

VW e-Up

Vehicle Type VWUP

This vehicle type supports the VW e-UP (2013- 2020-) Skoda Citigo E IV and the Seat MII electric (2020-) Con-nection can be made via the OBD2 port to the top left of the driving pedals andor the Comfort CAN bus eg belowthe passenger seat (T26 connector instead of the VW OCU there)

The main difference currently is that the OBD connection enables access to way more metrics (eg down to cellvoltages) while the Comfort CAN connection is necessary if write access is needed eg for remote climate controlThe Comfort CAN also provides data in more cases without turning on the car or charging as the bus wakes on manyevents (eg opening of doors) and can also be woken via OVMS

For the full experience making both connections is recommended

271 Using OBD2

Connection to OBD2 is done with the standard OVMS OBD2-cable just below the fuses left of the driving pedals

205

Open Vehicles

272 Using Comfort CAN

Connection to Comfort CAN can be done by removing the OCU below the passenger seat using a custom 26-pinadapter cable to the T26A plug (advantage the connections for the GSM amp GPS-antennas of the car can be used usinga Fakra-SMA adapter)

206 Chapter 27 VW e-Up

Open Vehicles

272 Using Comfort CAN 207

Open Vehicles

The passenger seat doesnrsquot need to be removed completely you can access the OCU connection from the back whentilting the unscrewed seat to the front To unscrew the seat yoursquoll need an XZN (triple-square german ldquoVielzahnrdquo)M10 bit Hint raise the seat to gain access to the rear screws

The T26a plug is secured by the white clamp open it fully to the left to unplug

273 Using both Connections

This document shows two options to use both connections

1 Variant 1 connects to the Comfort CAN using the OCU T26A connector

2 Variant 2 connects to the Comfort CAN by tapping the Comfort CAN cables

Both variants allow keeping the OCU in place If you intend to replace the OCU by the OVMS and reuse the OCUantennas for the OVMS variant 1 will probably be the better choice

2731 Variant 1

Connecting to the Comfort CAN using the OCU T26A connector

You need to establish a connection between the OBD2 and the OCU ports If installing the OVMS near the OBD2port you need to make a cable to connect to the T26A plug (or tap into the T26A cable there) If installing the OVMSreplacing the OCU you need to connect the OBD2 CAN bus from there

An adapter cable has to be made with the following connections

208 Chapter 27 VW e-Up

Open Vehicles

The cable used between the OBD plug and the DB9-F plug needs to be twisted to avoid transmission problems Agood cable to use here is a CAT-5 or CAT-6 double shielded network cable Be sure to not only connect CAN hi andCAN lo but also connect ground

T26 OBD DB9-F Signal26 4 3 Chassis Power GND 14 2 can1 L (OBD2 CAN Low) 6 7 can1 H (OBD2 CAN High) 4 can2 L (not used) 5 can2 H (not used)2 6 can3 L (Comfort-CAN Low)14 8 can3 H (Comfort-CAN High)1 9 +12V Vehicle Power

Important note the VW T26a pin numbering scheme does not follow the IT standard (zig zag) but instead has pins1-13 left to right on the top and 14-26 left to right on the bottom row See image above

2732 Variant 2

Connecting to the Comfort CAN by tapping the Comfort CAN cables

Description amp images by courtesy of GE user donaldduck8

This approach installs the OVMS near the OBD2 port and keeps the OCU in place Advantages

1 The OCU remains untouched and can be switched onoff as needed (fuse SD1)

2 No need to unmount the passenger seat

3 The OVMS can be disabledenabled any time simply via the OBD2 plug

The OVMS will be mounted on the driver side behind the footwell panel near the OBD2 port The Comfort CANsignal will be taken by tapping the cables behind the passengerrsquos footwell panel

The cable used needs to be twisted to avoid transmission problems A good cable to use here is a CAT-5 or CAT-6double shielded network cable A network cable has four pairs you will only need one pair here We recommendconnecting the shielding as well to avoid issues

273 Using both Connections 209

Open Vehicles

To connect to the OVMS you can use either a custom DB9 plug or add a DA26 connector You need to connect toCAN3

Comfort CAN OBD DB9-F DA26 Signal 4 3 8 Chassis Power GND 14 2 5 can1 L (OBD2 CAN Low) 6 7 15 can1 H (OBD2 CAN High) 12 4 7 can2 L (not used) 13 5 17 can2 H (not used)orangebrown 6 6 can3 L (Comfort-CAN Low)orangegreen 8 16 can3 H (Comfort-CAN High) 16 9 9 +12V Vehicle Power

Step 1 Remove the passenger footwell panel

Step 2 Tap into the Comfort CAN

Comfort CAN is on cables orangegreen (rarrCAN3-H) and orangebrown (rarrCAN3-L) Carefully remove a part of theisolation solder on your twisted pair cables then restore the isolation (eg by applying PlastiDip)

210 Chapter 27 VW e-Up

Open Vehicles

Step 3 Lay the cable towards the fuse box amp OBD2 port on the left

273 Using both Connections 211

Open Vehicles

Step 4 Use velcro tape to mount the OVMS on the side wall

Step 5 Stick the GPS antenna eg onto the air vent pipe To disable the OCU unplug fuse SD1

212 Chapter 27 VW e-Up

Open Vehicles

Step 6 Stick the GSM antenna eg on the lower panelrsquos rear side

Finally Refit all panels

273 Using both Connections 213

Open Vehicles

274 Basic Configuration

After selecting the VW e-Up vehicle module the corresponding settings have to be made in the web interface via theldquoVW e-Uprdquo menu under ldquoFeaturesrdquo

214 Chapter 27 VW e-Up

Open Vehicles

By default both connections are activated

For more details on the two connection types please see the corresponding projects

VW e-Up via Comfort CAN (T26A)

VW e-Up via OBD2

The initial code is shamelessly copied from the original projects for the Comfort CAN by Chris van der Meijden andfor the OBD2 port by SokoFromNZ

List of (possible) metrics via OBD2 httpswwwgoingelectricdewikiListe-der-OBD2-Codes

If OBD is selected a sample page with some charging metrics is shown in the web interface

274 Basic Configuration 215

Open Vehicles

216 Chapter 27 VW e-Up

Open Vehicles

Beware obviously these values have great uncertainties (in my car the DC output voltage of the charger is alwayslower than the voltage of the battery ) But eg the internal energy counters are very informative )

Additional custom web pages (code for the example above is below) can be defined as described here httpsdocsopenvehiclescomenlatestpluginREADMEhtmlhighlight=web20plugininstalling-web-plugins

274 Basic Configuration 217

Open Vehicles

275 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 2013-Vehicle Ca-ble

Comfort CAN T26A (OCU connector cable located under front passenger seat) to DB9 Data Cablefor OVMS using pin 6 and 8 for can3 _AND_ OBD-II to DB9 Data Cable for OVMS (1441200right or 1139300 left) for can1

GSMAntenna

T4AC - R205 with fakra_sma adapter cable or 1000500 Open Vehicles OVMS GSM Antenna (orany compatible antenna)

GPS An-tenna

T4AC - R50 with fakra_sma adapter cable or 1020200 Universal GPS Antenna (or any compatibleantenna)

SOC Dis-play

Yes

Range Dis-play

Yes

Cabin Pre-heatcoolControl

Yes

GPS Loca-tion

Yes (from modem module GPS)

Speed Dis-play

Yes

Tempera-ture Display

Yes (see list of metrics below)

BMS v+tDisplay

Yes

TPMS Dis-play

tba

Charge Sta-tus Display

Yes

ChargeInterruptionAlerts

Yes (per notification on the charging state)

ChargeControl

tba

LockUnlockVehicle

No

Valet ModeControl

No

Others See list of metrics below

276 Supported Standard Metrics

The second column specifies the bus from which the metrics are obtained Metrics via OBD are only updated when thevehicle is on (ignition started) or some in charging mode Metrics via T26 (Comfort CAN) can be updated on demandby waking the Comfort CAN from the OVMS module During charging the Comfort CAN automatically wakes every5 of SoC

218 Chapter 27 VW e-Up

Open Vehicles

Metric name bus Example value Descriptionvb12vvoltage direct 129 V Current voltage of the 12V batteryvbconsumption OBD 0Whkm Main battery momentary consumptionvbcurrent OBD 232 A Current current into (negative) or out of (positive) the main batteryvbenergyrecdtotal OBD 578323 kWh Energy recovered total (life time) of the main battery (charging and recuperation)vbenergyusedtotal OBD 540342 kWh Energy used total (life time) of the main batteryvbpower OBD 23234 kW Current power into (negative) or out of (positive) the main batteryvbrangeest T26 99km Estimated rangevbrangeideal T26 48km Ideal rangevbsoc OBD T26 882 Current usable State of Charge (SoC) of the main batteryvbtemp OBD 225 degC Current temperature of the main batteryvbvoltage OBD 3202 V Current voltage of the main batteryvc12vcurrent OBD 78A Output current of DCDC-convertervc12vpower OBD 0123kW Output power of DCDC-convertervc12vtemp OBD 345degC Temperature of DCDC-convertervc12vvoltage OBD 123V Output voltage of DCDC-convertervccharging T26 true Is vehicle charging (true = ldquoVehicle CHARGINGrdquo state veon=false if this is true)vcclimit fixed 1632A Maximum charger output currentvccurrent OBD 125A Momentary charger output currentvcefficiency OBD 913 Charging efficiency calculated by vbpower and vcpowervckwh OBD 26969kWh Energy sum for running chargevcmode T26 standard standard range performance storagevcpilot T26 no Pilot signal presentvcpower OBD 7345 kW Input power of chargervcstate T26 done charging topoff done prepare timerwait heating stoppedvcsubstate T26 scheduledstop scheduledstart onrequest timerwait powerwait stopped interruptedvctemp OBD 16degC Charger temperaturevctime T26 0Sec Duration of running chargevcvoltage OBD 0V Momentary charger supply voltagevdcp T26 yes yes = Charge port openvdfl T26 yes = Front left door openvdfr T26 yes = Front right door openvdhood T26 yes = Hoodfrunk openvdrl T26 yes = Rear left door openvdrr T26 yes = Rear right door openvdtrunk T26 yes = Trunk openveawake T26 no yes = Vehiclebus awake (switched on)vecabintemp T26 20degC Cabin temperaturevedrivetime T26 0Sec Seconds driving (turned on)veheadlights T26 yes = Headlights onvehvac T26 yes = HVAC activevelocked T26 yes = Vehicle lockedveon T26 true Is ignition on and drivable (true = ldquoVehicle ONrdquo false = ldquoVehicle OFFrdquo state)veparktime T26 49608Sec Seconds parking (turned off)veservrange OBD 12345km Distance to next scheduled maintenanceservice [km]veservtime OBD 1572590910Sec Time of next scheduled maintenanceservice [UTC]vetemp OBD T26 Ambient temperaturevitemp OBD Inverter temperaturevmtemp OBD 0degC Motor temperaturevpodometer OBD T26 2340 km Total distance traveledvpspeed T26 0kmh Vehicle speed

Continued on next page

276 Supported Standard Metrics 219

Open Vehicles

Table 1 ndash continued from previous pageMetric name bus Example value Descriptionvvin T26 VF1ACVYB012345678 Vehicle identification number

277 Custom Metrics

In addition to the standard metrics above the following custom metrics are read from the car or internally calculatedby OVMS using read values

Metricname

bus Examplevalue

Description

xvubcelldeltaOBD 0012 V Delta voltage between lowest and highest cell voltagexvubsocabs OBD 853 Current absolute State of Charge (SoC) of the main batteryxvucsocnormOBD 805 Current normalized State of Charge (SoC) of the main battery as reported by

charge management ECUxvucaci1 OBD 59 A AC current of AC charger phase 1xvucaci2 OBD 70 A AC current of AC charger phase 2 (only for model 2020+)xvucacp OBD 7223 kW Current charging power on AC side (calculated by ECUrsquos AC voltages and

AC currents)xvucacu1 OBD 223 V AC voltage of AC charger phase 1xvucacu2 OBD 233 V AC voltage of AC charger phase 2 (only for model 2020+)xvucdci1 OBD 12 A DC current of AC charger 1xvucdci2 OBD 12 A AC current of AC charger 2 (only for model 2020+)xvucdcp OBD 6500 kW Current charging power on DC side (calculated by ECUrsquos DC voltages and

DC currents)xvucdcu1 OBD 380 V DC voltage of AC charger 1xvucdcu2 OBD 375 V DC voltage of AC charger 2 (only for model 2020+)xvuceffcalc OBD 900 Charger efficiency calculated by AC and DC powerxvuceffecu OBD 923 Charger efficiency reported by the Charger ECUxvuclosscalc OBD 0733 kW Charger power loss calculated by AC and DC powerxvuclossecu OBD 0620 kW Charger power loss reported by the Charger ECUxvueservdaysOBD 78 days Time to next scheduled maintenanceservice [days]xvumsocabs OBD 853 Current absolute State of Charge (SoC) of the main battery as reported by

motor electronics ECUxvumsocnormOBD 805 Current normalized State of Charge (SoC) of the main battery as reported by

motor electronics ECU

278 Example Code for Web Plugin with some custom metrics

ltdiv class=panel panel-primarygtltdiv class=panel-headinggtCustom Metricsltdivgtltdiv class=panel-bodygt

lthrgt

ltdiv class=receivergtltdiv class=clearfixgtltdiv class=metric progress data-metric=vbsoc data-prec=1gtltdiv class=progress-bar value-low text-left role=progressbar

(continues on next page)

220 Chapter 27 VW e-Up

Open Vehicles

(continued from previous page)

aria-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoCltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=xvubsocabs data-prec=1gtltdiv class=progress-bar progress-bar-info value-low text-left role=progressbar

rarr˓aria-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoC (absolute)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbenergyusedtotal data-prec=2gtltspan class=labelgtTOTALSampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbsp

rarr˓ampnbspampnbspampnbspUsedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vbenergyrecdtotal data-prec=2gtltspan class=labelgtChargedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vpodometer data-prec=0gtltspan class=labelgtOdoltspangtltspan class=valuegtltspangtltspan class=unitgtkmltspangt

ltdivgtltdiv class=metric number data-metric=veservrange data-prec=0gtltspan class=labelgtSERVICEampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbspamp

rarr˓nbspampnbspampnbspampnbspRangeltspangtltspan class=valuegtltspangtltspan class=unitgtkmltspangt

ltdivgtltdiv class=metric number data-metric=xvueservdays data-prec=0gtltspan class=labelgtDaysltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

lth4gtBatterylth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=vbvoltage data-prec=1gtltdiv class=progress-bar value-low text-left role=progressbararia-valuenow=0 aria-valuemin=300 aria-valuemax=420 style=width0gtltdivgt

(continues on next page)

278 Example Code for Web Plugin with some custom metrics 221

Open Vehicles

(continued from previous page)

ltspan class=labelgtVoltageltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbcurrent data-prec=1gtltdiv class=progress-bar progress-bar-danger value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-200 aria-valuemax=200 style=width0gtltdivgtltspan class=labelgtCurrentltspangtltspan class=valuegtltspangtltspan class=unitgtAltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbpower data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-70 aria-valuemax=70 style=width0gtltdivgtltspan class=labelgtPowerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgtltdivgt

ltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbtemp data-prec=1gtltspan class=labelgtTempltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangtltdivgtltdiv class=metric number data-metric=xvubcelldelta data-prec=3gtltspan class=labelgtCell deltaltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangtltdivgt

ltdivgt

lth4gtTemperatureslth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=vetemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtAmbientltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vecabintemp data-prec=1gt

(continues on next page)

222 Chapter 27 VW e-Up

Open Vehicles

(continued from previous page)

ltdiv class=progress-bar progress-bar-warning value-low text-left role=rarr˓progressbar

aria-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtCabinltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbtemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtBatteryltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vctemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtChargerltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vc12vtemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtDCDC-Converterltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vitemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtInverterltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vmtemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbar(continues on next page)

278 Example Code for Web Plugin with some custom metrics 223

Open Vehicles

(continued from previous page)

aria-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtMotorltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgt

ltdivgtltdivgt

ltdivgtltdivgt

ltdivgt

279 Custom Data Logs

2791 SOC Monitoring Log

The SOC monitoring log provides detailed data about the correlations and connections between the various SOCsvoltage level amp energycoulomb chargedischarge amounts

You need to enable this log explicitly by configuring a storage time via config param xvu logsocmonstoretime (in days) Set to 0empty to disable the log Already stored log entries will be kept on the serveruntil expiry or manual deletion

Log entries are created on SOC changes while charging and every 10 seconds while driving

bull Notification subtype xvulogsocmon

bull History record type XVU-LOG-SOCMon

bull Format CSV

bull Archive time config xvu logsocmonstoretime (days 0=off)

bull Fieldscolumns

ndash temp ndash battery temperature [degC]

ndash charging ndash 01

ndash soc_abs_bms ndash absolute SOC from BMS (ECU 8C PID 028C) []

ndash soc_abs_eng ndash absolute SOC from engine (ECU 01 PID F45B) []

ndash soc_norm_cmg ndash normalized user SOC from charge manager (ECU BD PID 1DD0) []

ndash soc_norm_eng ndash normalized user SOC from engine (ECU 01 PID 1164) []

ndash soc_norm ndash previously selected soc_norm_eng while driving now always soc_norm_cmg []

ndash voltage ndash momentary total battery voltage [V]

ndash current ndash momentary battery current negative = charging [A]

ndash soh ndash state of health sourced as configured []

ndash cac ndash battery capacity sourced as configured [Ah]

ndash energy_used ndash total car energy discharge counter [kWh]

ndash energy_recd ndash total car energy charge counter [kWh]

224 Chapter 27 VW e-Up

Open Vehicles

ndash coulomb_used ndash total car coulomb discharge counter [Ah]

ndash coulomb_recd ndash total car coulomb charge counter [Ah]

ndash pack_vavg ndash average cell voltage [V]

ndash pack_vmin ndash minimum cell voltage [V]

ndash pack_vmax ndash maximum cell voltage [V]

ndash pack_vstddev ndash cell voltage standard deviation [V]

ndash pack_vgrad ndash cell voltage series quality (gradient)

ndash energy_range ndash remaining usable energy from MDF range estimation (ECU 17 PID 22E4) [kWh]

279 Custom Data Logs 225

Open Vehicles

226 Chapter 27 VW e-Up

CHAPTER 28

VW e-Up via OBD2

Vehicle Type VWUPOBD

This vehicle type supports the VW e-UP (new model from year 2020 onwards) Untested (so far) but probably workingThe older models of the e-Up as well as Skoda Citigo E IV and Seat MII electric

Connection is via the standard OBD-II port (above the drivers left foot)

All communication with the car is read-only For changing values (ie climate control) see the T26A connection tothe Comfort CAN bus

281 Support Overview

Function Support StatusHardware No specific requirementsVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display YesBMS v+t Display Yes (including cell details)TPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers See list of metrics below

227

Open Vehicles

282 Vehicle States

Warning For proper state detection the 12V calibration is crucial Calibrate using the OVMS Web UI Configrarr Vehicle rarr 12V Monitor

Three vehicle states are supported and detected automatically

Vehicle ON The car is on It is drivable

Vehicle CHARGING The car is charging The carrsquos Charger ECU is responsive and reports charging activity

Vehicle OFF The car is off It hasnrsquot drawn (or charged) any current into the main battery for a period of time andthe 12V battery voltage is smaller than 129V

283 Supported Standard Metrics

Metrics updated in state ldquoVehicle ONrdquo or ldquoVehicle CHARGINGrdquo

Metric name Examplevalue

Description

veon yes Is ignition on and drivable (true = ldquoVehicle ONrdquo false = ldquoVehicle OFFrdquostate)

vccharging yes Is vehicle charging (true = ldquoVehicle CHARGINGrdquo state veon=false if thisis true)

vclimitsoc 100 Sufficient SOC timer mode SOC destination or user CTP configuration (seebelow)

vcmode range ldquorangerdquo = charging to 100 SOC else ldquostandardrdquovctimermode no Yes = currentnext charge under timer controlvcstate done charging stopped donevcsubstate scheduledstop scheduledstop scheduledstart onrequest timerwait stopped interruptedvb12vvoltage1 129 V Current voltage of the 12V batteryvbvoltage 3202 V Current voltage of the main batteryvbcurrent 232 A Current current into (negative) or out of (positive) the main batteryvbpower 23234 kW Current power into (negative) or out of (positive) the main batteryvbenergyusedtotal 540342 kWh Energy used total (life time) of the main batteryvbenergyrecdtotal 578323 kWh Energy recovered total (life time) of the main battery (charging and recu-

peration)vbtemp 225 degC Current temperature of the main batteryvpodometer 2340 km Total distance traveled

Metrics updated only in state ldquoVehicle ONrdquo

Metric name Example value Descriptionvbsoc2 882 Current usable State of Charge (SoC) of the main batteryvedrivemode 2 1=STD 2=ECO 3=ECO+vegear 1 1=forward 0=neutral -1=reverse (2020 model only)

Metrics updated only in state ldquoVehicle CHARGINGrdquo1 Also updated in state ldquoVehicle OFFrdquo2 Restriction by the ECU Supplied when the ignition is on during charging Use xvubsoc as an alternative when charging with ignition off

228 Chapter 28 VW e-Up via OBD2

Open Vehicles

Metric name Example value Descriptionvcpower 7345 kW Input power of chargervcefficiency 913 Charging efficiency calculated by vbpower and vcpower

284 Custom Metrics

In addition to the standard metrics above the following custom metrics are read from the car or internally calculatedby OVMS using read values

State metrics

Metric name Example value Descriptionxvuehvchgmode 0 High voltage charge mode 0=off 1=Type2 4=CCSxvuelvautochg 1 Auxiliary battery (12V) auto charge mode (01)xvuelvpwrstate 0 Low voltage (12V) power state (0=off 4=12V 8=HVAC 15=on)

Timed charge metrics

Metric name Example value Descriptionxvuclimitsocmax 80 Charge schedule maximum SOCxvuclimitsocmin 20 Charge schedule minimum SOCxvuctimermodedef yes Charge timer defined amp default

xvuctimermodedef tells if a charge schedule has been configured and enabled If so the car uses timedcharging by default (the charge mode button will be lit) vctimermode tells if the charge timer is or will actuallybe used for the current or next charge ie reflects the mode selected by pushing the button

With timed charging the car first charges to the minimum SOC as soon as possible (when connected) If the maximumSOC configured for the schedule hasnrsquot been reached by then it will then wait for the timer to signal the second phaseto charge up to the maximum SOC The ldquosufficient SOCrdquo vclimitsoc will be the maximum SOC if less than100 If the timer is disabled or set to charge up to 100 the sufficient SOC is set to the user configured charge timeprediction SOC limit (config xvu ctpsoclimit)

Charging above vclimitsoc is classified as the ldquotopping offrdquo charge phase When crossing that SOC thresholdan intermediate charge status notification is sent

Note xvuclimitsocmin will show the configured minimum SOC also if no schedule is currently enabledxvuclimitsocmax shows the maximum for the currentnext schedule to apply If no schedule is enabled itwill be zero

Metrics updated in state ldquoVehicle ONrdquo or ldquoVehicle CHARGINGrdquo

Metric name Example value Descriptionxvubcelldelta 0012 V Delta voltage between lowest and highest cell voltagexvubsoc 853 Current absolute State of Charge (SoC) of the main battery

Metrics updated only in state ldquoVehicle CHARGINGrdquo

284 Custom Metrics 229

Open Vehicles

Metric name Examplevalue

Description

xvuceffecu3 923 Charger efficiency reported by the Charger ECUxvuclossecu3 0620 kW Charger power loss reported by the Charger ECUxvucacp 7223 kW Current charging power on AC side (calculated by ECUrsquos AC voltages and AC

currents)xvucdcp 6500 kW Current charging power on DC side (calculated by ECUrsquos DC voltages and DC

currents)xvuceffcalc 900 Charger efficiency calculated by AC and DC powerxvuclosscalc 0733 kW Charger power loss calculated by AC and DC powerxvucccsu4 3315V CCS charger supplied voltage [V]xvucccsi4 622A CCS Charger supplied current [A]xvucccsp4 206193kW CCS Charger supplied power [kW]

285 Battery Capacity amp SOH

e-Up Model Total capacity Usable capacityGen 1 (2016) 187 kWh 50 Ah 164 kWh 439 Ah (877)Gen 2 (2020) 368 kWh 120 Ah 323 kWh 1053 Ah (877)

There are currently two ways to get an estimation of the remaining capacity of the e-Up

1 By deriving a usable energy capacity from the MFD range estimation

2 By deriving a total coulomb capacity from the coulombs charged

You can configure which of the estimations you want to use as the standard SOH from the ldquoFeaturesrdquo web page or bysetting the config parameter xvu batsohsource to either charge (default) or range

Note Consider the capacity estimations as experimental preliminary We need field data to optimize thereadings If yoursquod like to help us see below

The MFD range estimation seems to include some psychological factors with an SOC below 30 so we onlyprovide this and the derived capacity in two custom metrics The capacity derivation is only calculated with SOC gt=30 (initial value needs SOC gt= 70) but if so is available immediately after switching the car on This can serve asa quick first estimation relate it to the usable capacity of your model

The range based SOH is taken at itrsquos maximum peaks observed and copied if higher than the previously observedvalue or added smoothed if lower So to take the next reading directly set metric xvubsohrange to 0 beforeswitching on the car

The charge coulomb based estimation provides a better estimation but will need a little more time to settle Usablemeasurements need charges of at least 30 SOC the more the better Estimations are only calculated if a charge hasexceeded 30 SOC and results are smoothed over multiple charges to provide stable readings

bull To get a rough capacity estimation charge at least 30 normalized SOC difference

3 Only supplied by ECU when the car ignition is on during charging4 These are not measurements by the car but provided as is by the charger and typically deviate from the battery metrics According to IEC

61851 CCS currents may be off by +- 3 and voltages by +- 5 The power figures displayed by some chargers also typically wonrsquot match thesevalues possibly because the charger displays the power drawn from the grid (including losses)

230 Chapter 28 VW e-Up via OBD2

Open Vehicles

bull To get a good capacity estimation do at least three charges with each covering 60 or more normalized SOCdifference

Charging by CCS (DC) apparently yields higher results especially on the energy estimations We donrsquot know yet thereason or if we need to compensate this

Note the SOH (state of health) is currently coupled directly and solely to the calculated amp-hour capacity CAC

To log your capacity data on a connected V2 server do

OVMS config set xvu logchargecapstoretime 30

30 is the number of days to keep the data set to 0 to disable The counters will be stored in tableXVU-LOG-ChargeCap with one entry every 24 absolute SOC difference Resulting CACSOH updates willbe logged in table XVU-LOG-ChargeCapSOH You can also extract the data from your module log file by filteringlines matching ChargeCap

2851 Capacity and SOH metrics

Metric name Example value Descriptionxvubsohcharge 9923 SOH based on charge energy sumxvubsohrange 9889 SOH based on MFD range estimationxvubcapahabs 12271Ah Total coulomb capacity estimationxvubcapahnorm 11363Ah Usable coulomb capacity estimationxvubcapkwhabs 391kWh Total energy capacity estimationxvubcapkwhnorm 3621kWh Usable energy capacity estimationxvubcapkwhrange 328947kWh Usable energy capacity estimation from MFD rangexvubenergyrange 185kWh Current energy used by MFD range estimation

2852 Provide Data to the Developers

To help us with optimizing the capacity estimations first of all enable file logging if not already enabled Then enableextended polling and logging before a charge by

OVMS config set xvu dc_interval 30OVMS log level verbose v-vweup

After the charge disable the extended polling and logging

OVMS config set xvu dc_interval 0OVMS log level info v-vweup

Then download all log files written during the charge (archived and current) zip them and mail the zip to MichaelBalzer ltdexterdexters-webdegt The log data will only be used for technical analysis and deleted afterwards

Note if you forgot enabling the local log but still have chargecap logs on the server these can help as well

Thanks

286 Configuration Variables

The main configuration variables can be set through the web configuration page

286 Configuration Variables 231

Open Vehicles

bull VW e-Up rarr Features

Some configuration variables are kept ldquounder the hoodrdquo as these will normally not need to be changed except forsome special use cases or for development debugging

Configuration variables can be listed using command config list xvu and changed using command configset xvu ltvariablegt ltvaluegt

Configuration variable Default value Descriptionbatsohsource charge SOH source ndash see abovebmsautoreset no Reset BMS statistics on use phase transitionscanwrite no Allow CAN write accesscell_interval_awk 60 BMS cell query interval in awake state [s]cell_interval_chg 60 BMS cell query interval in charge state [s]cell_interval_drv 15 BMS cell query interval in drive state [s]con_obd yes Enable OBDII connectioncon_t26 yes Enable T26 connectionctpmaxpower 0 Charge time prediction fallback power limit [kW] (0=none)ctpsoclimit 80 Charge time prediction fallback SOC limit []dc_interval 0 Development additional DC charge PID query interval [s] (0=off)logchargecapcpstep 24 Charge capacity checkpoint interval [110]logchargecapminvalid 272 Charge capacity min SOC hub for SOH change [110]logchargecapstoretime 0 Charge capacity server log archive time [days] (0=off)modelyear 2012 Vehicle model yearnotifychargestartdelay 24 Charge start notification delay [s]5

287 Shell Commands

bull xvu polling ltstatus|pause|continuegt ndash control OBD2 polling

The OBD2 polling is normally continuously active as long as the vehicle module is loaded To free the CANbus from this load during an extended OBD2 diagnostics or modification (coding adaptation) session you cantemporarily pause the polling using this command

There is no time limit for a pause keep in mind you need to explicitly continue the polling when yoursquore doneDuring a polling pause no vehicle state changes can be detected

288 Custom Status Page for Web UI

Note This plugin is obsolete use the standard page VW e-Up rarr Charging Metrics instead We keep the sourcehere as a base for user customization

The easiest way to display custom metrics is using the Web Plugins feature of OVMS (see Installing Web Plugins)

This page plugin content shows the metrics in a compact form which can be displayed on a phone in landscape modeon the dashboard of the car Best approach is to connect the phone directly to the OVMS AP-WiFi and access the webUI via the static IP (19216841) of OVMS

5 Charge start needs some time to ramp up the charge current which implies charge speed amp time estimations If you want the start notificationas fast as possible reduce the value

232 Chapter 28 VW e-Up via OBD2

Open Vehicles

ltdiv class=panel panel-primarygtltdiv class=panel-headinggtVW eUpltdivgtltdiv class=panel-bodygt

lthrgt

ltdiv class=receivergtltdiv class=clearfixgtltdiv class=metric progress data-metric=vbsoc data-prec=2gtltdiv class=progress-bar value-low text-left role=progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoCltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=xvubsoc data-prec=2gtltdiv class=progress-bar progress-bar-info value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoC (absolute)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

(continues on next page)

288 Custom Status Page for Web UI 233

Open Vehicles

(continued from previous page)

ltdivgtltdivgt

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbenergyusedtotal data-prec=3gtltspan class=labelgtTOTALSampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbspamp

rarr˓nbspampnbspampnbspampnbspUsedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vbenergyrecdtotal data-prec=3gtltspan class=labelgtChargedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vpodometer data-prec=0gtltspan class=labelgtDistanceltspangtltspan class=valuegtltspangtltspan class=unitgtkmltspangt

ltdivgtltdivgt

lth4gtBatterylth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=vbvoltage data-prec=1gt

ltdiv class=progress-bar value-low text-left role=progressbararia-valuenow=0 aria-valuemin=300 aria-valuemax=350 style=width0gtltdivgtltspan class=labelgtVoltageltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbcurrent data-prec=1gtltdiv class=progress-bar progress-bar-danger value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-200 aria-valuemax=200 style=width0gtltdivgtltspan class=labelgtCurrentltspangtltspan class=valuegtltspangtltspan class=unitgtAltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbpower data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-70 aria-valuemax=70 style=width0gtltdivgtltspan class=labelgtPowerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgt

(continues on next page)

234 Chapter 28 VW e-Up via OBD2

Open Vehicles

(continued from previous page)

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbtemp data-prec=1gtltspan class=labelgtTempltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdiv class=metric number data-metric=xvubcelldelta data-prec=3gtltspan class=labelgtCell deltaltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangt

ltdivgtltdivgt

lth4gtChargerlth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=xvucacp data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=8 style=width0gtltdivgtltspan class=labelgtAC Powerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=xvucdcp data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=8 style=width0gtltdivgtltspan class=labelgtDC Powerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgt

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vcefficiency data-prec=1gt

ltspan class=labelgtEfficiency (total)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdiv class=metric number data-metric=xvuceffcalc data-prec=1gtltspan class=labelgtEfficiency (charger)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdiv class=metric number data-metric=xvuclosscalc data-prec=3gtltspan class=labelgtLoss (charger)ltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgt(continues on next page)

288 Custom Status Page for Web UI 235

Open Vehicles

(continued from previous page)

ltdivgtltdivgtltdivgt

ltdivgt

236 Chapter 28 VW e-Up via OBD2

CHAPTER 29

VW e-Up via Comfort CAN (T26A)

Vehicle Type integrated in VWUP

This part was the initial code for the OVMS VWUP vehicle module Development started in January 2020 by Chrisvan der Meijden

It supports the VW e-UP (2013- 2020-) Skoda Citigo E IV and the Seat MII electric (2020-) directly connected tothe comfort can bus through the lsquoT26Arsquo socket

237

Open Vehicles

291 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 2020- (2013- VW e-Up as well)Vehicle Cable Comfort CAN T26A (OCU connector cable located under front passenger seat) to DB9 Data

Cable for OVMS using pin 6 and 8 for can3GSM Antenna T4AC - R205 with fakra_sma adapter cable or 1000500 Open Vehicles OVMS GSM Antenna

(or any compatible antenna)GPS Antenna T4AC - R50 with fakra_sma adapter cable or 1020200 Universal GPS Antenna (or any com-

patible antenna)SOC Display YesRange Display YesCabin Pre-heatcool Control

Yes

GPS Location Yes (from modem module GPS)Speed Display YesTemperature Dis-play

Yes (outdoor cabin)

BMS v+t Display NoTPMS Display NoCharge Status Dis-play

Yes

Charge Interrup-tion Alerts

Yes (per notification on the charging state)

Charge Control tbaLockUnlockVehicle

No

Valet Mode Con-trol

No

Others Odometer trip VIN status of lock plug lights doors trunk and bonnet

292 Pinout OCU T26A - OVMS DB9 adapter

For the T26A approach we directly tap into the comfort can bus via the original OCU cable

The OCU connector is located under the passenger seat

238 Chapter 29 VW e-Up via Comfort CAN (T26A)

Open Vehicles

Advantage is the direct write access to the comfort can bus

Disadvantage is that we wonrsquot be able to access all control units of the car

OCU DB9-F Signal26 3 Chassis Power GND 2 can1 L (Can Low not used) 7 can1 H (Can High not used) 4 can2 L (Can Low not used) 5 can2 H (Can High not used)2 6 can3 L (Comfort-can Low)14 8 can3 H (Comfort-can High)1 9 +12V Vehicle Power

For confectioning the T26A adapter cable you can use a standard 26 pin ribbon cable (2x13 pins 254mm grid dimen-sion) and a DB9 female D-Sub connector You will need to grind down the rim of the socket of the ribbon cable

To make a GSMGPS adapter cable to connect to the original VW fakra socket you can use a double fakra maleconnector with two SMA male connectors attached

292 Pinout OCU T26A - OVMS DB9 adapter 239

Open Vehicles

293 User notes

bull Remove the passenger seat (on right hand drive cars the driverrsquos seat)

bull Open the carpet lid

bull Disconnect the T26A cable and the fakra cable from the OCU (online communication unit)

bull Remove the OCU

bull Connect the confectioned T26A adapter DB9 cable attached to the OVMS to the VW T26A connector of thecar

bull Connect your GMSGPS fakra adapter to the VW fakra cable

bull Fit OVMS in the compartment

bull Close the carpet lid

bull Reinstall the passenger seat

bull Configure OVMS as described in the OVMS user manual

bull Configure lsquoModel yearrsquo lsquoCan write accessrsquo and lsquoConnection typersquo under VW e-Up -gt Features

bull lsquoModel yearrsquo and lsquoCan write accessrsquo can also be set from within the app (FEATURES 20 and 15)

bull Register and connect OVMS to a server (as guided within the OVMS setup)

bull Turn the ignition in the car on and off to receive initial values (also needed after updates)

bull Install the OVMS app on your smartphone or tablet and configure it to connect to the server

240 Chapter 29 VW e-Up via Comfort CAN (T26A)

Open Vehicles

bull Enjoy -)

294 Climate control

Climate control works as long as write access to the comfort can has been enabled in the app or in the OVMSwebinterface (VW e-Up -gt Features)

To turn on or off the AC from within the Android app just press the ldquoACrdquo button Within the iOS app press ldquoHomelink1rdquo for AC on and ldquoHomelink 2rdquo for AC off

Once the AC is turned on by the app there will be a delay of about 17 seconds untill the AC actually starts in the carFurther 10 seconds all communication from the app to the car is blocked

The communication from the app to the car is also blocked for 10 seconds after the ldquoAC offrdquo command from the appto the car There is no delay between the ldquoAC offrdquo signal of the app and the actually turning off in the car

In rare cases lsquoAC offrsquo does not respond There will be a delay of 40 seconds before you can try again

The cabin target temperature can be set from the OVMS webinterface (VW e-Up (Komfort CAN) -gt Climate control)or via the app under FEATURES 21

294 Climate control 241

Open Vehicles

295 IDs on Comfort CAN Bus

ID Conversion Unit Function61A d72 State of Charge (relative)320 (d4ltlt8+d3-1)190 kmh Speed65F 3 Msg d5-7d1-7d1-7 String VIN number571 5+(05d0) Volt 12 Volt battery voltage65D d3ampfltlt12|d2ltlt8|d1 km Odometer3E3 (d2-100)2 degC Cabin temperature527 (d52)-50 degC Outdoor temperature531 d0 00 Headlights off52D d0 +255 if d1 41 km Calculated range381 d0 02 Status doors locked470 d1 12482010 Integer Doors trunk hood opened or closed3E1 d4 Integer Blower speed(57667D98BBDEFA)575 d0 00 to 0F Integer Key position575 d3 00 or 10 windshield heater (off or on)569 b07 ldquoACrdquo-LED69C d110+10 degC temperature setpoint for remote AC (only in message D2 ltd1gt 00 1E 1E

0A 00 00)61C d2 lt 07 bool Charging detection43D d1 01 or 11 TX Working or sleeping in the ring5A7 d1 16 TX OCU AC blocking signal5A9 all 00 TX OCU heartbeat69E multiple msg d0 C1 d6

xxdegC TX AC on off signals TX set cabin temperature for 69C

242 Chapter 29 VW e-Up via Comfort CAN (T26A)

Open Vehicles

296 Development notes

Under this vehicle component part we use the original T26A approach which can write to the comfort can and is ableto manage the climate control of the car

You will normally use the OVMS binaries provided ie here

The VWUP T26A component part with working climate control is publicly available within the OVMS binary version3215 lsquoedgersquo and upwards (lsquomainrsquo lsquoeaprsquo and lsquoedgersquo) The Android app version has to be 3171 or higher to haveaccess to the climate control functions for this vehicle component

If you want to compile the binary yourself you will need to read the OVMS development documentation on how to setup the tool chain check out the repository and the submodules and copy the file

sdkconfigdefaulthw31

from the OVMSV3support folder to the OVMSV3 folder and rename it to

sdkconfig

297 Vehicle log files

To be able to implement the VWUP vehicle component for OVMS the CAN logging of the VW e-UP provided bylsquosharkcowrsquo was of tremendous help

The implementation of this vehicle component could not have been done without these great files

They can be found here

httpsgithubcomsharkcowVW-e-UP-OBD-CAN-logs

296 Development notes 243

Open Vehicles

244 Chapter 29 VW e-Up via Comfort CAN (T26A)

CHAPTER 30

Command Line Interpreter

The command line interpreter or command parser presented by the OVMS async serial console is constructed as a treeof command word tokens Enter a single question mark followed by RETURN to get the root command list like this

OVMS Run a scriptbms BMS frameworkboot BOOT frameworkcan CAN framework

A root command may be followed by one of a list of additional tokens called subcommands which in turn may befollowed by further subcommands down multiple levels forming a tree The command and subcommand tokens maybe followed by parameters Use question mark at any level in the command sequence to get the list of subcommandsapplicable at that point If the next item to be entered is a parameter rather than a subcommand then a usage mes-sage will be displayed to indicate the required or optional parameters The usage message will also be shown if thecommand as entered is not valid The usage message is described in further detail below

Command tokens can be abbreviated so long as enough characters are entered to uniquely identify the command Op-tionally pressing TAB at that point will auto-complete the token If the abbreviated form is not sufficient to be unique(in particular if no characters have been entered yet) then TAB will show a concise list of the possible subcommandsand retype the portion of the command line already entered so it can be completed Pressing TAB is legal at any pointin the command if there is nothing more that can be completed automatically then there will just be no response tothe TAB

301 OvmsCommand API

Each command word token in the tree is represented by an OvmsCommand object TheOvmsCommandRegisterCommand() function is used to create and add a command or subcommand to-ken object into the tree returning an OvmsCommand pointer to the new object New commands are added to theroot of the tree using the global MyCommandAppRegisterCommand() Subcommands are added as childrenof a command by calling RegisterCommand() using the OvmsCommand pointer to the parent object thusbuilding the tree For example

245

Open Vehicles

OvmsCommand cmd_wifi = MyCommandAppRegisterCommand(wifiWIFI framework wifi_rarr˓status)cmd_wifi-gtRegisterCommand(statusShow wifi statuswifi_status)cmd_wifi-gtRegisterCommand(reconnectReconnect wifi clientwifi_reconnect)

The RegisterCommand() function takes the following arguments

bull const char name ndash the command token

bull const char title ndash one-line description for the command list

bull void (execute)() ndash does the work of the command

bull const char usage ndash parameter description for ldquoUsagerdquo message

bull int min ndash minimum number of parameters allowed

bull int max ndash maximum number of parameters allowed

bull bool secure ndash true for commands permitted only after enable

bull int (validate)() ndash validates parameters as explained later

The RegisterCommand() function tolerates duplicate registrations of the same name at the same node of the treeby assuming that the other arguments are also the same and returning the existing object This allows mulitple modulesthat can be configured independently to share the same top-level command For example the obdii command is sharedby the vehicle and obd2ecu modules

Modules that can be dynamically loaded and unloaded must remove their commands from the tree usingUnregisterCommand(const char name) before unloading

Itrsquos important to note that many of the arguments to RegisterCommand() can and should be defaulted The defaultvalues are as follows

execute = NULLusage = min = 0max = 0secure = truevalidate = NULL

For example for secure non-terminal commands (those with child subcommands) such as the top-level frameworkcommands like bms in the list of root commands shown earlier the model should simply be

RegisterCommand(name Title)

For secure terminal subcommands (those with no children) that donrsquot require any additional parameters the modelshould be

RegisterCommand(name Title execute)

This model also applies if the command has children but the command itself wants to execute a default operation if nosubcommand is specified It is incorrect to specify min = 0 max = 1 to indicate an optional subcommand that isindicated by the presence of the execute function along with a non-empty array of child subcommands

Any command with required or optional parameters should provide a ldquousagerdquo string hinting about the parameters inaddition to specifying the minimum and maximum number of parameters allowed

RegisterCommand(name Title execute usage min max)

246 Chapter 30 Command Line Interpreter

Open Vehicles

The usage argument only needs to describe the parameters that follow this (sub)command because the full usagemessage is dynamically generated The message begins with the text ldquoUsage rdquo followed by the names of the ancestorsof this subcommand back to the root of the tree plus the name of this subcommand itself That is the message startswith all the tokens entered to this point The message continues with a description of subcommands andor parametersthat may be entered next as specified by the usage string

Note The usage message is not resricted to a single line the usage string can include additional lines of explana-tory text separated by n (newline) characters to help convey the meaning of the paramters and the purpose of thecommand

The usage string syntax conventions for specifying alternative and optional parameters are similar to those of usagemessages in Unix-like systems The string can also include special codes to direct the dynamic generation of themessage

bull $C expands to the list of children commands as child1|child2|child3

bull [$C] expands to list optional children as [child1|child2|child3]

bull $G$ expands to the usage string of the first child this would typically used after $C so the usage message showsthe list of children and then the parameters or next-level subcommands that can follow the children This isuseful when the usage string is the same for all or most of the children as in this example

Usage power adc|can1|can2|can3|egpio|esp32|sdcard|simcom|spi|wifirarr˓deepsleep|devel|off|on|sleep|status

bull $Gfoo$ expands to the usage of the child named ldquofoordquo this variant would be used when not all the childrenhave the same usage but it would still be helpful to show the usage of one thatrsquos not first

bull $L lists a full usage message for each of the children on separate lines This provides more help than justshowing the list of children but at the expense of longer output

For subcommands that take parameters the usage string contains explicit text to list the parameters

bull Parameter names or descriptions are enclosed in angle brackets to distinguish the them from command tokensfor example ltmetricgt ltvaluegt Since the angle brackets demarcate each parameter spaces may be in-cluded in the description

bull Parameters that are optional are further enclosed in square brackets like ltidgt ltnamegt [ltvaluegt]

bull When there are alternative forms or meanings for a parameter the alternatives are separated by vertical bar asin lttask names or idsgt||= which indicates that the parameter can be either of the characters or =instead of a list of task names or ids A variant form encloses the alternatives in curly braces as in ltparamgtltinstancegt |

bull One or more additional lines of explanatory text can be included like this

ltidgtnUse ID from connection list 0 to close all

For non-terminal commands (those with children subcommands) the usage argument can be omitted because thedefault value of is interpreted as $C For commands that have children subcommands that are optional (because anexecute function is included) the default usage argument is interpreted as [$C]

3011 Execute Function

The execute function performs whatever work is required for the command Its signature is as follows

301 OvmsCommand API 247

Open Vehicles

void (execute)(int verbosity OvmsWriter writer OvmsCommand cmd int argc constrarr˓char const argv)

bull int verbosity ndash tells how much output is appropriate (eg shell vs SMS)

bull OvmsWriter writer ndash object to which output is delivered eg console

bull OvmsCommand cmd ndash the command that held the execute function pointer

bull int argc ndash how many parameters are being supplied to the function

bull const char const argv ndash the parameter list

Any output appropriate for the command is accomplished through puts() or printf() calls on the writerobject The cmd pointer may allow sharing one execute function among multiple related command objects andprovides access to members of the command object such as GetName()

The argc count will be constrained to the min and max values specified for the cmd object so if the minimum andmaximum are the same then the execute function does not need to check However if parameters are expected thentheir values must be validated

3012 Validate Function

Most commands do not need to specify a validate function It supports extensions of the original command parserdesign for two use cases

1 For commands that store the possible values of a parameter in a NameMapltTgt or CNameMapltTgt thevalidate function enables TAB auto-completion when entering that parameter

2 The original design only allowed parameters to be collected by the terminal subcommand That forced anunnatural word order for some commands The validate function enables non-terminal subcommands totake one or more parameters followed by multiple levels of children subcommands The parameters may bestrings looked up in a NameMapltTgt or CNameMapltTgt or they could be something else like a number that canbe validated by value The validate function must indicate success for parsing to continue to the childrensubcommands The return value is the number of parameters validated if successful or -1 if not

The signature of the validate function is as follows

int (validate)(OvmsWriter writer OvmsCommand cmd int argc const char constrarr˓argv bool complete)

bull OvmsWriter writer ndash object to which output is delivered eg console

bull OvmsCommand cmd ndash the command that held the validate function pointer

bull int argc ndash how many parameters are being supplied to the function

bull const char const argv ndash the parameter list

bull bool complete ndash true for TAB completion of the last parameter (case 1) false when validating intermediateparameters before calling execute on the terminal descendant command (case 2)

The writer and cmd arguments are the same as for the execute function The argc count is never more than maxand if complete is false never less than min However when complete is true to request TAB auto-completionand max is greater than 1 argc will be at least 1 but may be less than min because it indicates how many parametershave been entered so far The TAB auto-completion is performed on the last parameter entered after validating anypreceding parameters If min and max are both 1 then it is not necessary to check argc

If the acceptable values of a parameter are stored in a NameMapltTgt or CNameMapltTgt those maps implement aValidate() function that will perform the validation needed for the validate function covering both the true

248 Chapter 30 Command Line Interpreter

Open Vehicles

and false cases of complete Those maps also implement a FindUniquePrefix() function that may be used tovalidate preceding parameters for commands that take multiple parameters

The config_validate() function for the config command in mainovms_configcpp is an example imple-mentation of use case 1 for a command taking three parameters with TAB auto-completion on the first two

int config_validate(OvmsWriter writer OvmsCommand cmd int argc const charrarr˓const argv bool complete)if (MyConfigismounted())return -1

argv[0] is the ltparamgtif (argc == 1)return MyConfigm_mapValidate(writer argc argv[0] complete)

argv[1] is the ltinstancegtif (argc == 2)OvmsConfigParam const p = MyConfigm_mapFindUniquePrefix(argv[0])if (p) ltparamgt was not valid so cant check ltinstancegtreturn -1

return (p)-gtm_mapValidate(writer argc argv[1] complete)

argv[2] is the value which we cant validatereturn -1

The location command in componentsovms_locationsrcovms_locationcpp is an example of usecase 2 as it includes an intermediate parameter and also utilizes the $L form of the usage string

OVMS location action enter Usage location action enter ltlocationgt acc ltprofilegtUsage location action enter ltlocationgt homelink 1|2|3Usage location action enter ltlocationgt notify lttextgt

The following excerpt shows the implementation of the location_validate() function and a subset of theRegisterCommand() calls to build the command subtree This example shows how simple the validation codecan be ndash sometimes just one line to call Validate() In this case the code does need to check argc because thefunction is shared by multiple subcommand objects taking 1 or 2 parameters

int location_validate(OvmsWriter writer OvmsCommand cmd int argc const charrarr˓const argv bool complete)if (argc == 1)return MyLocationsm_locationsValidate(writer argc argv[0] complete)

return -1

OvmsCommand cmd_location = MyCommandAppRegisterCommand(locationLOCATIONrarr˓framework)OvmsCommand cmd_action = cmd_location-gtRegisterCommand(actionSet an action for

rarr˓a location)OvmsCommand cmd_enter = cmd_action-gtRegisterCommand(enterSet an action upon

rarr˓entering a location NULL ltlocationgt $L 1 1 true location_validate)OvmsCommand enter_homelink = cmd_enter-gtRegisterCommand(homelinkTransmit

rarr˓Homelink signal)enter_homelink-gtRegisterCommand(1Homelink 1 signallocation_homelink 0 0

rarr˓true)enter_homelink-gtRegisterCommand(2Homelink 2 signallocation_homelink 0 0

rarr˓true) (continues on next page)

301 OvmsCommand API 249

Open Vehicles

(continued from previous page)

enter_homelink-gtRegisterCommand(3Homelink 3 signallocation_homelink 0 0rarr˓true)cmd_enter-gtRegisterCommand(accACC profilelocation_accltprofilegt 1 1

rarr˓true)cmd_enter-gtRegisterCommand(notifyText notificationlocation_notifylttextgt 1

rarr˓ INT_MAX true)

250 Chapter 30 Command Line Interpreter

CHAPTER 31

CAN Bus Data Logging

OVMS can be used as CAN bus datalogging tool

311 Physical Connections

OVMS hardware V3 supports up to three CAN bus connections The connections to OVMS are as follows

DB9-F Signal----- ------

2 CAN1-L7 CAN1-H

4 CAN2-L5 CAN2-H

6 CAN3-L8 CAN3-H

Note the board schematics refer to CAN012 These correspond to CAN123 here in the documentation and sourcecode The first is handled by ESP32 io lines directly and CAN23 are handled by MCP2515 ICs via SPI from theESP

CAN1 is the fastest bus use this one if possible The CAN logging tool is able to log all buses at the same time to thesame file or stream

Vehicle CAN bus(s) are usually accesable via the vehiclersquos OBD2 port Most modern cars have multiple CAN bussesThe OBD2 lsquostandardrsquo CAN will be available on OBD2 pin 6 CAN-H and pin 14 CAN-L However modern vehicles(especially EVrsquos) often have other CAN buses available on non-standard OBD2 pins

A voltmeter (ideally oscilloscope) can be used to determine which OBD2 pins contain CAN data

bull Can high pins should normally be between 25 and 35 volts (to ground) - maybe 27 to 33 volts if there istraffic

bull Can low pins should normally be between 15 and 25 volts (to ground) - maybe 17 to 23 volts if there is traffic

251

Open Vehicles

Pre-fabricated OBD2 gt DB9-F for several specific vehicles can be purchased via OpenVehicles

312 Enable OVMS CAN bus

Once physical connections has been made and OVMS is up and running connect to OVMS shell via web browser SSH or serial

If a specific vehicle module is loaded the CAN bus will already be enabled in OVMS To check which CAN buses areenabled use

OVMS can list

If no vehicle module is selected the CAN bus must be started eg

OVMS can can1 start listen 500000

This will enable CAN1 in listen mode (read only) at 500k baud active can be used instead of listen to enableread-write mode To stop a CAN1 bus

OVMS can can1 stop

OVMS supports the following CAN bauds rates 100000 125000 250000 500000 1000000

313 Logging to SD card

It is possible to view CAN data directly in OVMS monitor shell however since modern cars have very busy CANbuses there is often too much data which swamps the monitor or exceeds the logging queue resulting in droppedmessages Logging to SD card is the better option

If using a good quality SD card with a current OVMS V3 module (ie PCB revision 32 20190523 or later) increasethe SD card speed for best performance with

config set sdcard maxfreqkhz 20000

Start logging all CAN messages using CRTD log file format with

ovms can log start vfs crtd sdcancrtd

or log specific CAN packets by applying a filter eg 0x55b the Nissan LEAF SoC CAN message

ovms can log start vfs crtd sdcancrtd 55b

Other CAN log file formats are supported eg crtd gvret-a gvret-b lawricel pcap raw

Check CAN logging satus with

ovms can log status

To Stop CAN logging

ovms can log stop

Note the can logging must be stopped before the file can be viewed

To View the CAN log

ovms vfs head sdcancrtd

tail and cat commands can also be used However be careful the log file can quickly become very large cat mayoverwhelm the shell

The log file can also be viewed in a browser with httpltovms-ipaddressgtsdcancrtd

252 Chapter 31 CAN Bus Data Logging

Open Vehicles

The logfiles can then be imported into a tool like SavvyCan for analysis

314 Network Streaming

CAN data can be streamed directly to SavvyCan (or other compatible application) using the OVMS tcpserver CANlogging feature over a local network Start tcpserver CAN logging with

OVMS can log start tcpserver discard gvret-b 23

This will start a tcpserver on port 23 (as required by SavvyCan) using the GVRET format supported by SavvyCAN

Once OVMS CAN logging tcpserver is running open up SavvyCan and select

Connection gt Add New Device Connection gt Network Connection

then enter the OVMS WiFi local network IP address (no port number required) CAN packets should now appearstreaming into SavvyCan

Note CAN tcpserver network streaming is a beta feture currently in edge firmware and may be buggy

315 Optimizing the Performance

On can log stop the system will output some statistics Check especially the dropped frame count Framedrops can occur because the system was busy with other tasks like handling network traffic There are two options tooptimize this

a) Reduce background activities ie stop all services not needed for the logging If possible do the loggingwithout an active vehicle module (eg set the ldquoemptyrdquo vehicle via vehicle module NONE)

b) Raise the log queue size The default queue size has a capacity of 100 frames To eg allow 200 frames doconfig set can logqueuesize 200

314 Network Streaming 253

Open Vehicles

254 Chapter 31 CAN Bus Data Logging

CHAPTER 32

CRTD CAN Log Format

321 Introduction

The CRTD CAN Log format is a textual log file format designed to store information on CAN bus frames and eventsIt was introduced as a human readable file format capable of supporting data dumps from multiple CAN buses

Files or network data streams in CRTD format contain only textual data in UTF-8 with each record being on anindividual line terminated by a single linefeed (ascii 10) character or CRLF (ascii 13 ascii 10)

Each line is made up from the following fields separated by single spaces (ASCII 32)

bull Timestamp Julian timestamp seconds and millisecondsmicroseconds separated by a decimal point

bull Record Type Mnenomic to denote the record type

bull Record Data The remaining data is dependant on the record type

Here are some examples

1542473901020305 1R11 1542473901020305 2T11 1542473901020305 R11 1542473901021 1R11

322 History

bull 10 Initial version supporting CXX R11 R29 T11 and T29 messages only

bull 20 Add optional bus ID prefix to record types

bull 30 Add support for comment commands and clarify documentation inconsistencies

255

Open Vehicles

323 Specification

CRTD files are UTF-8 text files using LF or CR+LF line termination to separate each record

ltcrtd-filegt = ltcrtd-recordgt [CR] LF

The records are formatted as follows

ltcrtd-recordgt = lttimestampgt ltspacegt ltcrtd-typegt lttimestampgt = ltjuliansecondsgt [ ltmillisecondsgt| ltmicrosecondsgt ] ltjuliansecondsgt = ltdigtigt ltdigitgt ltmillisecondsgt = ltdigitgt ltdigitgt ltdigitgtltmicrosecondsgt = ltdigitgt ltdigitgt ltdigitgt ltdigitgt ltdigitgt ltdigitgt ltdigitgt = [ 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |8 | 9 ] lthexdigitgt = [ ltdigitgt

A | B | C | D | E | F | a | b | c | d | e | f ]

ltspacegt = ASCII character 32 decimal (0x20 hex)

ltcrtd-typegt = [ ltcrtd-commentgt | ltcrtd-transmitgt | ltcrtd-receivegt ]

ltcrtd-commentgt = CXX ltspacegt lttextual-commentgt

ltcrtd-receivegt = R11 ltspacegt ltrxtx-datagt

ltbusgtR11 ltspacegt ltrxtx-datagtR29 ltspacegt ltrxtx-datagtltbusgtR29 ltspacegt ltrxtx-datagt

ltcrtd-transmitgt = T11 ltspacegt ltrxtx-datagt

ltbusgtT11 ltspacegt ltrxtx-datagtT29 ltspacegt ltrxtx-datagtltbusgtT29 ltspacegt ltrxtx-datagt

ltbusgt = ltdigitgt ltdigitgt

ltrxtx-datagt = ltcan-idgt ltspacegt ltcan-bytegt ltcan-idgt = lthexdigitgt lthexdigitgt ] ltcan-bytegt =lthexdigitgt [ lthexdigitgt ]

324 Timestamps

Timestamps can be provided in either millisecond or microsecond precision It is recommended that they be based onthe julian seconds in UTC but there is no specific requirement for that It is suggested that a comment may optionallybe placed at the start of the file to describe the timezone The timestamps should however increase monotonically inthe file (ie time flows forward with subsequent records)

If the timestamp contains 3 digits after the decimal point it should be consider millisecond precision and handledappropriately Similarly if the timestamp contains 6 digits after the decimal point it should be considered microsecondprecision

325 Case Independence

CAN IDs and data bytes are in case-independent hex and may or may not be padded with leading zeros CRTDprocessors should be as flexible as possible in their handling of this

256 Chapter 32 CRTD CAN Log Format

Open Vehicles

326 CAN Bus Designation

Record types may optionally be prefixed by the CAN bus number (1 n) If no bus number is provided 1 shouldbe assumed

327 Data bytes

The number of data bytes is limited by the CAN specification to a maximum of 8 bytes Similarly the range ofacceptable CAN IDs is limited by the 11bit 29bit encoding in the CAN protocol specification

328 Record Types

Each record can be one of a comment receive or transmit data Other record types should be discarded to allow newrecord types to be introduced without breaking existing processors

3281 Comment Records

Comment records start with the letter lsquoCrsquo and the record type has two characters following to denote the sub-typeThe rest of the record is to be considered a comment (or data for the command)

The following comment record types are defined

bull CXX General textual comment

bull CER An indication of a (usually recoverable) error

bull CST Periodical statistics

bull CEV An indication of an event

bull CVR Version of CRTD protocol adhered to (with version number as text comment)

and the following command record types are defined

bull CBC A command to configure a CAN bus

bull CDP A command to pause the transmission of messages

bull CDR A command to resume the transmission of messages

bull CFC A command to clear all filters for this connection

bull CFA A command to add a filter for this connection

Here are some examples

169971289 CXX Info Typecrtd Pathsdcan3crtd Filter30-ffffffffrarr˓VehicleTSHK19292299819 CEV vehiclealert this is a textual vehicle alert198923283738 CST intr=0 rxpkt=0 txpkt=0 errflags=0 rxerr=0 txerr=0 rxovr=0 txovr=0rarr˓txdelay=0 wdgreset=02783384726 CER intr=0 rxpkt=0 txpkt=0 errflags=0 rxerr=0 txerr=0 rxovr=0 txovr=0rarr˓txdelay=0 wdgreset=0

326 CAN Bus Designation 257

Open Vehicles

3282 Command Record CBC - Configure a CAN bus

The CBC command is used to configure a CAN bus It should be prefixed with the bus ID in the usual way or defaultto bus 1 if not defined

The command should have the following space separated parameters

bull mode either L for listen or A for active

bull speed the baud rate of the CAN bus

3283 Command Record CDP - Pause transmission

The CDP command is used to pause transmission of messages for this connection Upon receiving this commandthe device producing CRTD logs should henceforth discard those logs and not transmit them to this connection untilresumed

3284 Command Record CDR - Resume transmission

The CDR command is used to resume transmission of messages for this connection It clears the condition previouslyset by the CDP command

3285 Command Record CFC - Clear filters

The CFC command is used to clear the message filters for this connection

By default connections receive all messages for all CAN buses and that is indicated by the filter list being initiallyempty This command resets the filters to this default condition

Note that external to the per-message filters CAN data sources may also have incoming filters that apply to all incom-ing data (regardless of the logging destination) These incoming filters are not affected by this

3286 Command Record CFA - Add a filter

The CFA command is used to add a filter to the list of message filters for this connection If one or more filters aredefined only messages matching those filters will be forwarded

The command should have the filter passed as a single parameter

bull filter the filter to add

Filters are formatted as

Filter = ltbusgt | ltidgt[-ltidgt] | ltbusgtltidgt[-ltidgt]

For example

bull 22a0-37f for bus 2 IDs 0x2a0 - 0x37f

bull 10-37f for bus 1 IDs 0x000 - 0x37f

bull 3 for bus 3 all messages

bull 100-200 for bus 1 IDs 0x100 - 0x200

258 Chapter 32 CRTD CAN Log Format

Open Vehicles

3287 Received Frame Record

Received frame records describe a frame received from the CAN bus and start with the letter lsquoRrsquo Two types aredefined

bull R11 A standard 11bit ID CAN frame

bull R29 An extended 29bit ID CAN frame

The record type is followed by the frame ID (in hexadecimal) and then up to 8 bytes of CAN frame data

Here are some examples

1542473901020305 1R11 213 00 00 00 00 c0 01 00 001542473901020970 2R11 318 92 0b 13 10 11 3a 00 001542473901021259 2R11 308 00 ff f6 a6 06 03 80 001542473901021560 2R11 408 001542473901030341 1R11 358 18 08 20 00 00 00 00 201542473901034872 2R11 418 801542473901035514 1R11 408 101542473901036694 3R11 41C 101542473901040289 R11 428 00 301542473901042516 2R11 168 e0 7f 70 00 ff ff ff1542473901042809 2R11 27E c0 c0 c0 c0 00 00 00 001542473901043073 1R11 248 29 29 0f bc 01 10 00

3288 Transmitted Frame Record

Transmitted frame records describe a frame transmitted onto the CAN bus and start with the letter lsquoTrsquo Two types aredefined

bull T11 A standard 11bit ID CAN frame

bull T29 An extended 29bit ID CAN frame

The record type is followed by the frame ID (in hexadecimal) and then up to 8 bytes of CAN frame data

Here are some examples

1542473901020305 1T11 213 00 00 00 00 c0 01 00 001542473901020970 2T11 318 92 0b 13 10 11 3a 00 001542473901021259 2T11 308 00 ff f6 a6 06 03 80 001542473901021560 2T11 408 001542473901030341 1T11 358 18 08 20 00 00 00 00 201542473901034872 2T11 418 801542473901035514 1T11 408 101542473901036694 3T11 41C 101542473901040289 T11 428 00 301542473901042516 2T11 168 e0 7f 70 00 ff ff ff1542473901042809 2T11 27E c0 c0 c0 c0 00 00 00 001542473901043073 1T11 248 29 29 0f bc 01 10 00

329 Conclusions

The CRTD format is intended to be very simple to process either by automated code or humans manually It can beloaded into text editors for manipulation (search replace etc) and easily processed by command line tools such aslsquocutrsquo lsquogreprsquo lsquoawkrsquo etc

329 Conclusions 259

Open Vehicles

260 Chapter 32 CRTD CAN Log Format

CHAPTER 33

Web Framework amp Plugins

331 TLDR Examples

The following examples include their documentation in the HTML page and source Read the source and install themas plugins (see below) to see how they work

3311 Metric Displays

OVMS V3 is based on metrics Metrics can be single numerical or textual values or complex values like sets and arraysThe web framework keeps all metrics in a global object which can be read simply by eg metrics[vbsoc]

Metrics updates (as well as other updates) are sent to all DOM elements having the receiver class To hook intothese updates simply add an event listener for msgmetrics

Listening to the event is not necessary though if all you need is some metrics display This is covered by the metricwidget class family as shown here

261

Open Vehicles

Single Values amp Charts

The following example covers

bull Text (String) displays

bull Number displays

bull Progress bars (horizontal light weight bar charts)

bull Gauges

bull Charts

Gauges amp charts use the HighCharts library which is included in the web server The other widgets are simple standardBootstrap widgets extended by an automatic metrics value update mechanism

Highcharts is a highly versatile charting system For inspiration have a look at

bull httpswwwhighchartscomdemo

bull httpswwwhighchartscomdocs

Wersquore using styled mode so some options donrsquot apply but everything can be styled by standard CSS

Install the example as a web page plugin

metricshtm (hint right click save as)

262 Chapter 33 Web Framework amp Plugins

Open Vehicles

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltdiv class=panel panel-primarygt6 ltdiv class=panel-headinggtMetrics Displays TestDemoltdivgt7 ltdiv class=panel-bodygt8

9 ltpgtOVMS V3 is based on metrics Metrics can be single numerical or textual valuesrarr˓or complex values

10 like sets and arrays The web framework keeps all metrics in a global objectrarr˓which can be read

11 simply by eg ltcodegtmetrics[vbsoc]ltcodegtltpgt12

13 ltpgtMetrics updates (as well as other updates) are sent to all DOM elements havingrarr˓the

14 ltcodegtreceiverltcodegt class To hook into these updates simply add an eventrarr˓listener for

15 ltcodegtmsgmetricsltcodegt Listening to the event is not necessary if all yourarr˓need is some metrics

16 display This is covered by the ltcodegtmetricltcodegt class family as shown hererarr˓ltpgt

17

18 ltpgt19 ltbutton type=button class=btn btn-default action-gendatagtGenerate random

rarr˓dataltbuttongt20 ltbutton type=button class=btn btn-default action-showsrcgtShow page sourcelt

rarr˓buttongt21 ltpgt22

23 lthrgt24

25 ltdiv class=receivergt26

27 lth4gtBasic usagelth4gt28

29 ltpgtAll elements of class ltcodegtmetricltcodegt in a ltcodegtreceiverltcodegt arerarr˓checked for the

30 ltcodegtdata-metricltcodegt attribute If no specific metric class is given therarr˓metric value

31 is simply set as the element text ltspan class=metric data-metric=mnetrarr˓providergtltspangt

32 is your current network providerltpgt33

34 lth4gtText ampamp Numberlth4gt35

36 ltpgtltcodegtnumberltcodegt ampamp ltcodegttextltcodegt displays get the metric valuerarr˓set in their child of

37 class ltcodegtvalueltcodegt They may additionally have labels and units ltcodegtrarr˓data-precltcodegt can

38 be used on ltcodegtnumberltcodegt to set the precision ltcodegtdata-scaleltcodegtrarr˓to scale the raw

39 values by a factor They have fixed min widths and float by default so yourarr˓can simply put

40 multiple displays into the same containerltpgt41

42 ltdiv class=clearfixgt

(continues on next page)

331 TLDR Examples 263

Open Vehicles

(continued from previous page)

43 ltdiv class=metric number data-metric=vethrottle data-prec=0gt44 ltspan class=labelgtThrottleltspangt45 ltspan class=valuegtltspangt46 ltspan class=unitgtltspangt47 ltdivgt48 ltdiv class=metric number data-metric=vb12vvoltageref data-prec=1gt49 ltspan class=valuegtltspangt50 ltspan class=unitgtVltsubgtrefltsubgtltspangt51 ltdivgt52 ltdiv class=metric text data-metric=mnetprovidergt53 ltspan class=labelgtNetworkltspangt54 ltspan class=valuegtltspangt55 ltdivgt56 ltdivgt57

58 lth4gtProgress Barlth4gt59

60 ltpgtBootstrap ltcodegtprogressltcodegt bars can be used as lightweight graphicalrarr˓indicators

61 Labels and units are available also ltcodegtdata-precltcodegt and ltcodegtdata-rarr˓scaleltcodegt

62 Again all you need is a bit of markupltpgt63

64 ltdiv class=clearfixgt65 ltdiv class=metric progress data-metric=vethrottle data-prec=0gt66 ltdiv class=progress-bar progress-bar-success value-low text-left role=

rarr˓progressbar67 aria-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gt68 ltdivgt69 ltspan class=labelgtThrottleltspangt70 ltspan class=valuegtltspangt71 ltspan class=unitgtltspangt72 ltdivgt73 ltdivgt74 ltdivgt75 ltdiv class=metric progress data-metric=vb12vvoltageref data-prec=1gt76 ltdiv class=progress-bar progress-bar-info value-low text-left role=

rarr˓progressbar77 aria-valuenow=0 aria-valuemin=5 aria-valuemax=15 style=width0gt78 ltdivgt79 ltspan class=labelgt12V refltspangt80 ltspan class=valuegtltspangt81 ltspan class=unitgtVltspangt82 ltdivgt83 ltdivgt84 ltdivgt85 ltdivgt86

87 lth4gtGauges ampamp Chartslth4gt88

89 ltpgtThe OVMS web framework has builtin support for the highly versatile ltbgtrarr˓Highcharts libraryltbgt

90 with loads of chart types and options ltcodegtchartltcodegt metric examplesltpgt91

92 ltdiv class=rowgt93 ltdiv class=col-sm-6gt94 ltdiv class=metric chart data-metric=vethrottle style=height220pxgt

(continues on next page)

264 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

95 ltdiv class=chart-box gaugechart id=throttle-gaugegt96 ltdivgt97 ltdivgt98 ltdiv class=col-sm-6gt99 ltdiv class=metric chart data-metric=vbcvoltagevbcvoltagemin

rarr˓style=height220pxgt100 ltdiv class=chart-box barchart id=cell-voltagesgt101 ltdivgt102 ltdivgt103 ltdivgt104

105 ltpgtltbutton type=button class=btn btn-default action-gendatagtGenerate randomrarr˓dataltbuttongtltpgt

106

107 ltpgtFor charts a little bit of scripting is necessary108 The scripts for these charts contain the chart configuration part of which

rarr˓is the update109 function you need to define The update function translates metrics data into

rarr˓chart data110 This is trivial for single values like the throttle the cell voltage chart

rarr˓is an example111 on basic array processingltpgt112

113 ltpgtAlso while charts ltemgtcanltemgt be defined with few options youll ltemgtloverarr˓ltemgt to explore

114 all the features and fine tuning options provided by Highcharts Forrarr˓inspiration

115 have a look at the lta target=_blank href=httpswwwhighchartscomdemogtrarr˓Highcharts demosltagt

116 and the lta target=_blank href=httpswwwhighchartscomdocsgtHighchartsrarr˓documentationltagt

117 Were using lta target=_blank href=httpswwwhighchartscomdocschart-rarr˓design-and-stylestyle-by-cssgt

118 styled modeltagt so some options dont apply but everything can be styled byrarr˓standard CSSltpgt

119

120 ltdivgt121

122 ltdivgt123 ltdivgt124

125 ltscriptgt126 (function()127

128 Get page source before chart rendering 129 var pagesrc = $(main)html()130

131 Init throttle gauge 132 $(throttle-gauge)chart(133 chart 134 type gauge135 spacing [0 0 0 0]136 margin [0 0 0 0]137 animation duration 500 easing easeOutExpo 138 139 title text Throttle verticalAlign middle y 75 140 credits enabled false

(continues on next page)

331 TLDR Examples 265

Open Vehicles

(continued from previous page)

141 tooltip enabled false 142 plotOptions 143 gauge dataLabels enabled false overshoot 1 144 145 pane [146 startAngle -125 endAngle 125 size 100 center [50 60]147 ]148 yAxis [149 title text 150 className throttle151 reversed false152 min 0 max 100153 plotBands [154 from 0 to 60 className green-band 155 from 60 to 80 className yellow-band 156 from 80 to 100 className red-band 157 ]158 minorTickInterval auto minorTickLength 5 minorTickPosition inside159 tickPixelInterval 40 tickPosition inside tickLength 13160 labels step 2 distance -28 x 0 y 5 zIndex 2 161 ]162 series [163 name Throttle data [0]164 className throttle165 animation duration 0 166 pivot radius 10 167 dial radius 88 topWidth 1 baseLength 20 baseWidth 10

rarr˓rearLength 20 168 ]169 Update method 170 onUpdate function(update) 171 Create gauge data set from metric172 var data = [ metrics[vethrottle] ]173 Update chart174 thisseries[0]setData(data)175 176 )177

178 Init cell voltages chart 179 $(cell-voltages)chart(180 chart 181 type column182 animation duration 500 easing easeOutExpo 183 184 title text Cell Voltages 185 credits enabled false 186 tooltip 187 enabled true188 shared true189 headerFormat Cell pointkeyltbrgt190 pointFormat seriesname ltbgtpointyltbgtltbrgt191 valueSuffix V192 193 legend enabled true 194 xAxis 195 categories []196

(continues on next page)

266 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

197 yAxis [198 title text null 199 labels format value2fV 200 tickAmount 4 startOnTick false endOnTick false201 floor 33 ceiling 42202 minorTickInterval auto203 ]204 series [205 name Current data []206 className cell-voltage207 animation duration 0 208 209 name Minimum data []210 className cell-voltage-min211 animation duration 0 212 ]213 Update method 214 onUpdate function(update) 215 Note the update parameter contains the actual update set216 You can use this to reduce chart updates to the actual changes217 For this demo we just use the global metrics object218 var219 m_vlt = metrics[vbcvoltage] || []220 m_min = metrics[vbcvoltagemin] || []221 Create categories (cell numbers) amp rounded values222 var cat = [] val0 = [] val1 = []223 for (var i = 0 i lt m_vltlength i++) 224 catpush(i+1)225 val0push(Number((m_vlt[i]||0)toFixed(3)))226 val1push(Number((m_min[i]||0)toFixed(3)))227 228 Update chart229 thisxAxis[0]setCategories(cat)230 thisseries[0]setData(val0)231 thisseries[1]setData(val1)232 233 )234

235 Test metrics generator 236 $(action-gendata)on(click function() 237 var td = 238 td[mnetprovider] = [hologramVodafoneTelekom][Mathfloor(Math

rarr˓random()3)]239 td[vethrottle] = Mathrandom() 100240 td[vb12vvoltageref] = 10 + Mathrandom() 4241 var m_vlt = [] m_min = []242 for (var i = 1 i lt= 16 i++) 243 m_vltpush(36 + Mathrandom() 05)244 m_minpush(34 + Mathrandom() 02)245 246 td[vbcvoltage] = m_vlt247 td[vbcvoltagemin] = m_min248 $(receiver)trigger(msgmetrics $extend(metrics td))249 )250

251 Display page source 252 $(action-showsrc)on(click function()

(continues on next page)

331 TLDR Examples 267

Open Vehicles

(continued from previous page)

253 $(ltdivgt)dialog(254 title Source Code255 body ltpre style=font-size85 heightcalc(100vh - 230px)gt256 + encode_html(pagesrc) + ltpregt257 size lg258 )259 )260

261 )()262 ltscriptgt

Vector Tables

Some metrics for example the battery cell voltages or the TPMS tyre health data may contain vectors of arbitrarysize Besides rendering into charts these can also be displayed by their textual values in form of a table

The following example shows a live view of the battery cell voltages along with their recorded minimum maximummaximum deviation and current warningalert state Alert states 0-2 are translated into icons

The metric table widget uses the DataTables library which is included in the web server The DataTables Javascriptlibrary offers a wide range of options to create tabular views into datasets

Install the example as a web page plugin

metrics-tablehtm (hint right click save as)

1 lt--2 Web UI page plugin DataTables metrics widget demonstration3 --gt4

5 ltstylegt6 td i

(continues on next page)

268 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

7 font-style normal8 font-size 1409 line-height 90

10 font-weight bold11 12 td iwarning color orange 13 td idanger color red 14 ltstylegt15

16

17 ltdiv class=panel panel-primary panel-single receiver id=my-receivergt18 ltdiv class=panel-headinggtMetrics Table Widget Exampleltdivgt19 ltdiv class=panel-bodygt20

21 ltpgtThe following table shows a live view of the battery cell voltages along withrarr˓their recorded

22 minimum maximum maximum deviation and current warningalert stateltpgt23 ltpgtTry resizing the window or using a mobile phone to see how the table adapts to

rarr˓the screen24 width The table will also keep the selected sorting over data updatesltpgt25 ltpgtHint if you dont have live battery cell data click the generator button to

rarr˓create26 some random values The random data is only generated in your browser not on

rarr˓the moduleltpgt27

28 ltdiv class=metric table29 data-metric=vbcvoltagevbcvoltageminvbcvoltagemaxvbcvoltage

rarr˓devmaxvbcvoltagealertgt30 lttable class=table table-striped table-bordered table-hover id=v-table gt31 ltdivgt32

33 ltpgtSee lta target=_blank href=httpsdatatablesnetmanualgtDataTables manualrarr˓ltagt for all

34 options and API methods availableltpgt35

36 ltdivgt37 ltdiv class=panel-footergt38 ltpgtltbutton type=button class=btn btn-default action-gendatagtGenerate random

rarr˓dataltbuttongtltpgt39 ltdivgt40 ltdivgt41

42

43 ltscriptgt44 (function()45

46 Utilities47 var alertMap = 48 0 49 1 lti class=warninggtltigt50 2 lti class=dangergtltigt51 52

53 function fmtCode(value map) 54 return (map[value] == undefined) map[value] null55 56 function fmtNumber(value prec)

(continues on next page)

331 TLDR Examples 269

Open Vehicles

(continued from previous page)

57 return (value == undefined) Number(value)toFixed(prec) null58 59

60 Init table61 $(v-table)table(62 responsive true63 paging true64 searching false65 info false66 autoWidth false67 columns [68 title className dt-body-center width 6

rarr˓responsivePriority 1 69 title Voltage className dt-body-right width 22

rarr˓responsivePriority 3 70 title Minimum className dt-body-right width 22

rarr˓responsivePriority 4 71 title Maximum className dt-body-right width 22

rarr˓responsivePriority 5 72 title MaxDev className dt-body-right width 22

rarr˓responsivePriority 2 73 title Alert className dt-body-center width 6

rarr˓responsivePriority 1 74 ]75 rowId 076 onUpdate function(update) 77 Get vector metrics to display78 var v = [79 metrics[vbcvoltage] || []80 metrics[vbcvoltagemin] || []81 metrics[vbcvoltagemax] || []82 metrics[vbcvoltagedevmax] || []83 metrics[vbcvoltagealert] || []84 ]85 var lcnt = 086 vmap(el =gt lcnt = Mathmax(lcnt ellength))87 Transpose vectors to columns88 var l d = []89 for (l = 0 l lt lcnt l++) 90 dpush([91 l+192 fmtNumber(v[0][l] 2)93 fmtNumber(v[1][l] 2)94 fmtNumber(v[2][l] 2)95 fmtNumber(v[3][l] 3)96 fmtCode(v[4][l] alertMap)97 ])98 99 Display new data

100 thisclear()rowsadd(d)draw()101 102 )103

104

105 Test data generator106 $(action-gendata)on(click function() 107 var td =

(continues on next page)

270 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

108 var m_vlt = [] m_min = [] m_max = [] m_devmax = [] m_alert = []109 for (var i = 1 i lt= 16 i++) 110 m_vltpush(36 + Mathrandom() 05)111 m_minpush(34 + Mathrandom() 02)112 m_maxpush(38 + Mathrandom() 02)113 m_devmaxpush(-02 + Mathrandom() 04)114 m_alertpush(Mathfloor(Mathrandom() 3))115 116 td[vbcvoltage] = m_vlt117 td[vbcvoltagemin] = m_min118 td[vbcvoltagemax] = m_max119 td[vbcvoltagedevmax] = m_devmax120 td[vbcvoltagealert] = m_alert121 $(receiver)trigger(msgmetrics $extend(metrics td))122 )123

124 )()125 ltscriptgt

3312 Command Buttons amp Monitors

commandshtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltstylegt6 h3 7 margin-top 40px8 margin-bottom 20px9

10 ltstylegt11

12 ltdiv class=panel panel-primarygt13 ltdiv class=panel-headinggtCommands ampamp Monitorsltdivgt14 ltdiv class=panel-bodygt15

16 ltpgtCommand execution is only allowed for an authorized session The command API will17 output Unauthorized and a Login button as necessary The login state is also18 available in the global variable ltcodegtloggedinltcodegt To send the user to the19 login page and return to the current page after login call ltcodegtlogin()ltcodegt

rarr˓ltpgt20

21 ltpgt22 ltbutton type=button class=btn btn-default action-login onclick=login()gtLogin

rarr˓ltbuttongt23 ltbutton type=button class=btn btn-default action-logout onclick=logout()gt

rarr˓Logoutltbuttongt24 ltpgt25

26 ltscriptgt27 $(action-login)prop(disabled loggedin)28 $(action-logout)prop(disabled loggedin)29 ltscriptgt

(continues on next page)

331 TLDR Examples 271

Open Vehicles

(continued from previous page)

30

31

32 lth3gtCommand Execution on Loadlth3gt33

34 ltpgtTo execute a command automatically on page load simply add the ltcodegtmonitorltrarr˓codegt class

35 to an output element set ltcodegtdata-updcmdltcodegt to the command to be executedrarr˓and

36 ltcodegtdata-updcntltcodegt to 1ltpgt37

38 ltpre class=monitor data-updcmd=boot status data-updcnt=1gtFetching bootrarr˓statusltpregt

39

40 ltpgtOutput elements typically are ltcodegtsampltcodegt or ltcodegtpreltcodegt as commands41 normally output formatted plain text but any element can be used ltcodegtsamplt

rarr˓codegt42 by default compresses white space and has no visible area while ltcodegtpreltcodegt43 is visible and preserves all spacingltpgt44

45 ltpgtltcodegtupdcntltcodegt will count down to zero and stop or run indefinitely ifrarr˓started

46 below zero The execution interval can be given in ltcodegtdata-updintltcodegt (inrarr˓seconds)

47 You can set the data attributes any time using jQuery all monitors are checkedrarr˓and

48 updated by the framework once per secondltpgt49

50

51 lth3gtCommand Execution on Eventslth3gt52

53 ltpgtTo automatically trigger a monitor update on OVMS events additionally set the54 ltcodegtdata-eventsltcodegt attribute to a regular expression matching the event(s)

rarr˓of55 interest This example monitor lists the active network channels and automatically56 updates on all server connection eventsltpgt57

58 ltpgtltpre class=monitor59 data-events=server(connect|open|close|stop)60 data-updcmd=network list61 data-updcnt=1gtltpregtltpgt62

63 ltpgt64 Try65 lta class=btn btn-default onclick=windowopen( _blank width=400

rarr˓height=500)gtOpen new windowltagt66 lta class=btn btn-default href= data-cmd=server v2 stopgtStop V2 serverltagt67 lta class=btn btn-default href= data-cmd=server v2 startgtStart V2 serverltagt68 lta class=btn btn-default href= data-cmd=event raise serverfakeopengtSend

rarr˓fake eventltagt69 ltpgt70

71

72 lth3gtCommand Buttonslth3gt73

74 ltpgtA bootstrap button has the base class ltcodegtbtnltcodegt Add the command torarr˓execute

75 as attribute ltcodegtdata-cmdltcodegt and optionally the output element as(continues on next page)

272 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

76 ltcodegtdata-targetltcodegt and youre doneltpgt77

78 ltdiv class=rowgt79

80 ltdiv class=col-sm-6gt81 ltbutton type=button class=btn btn-default data-target=out1 data-cmd=

rarr˓wifi statusgt82 Wifi Status rarr ltcodegtampltsampampgtltcodegt83 ltbuttongt84 ltsamp id=out1 gt85 ltdivgt86

87 ltdiv class=col-sm-6gt88 ltbutton type=button class=btn btn-default data-target=out2 data-cmd=

rarr˓wifi statusgt89 Wifi Status rarr ltcodegtampltpreampgtltcodegt90 ltbuttongt91 ltpre id=out2 gt92 ltdivgt93

94 ltdivgt95

96 ltpgtAdd class ltcodegtsamp-inlineltcodegt or wrap in a ltcodegtullist-inlineltcodegt torarr˓place

97 the output element on the same line with the button Prefix the target with a +rarr˓to

98 append to itltpgt99

100 ltpgt101 External 12V power102 ltbutton type=button class=btn btn-info data-target=+out3 data-cmd=power

rarr˓ext12v ongtonltbuttongt103 ltbutton type=button class=btn btn-info data-target=+out3 data-cmd=power

rarr˓ext12v offgtoffltbuttongt104 ltsamp class=samp-inline id=out3 gt105 ltpgt106

107

108 lth3gtCombining Buttons ampamp Monitorslth3gt109

110 ltpgtBy combination of a button and a monitor you can let the button start a repeated111 execution of a command set ltcodegtdata-watchcntltcodegt on the button to the

rarr˓number of112 repetitions (default 0) and ltcodegtdata-watchintltcodegt to the interval in seconds113 (default 2)ltpgt114

115 ltpgt116 ltbutton type=button class=btn btn-default data-target=out4117 data-cmd=power cellular on data-watchcnt=-1 data-watchint=3gt118 Power on cellular modem ampamp get status updates every 3 seconds119 ltbuttongt120 ltpre class=monitor id=out4 data-updcmd=cellular status gt121 ltpgt122

123 ltpgtNote to stop a monitor set ltcodegtdata-updcntltcodegt to 0124 ltbutton type=button class=btn btn-default onclick=$(out4)data(updcnt

rarr˓0)gt(continues on next page)

331 TLDR Examples 273

Open Vehicles

(continued from previous page)

125 Stop updates126 ltbuttongtltpgt127

128

129 lth3gtExecute Javascriptlth3gt130

131 ltpgtTo execute Javascript code directly (ie without calling ltcodegtscript evalltrarr˓codegt)

132 simply exchange the ltcodegtdata-cmd data-updcmdltcodegt attribute by133 ltcodegtdata-js data-updjsltcodegt Exampleltpgt134

135 ltpgt136 ltbutton type=button class=btn btn-default data-target=out5137 data-js=JSONprint(OvmsConfigGetValues(vehicle))gt138 Show vehicle config139 ltbuttongt140 ltpre id=out5 gt141 ltpgt142

143 ltdivgt144 ltdivgt145

146

147 ltscriptgt148 (function()149 Show page source 150 var pagesrc = $(main)html()151 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +152 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)153 $(action-showsrc)on(click function() 154 $(ltdivgt)dialog(155 title Source Code156 body ltpre style=font-size85 heightcalc(100vh - 230px)gt157 + encode_html(pagesrc) + ltpregt158 size lg159 )160 )161 )()162 ltscriptgt

3313 Notifications

notificationshtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web file path eg sddevnotificationshtm5 - open in framework by eg httptest1localdevnotificationshtm6 --gt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtNotification TestDemoltdivgt

10 ltdiv class=panel-bodygt

(continues on next page)

274 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

11 lth4gtReceiverlth4gt12 lt--13 You can use data-subscriptions to preconfigure subscriptions14 Note types info error and alert get sent to all receivers15 --gt16 ltpre id=log class=receiver data-subscriptions=notifystreammyappgtIm

rarr˓preconfigured to receive notifystreammyappltpregt17 ltdivgt18 ltdiv class=panel-footergt19 ltdivgt20 ltlabel for=topicsgtTest commandltlabelgt21 ltinput type=text class=form-control font-monospace id=cmd value=notify

rarr˓raise text stream myappinput my first streamgt22 ltpgtJSON example ltcode class=autoselectgtnotify raise text stream myappinput

rarr˓myJSON streampi3141fib[1235813]ltcodegtltpgt23 ltbutton type=button class=btn btn-default id=action-execgtExecuteltbuttongt24 ltsamp id=cmdres gt25 ltdivgt26 ltdivgt27 ltlabel for=topicsgtTopic subscription (separate topics by space)ltlabelgt28 ltinput type=text class=form-control font-monospace id=topics value=

rarr˓notifystreammyappgt29 ltbutton type=button class=btn btn-default id=action-subgtSubltbuttongt30 ltbutton type=button class=btn btn-default id=action-unsubgtUnsubltbuttongt31 ltbutton type=button class=btn btn-default id=action-unsuballgtUnsub alllt

rarr˓buttongt32 ltdivgt33 ltdivgt34 ltdivgt35

36 ltscriptgt37

38 Receiver event handling39 $(log)on(msgnotify function(ev msg) 40 You normally should filter by typesubtype here eg41 if (subtypestartsWith(myapp)) 42 msg has type subtype and value43 Dump the msg into the receiver to show the structure44 $(this)text(JSONstringify(msg null 2))45

46 A convenient way to transport complex data is JSON47 To decode a JSON string use JSONparse()48 Note JSONparse() needs strict JSON syntax ie quoted names49 var payload50 try 51 payload = JSONparse(msgvalue)52 if (payload) 53 $(this)append(ltdivgtFound JSON payloadltdivgt)54 append($(ltdiv gt)text(JSONstringify(payload null 2))html())55 consolelog(payload)56 57 catch(e) 58 no JSON59 consolelog(e)60 61 )62

(continues on next page)

331 TLDR Examples 275

Open Vehicles

(continued from previous page)

63 Topic subscription can be done on page load using the data-subscriptions attribute64 andor on demand using the subscribe amp unsubscribe calls65 $(action-sub)on(click function(ev) 66 var topics = $(topics)val()67 $(log)subscribe(topics)text(added + topics)68 )69 The receiver remembers the subscriptions and does an auto unsubscribe on unload70 You can also unsubscribe topics dynamically Your data producer can check for71 active subscriptions using the MyNotifyHasReader() method72 $(action-unsub)on(click function(ev) 73 var topics = $(topics)val()74 $(log)unsubscribe(topics)text(removed + topics)75 )76 $(action-unsuball)on(click function(ev) 77 $(log)unsubscribe()text(removed all subscriptions)78 )79

80 Command handler81 $(action-exec)on(click function(ev) 82 var cmd = $(cmd)val()83 if (cmd) loadcmd(cmd cmdres)84 )85 $(cmd)on(keydown function(ev) 86 if (evwhich == 13) $(action-exec)trigger(click)87 )88

89 ltscriptgt

3314 Hook Plugins

hookshtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 --gt4

5 ltdiv class=panel panel-primarygt6 ltdiv class=panel-headinggtPage Hook Pluginsltdivgt7 ltdiv class=panel-bodygt8

9 ltpgtPlugins can provide pages on their own or extend existing pages To extend anrarr˓existing

10 page the page needs to support this by offering hook pointsltpgt11

12 ltpgtYou are not limited to the hook points for page modifications To insert yourrarr˓extensions

13 at arbitrary placesltpgt14 ltulgt15 ltligtinsert your extensions dynamically or with ltcodegtdisplaynoneltcodegtltligt16 ltligtregister a onetime handler for the ltcodegtloadltcodegt event on ltcodegtmainlt

rarr˓codegtltligt17 ltligtmove your extensions into place and show them from the event handlerltligt18 ltulgt19

20 ltpgtand yes youre also not limited to adding stuffltpgt(continues on next page)

276 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

21

22 lth3gtExamplelth3gt23

24 ltpgtThe following hook plugin adds a custom menu and some color to ltcodegthomeltcodegtrarr˓ltpgt

25

26 ltpre id=plugindisplay style=font-size85gtltpregt27

28 lth3gtAvailable Hookslth3gt29

30 ltpgtas of January 2019 This is work in progress if you miss a hook somewhererarr˓contact usltpgt

31

32 lttable class=table table-condensed font-monospacegt33 lttrgtltth colspan=2gtFrameworkltthgtlttrgt34 lttrgtlttdgt lttdgtlttdgthtmlpre headpost bodypost

rarr˓ lttdgtlttrgt35 lttrgtlttdgthome lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt36 lttrgtlttdgtdashboard lttdgtlttdgtbodypre

rarr˓ lttdgtlttrgt37 lttrgtlttdgtstatus lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt38 lttrgtlttdgtshell lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt39 lttrgtltth colspan=2gtRenault Twizyltthgtlttrgt40 lttrgtlttdgtxrtdrivemode lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt41 lttrgtlttdgtxrtscmon lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt42 lttablegt43

44 ltdivgt45 ltdivgt46

47 ltscriptgt48 (function()49 var pluginsrc = $(pluginsrc)html()50 $(plugindisplay)html(encode_html(pluginsrcsubstr(1)))51 )()52 ltscriptgt53

54 ltdiv id=pluginsrc style=displaynonegt55 lt--56 Hook plugin for homebodypre57 - custom coloring of menu titles58 - add custom menu Test Demo after Main59 --gt60

61 ltstylegt62 menu legend 63 color brown64 65 ltstylegt66

67 ltfieldset class=menu id=fieldset-menu-demo1 style=displaynonegt68 ltlegendgtTest Demoltlegendgt

(continues on next page)

331 TLDR Examples 277

Open Vehicles

(continued from previous page)

69 ltul class=list-inlinegt70 ltligtlta class=btn btn-default href=usrdemometrics target=maingtMetrics lt

rarr˓agtltligt71 ltligtlta class=btn btn-info href=logslog target=_blankgtOpen Log File ltagtlt

rarr˓ligt72 ltulgt73 ltfieldsetgt74

75 ltscriptgt76 $(main)one(load function(ev) 77 $(fieldset-menu-demo1)insertAfter(fieldset-menu-main)show()78 )79 ltscriptgt80 ltdivgt

3315 Solid Gauges

solidgaugehtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltstylegt6 solidgauge highcharts-yaxis-grid highcharts-grid-line7 solidgauge highcharts-yaxis-grid highcharts-minor-grid-line 8 display none9

10 solidgauge highcharts-pane 11 fill eee12 fill-opacity 113 stroke aaa14 stroke-width 2px15 16 night solidgauge highcharts-pane 17 fill b1b1b118 stroke b1b1b119 20 solidgauge highcharts-point 21 transition fill 500ms stroke 500ms see stops styles note 22 23 throttle-gauge highcharts-color-0 24 fill eee initial colors = pane for smooth fade in 25 stroke aaa26 fill-opacity 0827 stroke-width 3px28 stroke-opacity 0529 30 rpm-gauge highcharts-color-0 31 fill 55e32 stroke none33 34 ltstylegt35

36 ltdiv class=panel panel-primarygt

(continues on next page)

278 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

37 ltdiv class=panel-headinggtSolid Gaugeltdivgt38 ltdiv class=panel-bodygt39

40 ltdiv class=receivergt41

42 ltdiv class=rowgt43 ltdiv class=col-sm-6gt44 ltdiv class=metric chart data-metric=vethrottle style=height220pxgt45 ltdiv class=chart-box solidgauge id=throttle-gaugegt46 ltdivgt47 ltpgt48 Note stops dont work by default in styled mode This example includes a

rarr˓simple redraw49 event callback that applies styles from the stops To get a smooth color

rarr˓transition50 the CSS transition time needs to be equal to the chart animation time51 ltpgt52 ltdivgt53 ltdiv class=col-sm-6gt54 ltdiv class=metric chart data-metric=vmrpm style=height220pxgt55 ltdiv class=chart-box solidgauge gaugechart id=rpm-gaugegt56 ltdivgt57 ltpgt58 Note the ltcodegtgaugechartltcodegt CSS class pulls in the default styling

rarr˓for the bands59 labels and ticks here You can also copy those CSS rules from ltcodegtovms

rarr˓cssltcodegt60 and do your own styling61 ltpgt62 ltdivgt63 ltdivgt64

65 ltpgtltbutton type=button class=btn btn-default action-gendatagtGenerate randomrarr˓dataltbuttongtltpgt

66

67 ltdivgt68

69 ltdivgt70 ltdivgt71

72 ltscriptgt73 (function()74

75 Show page source 76 var pagesrc = $(main)html()77 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +78 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)79 $(action-showsrc)on(click function() 80 $(ltdivgt)dialog(81 title Source Code82 body ltpre style=font-size85 heightcalc(100vh - 230px)gt83 + encode_html(pagesrc) + ltpregt84 size lg85 )86 )87

(continues on next page)

331 TLDR Examples 279

Open Vehicles

(continued from previous page)

88 Init throttle gauge 89 $(throttle-gauge)chart(90 chart 91 type solidgauge92 spacing [0 0 0 0]93 margin [0 0 0 0]94 animation duration 500 easing easeOutExpo 95 events 96 Apply stops styles on redraw97 redraw function(ev) 98 var y = thisseries[0]yData[0] $pt = $(thisrenderTo)find(highcharts-

rarr˓point)99 $map(thisyAxis[0]stops function(stop) if (y gt= stop[0]) $pt

rarr˓css(stop[1]) )100 101 102 103 title text Throttle verticalAlign middle y 75 104 credits enabled false 105 tooltip enabled false 106 plotOptions 107 solidgauge dataLabels enabled false overshoot 1 108 109 pane [110 startAngle -90 endAngle 90 size 140 center [50 85]111 background innerRadius 60 outerRadius 100 shape arc 112 ]113 yAxis [114 title text 115 className throttle116 reversed false117 min 0 max 100118 stops [119 [0 fill afa stroke 4f4 ]120 [50 fill ffa stroke ff4 ]121 [80 fill faa stroke f44 ]122 ]123 tickPixelInterval 40 tickPosition inside tickLength 13124 labels step 2 distance 10 x 0 y 0 zIndex 2 125 ]126 series [127 name Throttle data [40]128 className throttle129 animation duration 0 130 ]131 Update method 132 onUpdate function(update) 133 Create gauge data set from metric134 var data = [ metrics[vethrottle] ]135 Update chart136 thisseries[0]setData(data)137 138 )139

140 Init rpm gauge 141 $(rpm-gauge)chart(142 chart

(continues on next page)

280 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

143 type solidgauge144 spacing [0 0 0 0]145 margin [0 0 0 0]146 animation duration 500 easing easeOutExpo 147 148 title text RPM verticalAlign middle y 75 149 credits enabled false 150 tooltip enabled false 151 plotOptions 152 solidgauge dataLabels enabled false overshoot 1 153 154 pane [155 startAngle -90 endAngle 90 size 140 center [50 85]156 background innerRadius 70 outerRadius 100 shape arc 157 ]158 yAxis [159 title text rpm 160 className rpm161 reversed false162 min 0 max 11000163 plotBands [164 from 0 to 7000 className green-band 165 from 7000 to 9000 className yellow-band 166 from 9000 to 11000 className red-band 167 ]168 minorTickInterval auto minorTickLength 5 minorTickPosition inside169 tickPixelInterval 40 tickPosition inside tickLength 10170 labels step 2 distance 10 x 0 y 0 zIndex 2 171 ]172 series [173 name RPM data [4500]174 className rpm175 animation duration 0 176 innerRadius 72177 radius 92178 ]179 Update method 180 onUpdate function(update) 181 Create gauge data set from metric182 var data = [ metrics[vmrpm] ]183 Update chart184 thisseries[0]setData(data)185 186 )187

188 Test metrics generator 189 $(action-gendata)on(click function() 190 var td = 191 td[vethrottle] = Mathrandom() 100192 td[vmrpm] = Mathrandom() 11000193 $(receiver)trigger(msgmetrics $extend(metrics td))194 )195

196 )()197 ltscriptgt

331 TLDR Examples 281

Open Vehicles

3316 Command Streaming

loadcmdhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltdiv class=panel panel-primarygt6 ltdiv class=panel-headinggtAsynchronous Command Streamingltdivgt7 ltdiv class=panel-bodygt8

9 lth3gtSynopsislth3gt10

11 ltp class=leadgtltcodegt[jqxhr=] loadcmd(command [target] [filter] [timeout])ltrarr˓codegtltpgt

12

13 ltpgtThe ltcodegtloadcmd()ltcodegt function executes a shell command or evaluatesrarr˓javascript

14 code with asynchronous streaming of the output into a target element or onto ararr˓functionltpgt

15

16

17 lth3gtBasic Usagelth3gt18

19 ltpgtAs this is the underlying function for command buttons basic usage20 is very similar but fully scriptableltpgt21

22 ltpgt23 ltbutton type=button class=btn btn-default onclick=loadcmd(boot status

rarr˓out1)gt24 Show boot status25 ltbuttongt26 ltpgt27 ltpre id=out1 gt28

29 ltpgtAs with command buttons you can append the output by prefixing the target30 selector with + You can omit the output by passing null as the target If

rarr˓target31 is a DOM element loadcmd automatically sets the ltcodegtloadingltcodegt class on

rarr˓the32 target while the command is processedltpgt33

34 ltpgtThe target elements min-height is automatically fixed to the current height35 of the target before the output is set This avoids page layout jumps when36 reusing a target for commandsltpgt37

38 ltpgtIf the target is scrollable and the content exceeds the visible area the39 element is automatically scrolled to show the new content unless the user has40 done a manual scrolling on the elementltpgt41

42 ltpgtIf the command output stops for ltcodegttimeoutltcodegt seconds the request is43 aborted and a timeout error is shown Default timeout is 20 seconds for standard44 commands 300 seconds for known long running commandsltpgt45

46

47 lth3gtEvaluate Javascript Codelth3gt48

(continues on next page)

282 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

49 ltpgtTo execute Javascript either pass an object instead of the ltcodegtcommandltrarr˓codegt string

50 containing the command as property command and a second property type with51 value js or simply use the wrapper call ltcodegtloadjs()ltcodegt Exampleltpgt52

53 ltpgt54 ltbutton type=button class=btn btn-default55 onclick=loadjs(print(OvmsVehicleType()) out1js)gt56 Show vehicle type57 ltbuttongt58 ltpgt59 ltpre id=out1js gt60

61 ltpgtJavascript evaluation is not limited to a single command or line Hint torarr˓avoid

62 encoding complex JS code in the onclick attribute store the code in some hidden63 DOM element and read it via ltcodegt$()text()ltcodegtltpgt64

65

66 lth3gtOutput Encoding ampamp Binary Streamslth3gt67

68 ltpgtTo allow binary data to be sent by a command and to enable processing of the69 result by Javascript on the browser without character encoding issues the

rarr˓command70 API supports output binary modeltpgt71

72 ltpgtPrimary application for this is exchanging CBOR encoded objects between the73 module and the web frontend To fully support this the OVMS web frontent

rarr˓includes74 the CBOR library by Patrick Gansterer Example useltpgt75

76 ltpregt77 loadjs( command auxbatmondump(CBOR) output binary )done((data) =gt 78 history = CBORdecode(data)79 )80 ltpregt81

82 ltpgtSee the AuxBatMon and PwrMon OVMS plugins for full examplesltpgt83

84 ltpgtltcodegtoutputltcodegt modes supported by the command API areltpgt85

86 ltulgt87 ltligtltcodegttextltcodegt rarr Content-Type textplain charset=utf-8ltligt88 ltligtltcodegtjsonltcodegt rarr Content-Type applicationjson charset=utf-8ltligt89 ltligtltcodegtbinaryltcodegt rarr Content-Type applicationoctet-stream charset=x-

rarr˓user-definedltligt90 ltligtdefaultother rarr Content-Type applicationoctet-stream charset=utf-8ltligt91 ltulgt92

93

94 lth3gtjqXHR Objectlth3gt95

96 ltpgtltcodegtloadcmd()ltcodegt returns the jqXHR (XMLHttpRequest) object in charge for97 the asynchronous execution of the request This can be used to track the results98 of the execution check for errors or to abort the commandltpgt99

100 ltpgt(continues on next page)

331 TLDR Examples 283

Open Vehicles

(continued from previous page)

101 ltbutton type=button class=btn btn-default id=startcggtStart chargenltrarr˓buttongt

102 ltbutton type=button class=btn btn-default id=abortcg disabledgtAbortrarr˓chargenltbuttongt

103 ltpgt104 ltpre id=out2 style=max-height200px overflowauto gt105

106 ltpgtThe jQuery XHR object is also a thenable so actions to be performed after107 the command execution can simply be chained to the object Exampleltpgt108

109 ltpgtltbutton type=button class=btn btn-default id=showstatgtShow statltbuttongtrarr˓ltpgt

110

111 ltpgtSee lta target=_blank href=httpapijquerycomjQueryajaxjqXHRgtjQuery112 documentationltagt for full details and optionsltpgt113

114

115 lth3gtFilter Process Outputlth3gt116

117 ltpgtSupply a filter function to hook into the asynchronous output stream Userarr˓filters

118 to filter (ahem) preprocess reformat the command output scan the streamrarr˓for some

119 info youd like to know as soon as possible or completely take over the output120 processingltpgt121

122 ltpgtThe filter function is called when a new chunk of output has arrived or when123 a stream error has occurred The function gets a message object containing124 the ltcodegtrequestltcodegt object and either a ltcodegttextltcodegt for normal

rarr˓outputs125 or an ltcodegterrorltcodegt which is a preformatted error output you can use or126 ignoreltpgt127

128 ltpgtIf the filter function returns a string that will be added to the outputrarr˓target

129 If it returns ltcodegtnullltcodegt the target will remain untouchedltpgt130

131 ltpgtHint if you just want to scan the text for some info you can pass on therarr˓message

132 after your scan to the default ltcodegtstandardTextFilter()ltcodegtltpgt133

134 ltpgtExample lets reformat a ltcodegtcan statusltcodegt dump into a nice Bootstraprarr˓tableltpgt

135

136 ltpgtltbutton type=button class=btn btn-default id=canstatusgtCAN1 statusltrarr˓buttongtltpgt

137

138 lttable class=table table-condensed table-border table-striped table-hover id=rarr˓canoutgt

139 lttheadgt140 lttrgtltth class=col-xs-6gtKeyltthgtltth class=col-xs-6gtValueltthgtlttrgt141 lttheadgt142 lttbodygt143 lttablegt144

145 ltdivgt146 ltdivgt

(continues on next page)

284 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

147

148 ltscriptgt149 (function()150

151 Show page source 152 var pagesrc = $(main)html()153 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +154 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)155 $(action-showsrc)on(click function() 156 $(ltdivgt)dialog(157 title Source Code158 body ltpre style=font-size85 heightcalc(100vh - 230px)gt159 + encode_html(pagesrc) + ltpregt160 size lg161 )162 )163

164 Example jqXHRabort() 165 var xhr166 $(startcg)on(click function() 167 xhr = loadcmd(test chargen 20 600 out2)168 $(abortcg)prop(disabled false)169 )170 $(abortcg)on(click function() 171 xhrabort()172 )173

174 Example jqXHRthen() 175 $(showstat)on(click function() 176 loadcmd(stat)then(function(output) 177 confirmdialog(STAT result ltsampgt + output + ltsampgt [Close])178 )179 )180

181 Example filter output processor 182 $(canstatus)on(click function() 183 var $table = $(canout gt tbody)184 var buf = 185 $tableempty()186 loadcmd(can can1 status function(msg) 187 if (msgerror) 188 Render error into table row189 $(lttr class=dangergtlttd colspan=2gt + msgerror + lttdgtlttrgt)appendTo(

rarr˓$table)190 191 else if (msgtext) 192 As this is a stream the text chunks received need not be single or

rarr˓complete lines193 Were interested in lines here so we buffer the chunks and split the

rarr˓buffer at n194 buf += msgtext195 var lines = bufsplit(n)196 if (lineslength gt 1) 197 buf = lines[lineslength-1]198 for (var i = 0 i lt lineslength-1 i++) 199 Skip empty lines

(continues on next page)

331 TLDR Examples 285

Open Vehicles

(continued from previous page)

200 if (lines[i] == ) continue201 Split line into columns202 var col = lines[i]split( +)203 Create table row amp append to table add some color on error counters204 if (col[0]match([Ee]rr))205 $(lttr class=warninggtltthgt + col[0] + ltthgtlttdgt + col[1] + lttdgtlt

rarr˓trgt)appendTo($table)206 else207 $(lttrgtltthgt + col[0] + ltthgtlttdgt + col[1] + lttdgtlttrgt)appendTo(

rarr˓$table)208 209 210 211 Filter has handled everything212 return null213 )214 )215

216 )()217 ltscriptgt

3317 File API

The file API enables web clients to read and write files at arbitrary VFS locations

bull API URL apifile

bull Methods

ndash GET ndash read file

ndash POST ndash write file

bull Parameters

ndash path ndash the full path to the file

ndash content ndash the new file content on POST

bull Output

ndash HTTP status 200 (OK) or 400 (Error)

ndash HTTP body file content on GET or error message

On writing missing directories along the path will be created automatically

Usage Example

The API can be accessed easily in the web frontend with the jQuery AJAX methods

Write object JSON encoded into filevar json = JSONstringify(object)$post(apifile path sdmystorefile1 content json )

done(function() confirmdialog(Saved ltpgtFile has been savedltpgt [OK] 2)

)fail(function(jqXHR)

(continues on next page)

286 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

confirmdialog(Save failed jqXHRresponseText [OK]))

Read JSON encoded object from file$get(apifile path sdmystorefile1 )

done(function(responseText) var object = JSONparse(responseText) process object

)fail(function(jqXHR) confirmdialog(Load failed jqXHRresponseText [OK])

)

External Access

From external clients the API can be used by either registering a session cookie or by supplying the apikey param-eter (as explained in the general authorization overview)

Read example

curl http19216841apifileapikey=passwordamppath=sdmystorefile1

Write example

curl http19216841apifile -d apikey=password -d path=sdmystorefile1 --data-urlencode contentlocalfile

3318 Longtouch Buttons

btn-longtouchhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web dir eg scp testpagehtm test1localsddev5 - open in framework by eg httptest1localdevtestpagehtm6 --gt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtLongtouch Buttonsltdivgt

10 ltdiv class=panel-bodygt11

12 ltpgtNote open this test page with a mobile touch screen device or simulate13 a mobile device using the web debugger of your browserltpgt14

15 ltpgtThe buttons below should work normally on a non-touch deviceltpgt16

17 ltpgtOn a touch screen device touching the buttons starts a countdown18 of 15 seconds showing an overlay with a progress bar and giving vibration19 signals (on devices supporting this) The button action is triggered only20 after the countdown has finished while holding the touchltpgt21

22 ltpgtThis feature is meant to a) secure certain buttons against unintentionalrarr˓activation

(continues on next page)

331 TLDR Examples 287

Open Vehicles

(continued from previous page)

23 and to b) allow secure usage of these buttons while driving ie when the mobilerarr˓phone

24 tablet is mounted to a car holderltpgt25

26 ltpgtStandard candidates for this are buttons triggering deep modifications ie27 changing the car tuning or drive modeltpgt28

29 ltpgtTo activate the feature on a button simply add the class ltcodegtbtn-longtouchltrarr˓codegt to the button

30 To activate it on a group of buttons add the class to the container of therarr˓buttonsltpgt

31

32 ltpgtThe progress overlay shows the button title if set (HTML supported) else therarr˓button textltpgt

33

34 ltform action=gt35 ltdiv class=btn-group btn-group-justified btn-longtouchgt36 ltdiv class=btn-group btn-group-lggt37 ltbutton type=submit name=load value=0 id=prof-0 class=btn btn-

rarr˓defaultgtltstronggtSTDltstronggtltbuttongt38 ltdivgt39 ltdiv class=btn-group btn-group-lggt40 ltbutton type=submit name=load value=1 id=prof-1 class=btn btn-

rarr˓default title=Power ModegtltstronggtPWRltstronggtltbuttongt41 ltdivgt42 ltdiv class=btn-group btn-group-lggt43 ltbutton type=submit name=load value=2 id=prof-2 class=btn btn-

rarr˓successgtltstronggtECOltstronggtltbuttongt44 ltdivgt45 ltdiv class=btn-group btn-group-lggt46 ltbutton type=submit name=load value=3 id=prof-3 class=btn btn-

rarr˓default title=Winter ModegtltstronggtICEltstronggtltbuttongt47 ltdivgt48 ltdivgt49 ltformgt50

51 ltdivgt52 ltdivgt

3319 Basic Dialogs

dialogtesthtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web dir eg scp testpagehtm test1localsddev5 - open in framework by eg httptest1localdevtestpagehtm6 --gt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtDialog TestDemoltdivgt

10 ltdiv class=panel-bodygt11 lth4gtCore Widgetlth4gt12 ltbutton class=btn btn-default id=action-loadgtDialog 1ltbuttongt

(continues on next page)

288 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

13 ltbutton class=btn btn-default id=action-savegtDialog 2ltbuttongt14 ltbutton class=btn btn-default id=action-bothgtBoth togetherltbuttongt15 ltbutton class=btn btn-default id=action-dyngtDynamic customltbuttongt16 lthr gt17 lth4gtUtility Wrapperslth4gt18 ltbutton class=btn btn-default id=action-infogtAlertltbuttongt19 ltbutton class=btn btn-default id=action-confirmgtConfirmltbuttongt20 ltbutton class=btn btn-default id=action-choicegtChoiceltbuttongt21 ltbutton class=btn btn-default id=action-promptgtPromptltbuttongt22 ltbutton class=btn btn-default id=action-passwordgtPasswordltbuttongt23 lthr gt24 lth4gtLoglth4gt25 ltpre id=log gt26 ltdivgt27 ltdivgt28

29 ltdiv id=dialog1 gt30 ltdiv id=dialog2 gt31 ltdiv id=dialog3 gt32

33 ltscriptgt34

35 rarr˓=======================================================================================

36 Dialog core widget37 options 38 title 39 body 40 show false true = open directly on init41 remote false42 backdrop true background overlay43 keyboard true ESC = close44 transition fade 45 size sm lg46 contentClass added to modal-content47 onShown null function(input)48 onHidden null function(input)49 onShow null function(input)50 onHide null function(input)51 onUpdate null function(input)52 buttons [] see example53 timeout 0 in seconds54 input null predefinedshared input object to use55 56

57 Note use static dialogs (attached to the document) for speed and to store reusable58 input eg for a promptdialog59

60 The default dialog will contain just a Close button61 $(dialog1)dialog(62 title Please note63 body ltpgtThis is just a testltpgt64 )65 $(dialog2)dialog(66 title Alert67 body ltpgtDanger Will Robinson dangerltpgt68 contentClass alert-danger note looks strange just an example -- dont use

(continues on next page)

331 TLDR Examples 289

Open Vehicles

(continued from previous page)

69 )70

71 You can simply open preconfigured dialogs like this72 $(action-load)on(click function()73 $(dialog1)dialog(show)74 )75 $(action-save)on(click function()76 $(dialog2)dialog(show)77 )78

79 or you can reconfigure dialogs on the fly like this80 Note the new configuration is stored in the dialog81 $(action-both)on(click function()82 $(dialog1)dialog(show body ltpgtThis is now another testltpgt )83 This example also opens a second dialog on top of the first84 $(dialog2)dialog(show body ltpgtThis is a second layer dialogltpgt )85 )86

87 Use dynamic dialogs for single shot purposes88 $(action-dyn)on(click function()89 $(log)text()90 $(ltdiv gt)dialog(91 title Dynamic92 body ltpgtdialog with custom buttonsltpgt93 buttons [94 Buttons default to auto hiding the dialog95 label Nope 96 You can get the button clicked in the onHidden callback or you can97 add specific action callbacks to each button98 label Maybe btnClass warning autoHide false action

rarr˓function(input) 99 input is the data container of the widget with only predefined

100 member being button = the button clicked (or null)101 You can use this container for custom extensions102 inputclicked_maybe = true103 $(this)find(modal-body)append(ltpgtYoure now a maybe personltpgt)104 105 autoHide callbacks are called on the hidden event so a fade out106 is guaranteed to be finished in the callback107 label Done btnClass primary action function(input) 108 $(log)text(JSONstringify(input null 2))109 110 ]111 )112 )113

114

115 rarr˓=======================================================================================

116 Dialog utility wrappers117 confirmdialog(title body buttons [callback] timeout)118 promptdialog(type title body buttons callback)119 Both can be used plugin style or standalone for dynamic dialogs120

121 Dynamic alert() style dialog with 5 seconds timeout122 $(action-info)on(click function()123 confirmdialog(Sorry Im afraid I cant do that Dave [OK] 5)

(continues on next page)

290 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

124 Note you can also add a callback here to know when the dialog is dismissed125 )126

127 Dynamic confirm() style dialog128 $(action-confirm)on(click function()129 $(log)text()130 confirmdialog(Load file Discard unsaved changes [No Yes]

rarr˓function(confirmed)131 if (confirmed)132 $(log)text(Loading now)133 else134 $(log)text(Load aborted)135 )136 )137

138 The callback argument is the index of the button clicked (or null) so139 simple choice dialogs can be done like this140 $(action-choice)on(click function()141 $(log)text()142 confirmdialog(Select Please select the slot to use [1 2 3 4]

rarr˓function(button)143 if (button = null)144 $(log)text(Using slot + (button+1))145 else146 $(log)text(Abort)147 )148 )149

150 Static prompt() style text input dialog (with dialog3 keeping the dialog)151 $(action-prompt)on(click function()152 $(log)text()153 $(dialog3)promptdialog(text Save data Please enter file name [Cancel

rarr˓ Save] function(button input)154 if (button ampamp input)155 $(log)text(Saving to file + input)156 else157 $(log)text(Save aborted)158 )159 )160

161 All single field HTML5 input types can be used162 $(action-password)on(click function()163 $(log)text()164 promptdialog(password Authentication Please enter PIN [Cancel Continue

rarr˓] function(button input)165 if (button ampamp input)166 $(log)text(PIN entered + input)167 else168 $(log)text(Auth aborted)169 )170 )171

172 ltscriptgt

331 TLDR Examples 291

Open Vehicles

33110 File Dialogs

filedialoghtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web file path eg sddevfiledialoghtm5 - open in framework by eg httptest1localdevfiledialoghtm6 --gt7

8 ltdiv class=filedialog id=fileselectgt9

10 ltdiv class=panel panel-primarygt11 ltdiv class=panel-headinggtFileDialog Testltdivgt12 ltdiv class=panel-bodygt13

14 lth2gtDynamic APIlth2gt15

16 ltpgt17 ltbutton class=btn btn-default id=action-loadgtLoadltbuttongt18 ltbutton class=btn btn-default id=action-savegtSaveltbuttongt19 ltpgt20 ltpre id=loggt21

22 lth2gtData APIlth2gt23

24 ltdiv class=input-groupgt25 ltinput type=text class=form-control font-monospace placeholder=Enter file

rarr˓name26 name=filename id=input-filename value= autocapitalize=none

rarr˓autocorrect=off27 autocomplete=section-demo spellcheck=falsegt28 ltdiv class=input-group-btngt29 lt-- use data-toggle=filedialog data-target amp data-input on the button --gt30 ltbutton type=button class=btn btn-default data-toggle=filedialog data-

rarr˓target=fd-api data-input=input-filenamegtSelectltbuttongt31 ltdivgt32 ltdivgt33

34 lt-- This is the file dialog triggered by the button --gt35 ltdiv class=filedialog id=fd-api data-options=36 title This is a data API dialog37 path sdfoo38 quicknav [sd sdfoo sdbar]39 gt40 lt-- thats it no JS code necessary41 Note JSON syntax needs to be strict here see JS console for errors42 --gt43

44 ltdivgt45 ltdivgt46

47 ltscriptgt48

49 rarr˓=======================================================================================

50 FileDialog is a Dialog with an embedded FileBrowser

(continues on next page)

292 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

51 52 The input object combines the dialog button and the file browser data53 54 Options55 title Select file -- dialog title56 submit Select -- label of submit button57 select f -- f = only files selectable (default) d

rarr˓ = only directories58 onSubmit null -- callback function(input)59 onCancel null -- callback function(input)60 61 inherited from FileBrowser62 path 63 quicknav [sd store]64 filter null65 sortBy null66 sortDir 167 68 inherited from Dialog69 backdrop true70 keyboard true71 transition fade72 size lg73 onUpdate null74 75

76 Init dialog77 $(fileselect)filedialog(78 path storescripts79 quicknav [storescripts storeevents storeobd2ecu]80 )81

82 $(action-load)on(click function()83 $(log)empty()84 $(fileselect)filedialog(show 85 title Load Script86 submit Load87 onSubmit function(input) 88 This is called when the user doubleclicks an entry or presses Enter in a

rarr˓directory89 Note you need to check if inputfile is valid (empty = directory selected)90 if (inputfile)91 $(log)text(Loading + inputpath + n)92 else93 $(log)text(Directory selection + inputpath + n)94 95 onCancel function(input) 96 This is called when the user cancels or closes the dialog97 $(log)text(Load cancelledn)98 99 )

100 )101

102 $(action-save)on(click function()103 $(log)empty()104 $(fileselect)filedialog(show 105 title Save Script

(continues on next page)

331 TLDR Examples 293

Open Vehicles

(continued from previous page)

106 submit Save107 onSubmit function(input) 108 if (inputfile)109 $(log)text(Saving + inputpath + n)110 else111 $(log)text(Directory selection + inputpath + n)112 113 onCancel function(input) 114 $(log)text(Save cancelledn)115 116 )117 )118

119 ltscriptgt

33111 File Browser Widget

filebrowserhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web file path eg sddevfilebrowserhtm5 - open in framework by eg httptest1localdevfilebrowserhtm6 --gt7

8 ltstylegt9 Note set height or min-height on the filebrowser tbody

10 Default height by class filebrowser is 310px (each file row has a height of 31pxrarr˓with the default font size)

11 myfilebrowser tbody 12 height 35vh13 14 ltstylegt15

16 ltdiv class=panel panel-primarygt17 ltdiv class=panel-headinggtFileBrowser TestDemoltdivgt18 ltdiv class=panel-bodygt19

20 ltdiv class=filebrowser id=myfilebrowser gt21

22 lthrgt23 ltpre id=loggt24 ltbutton type=button class=btn btn-default id=action-setpathgtSet path to sd

rarr˓logslogltbuttongt25 ltbutton type=button class=btn btn-default id=action-stoploadgtStop loading

rarr˓dirltbuttongt26 ltbutton type=button class=btn btn-default id=action-filterongtFilter ziplt

rarr˓buttongt27 ltbutton type=button class=btn btn-default id=action-filteroffgtFilter offlt

rarr˓buttongt28 ltbutton type=button class=btn btn-default id=action-sortoffgtSort offlt

rarr˓buttongt29 ltpgtNote the test widget is configured to stopinhibit loading on selection of a

rarr˓txt file or a directory matching DCIMltpgt(continues on next page)

294 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

30 ltdivgt31 ltdivgt32

33 ltscriptgt34

35 rarr˓=======================================================================================

36 FileBrowser Widget37 38 Testdemo of init with all options39 Note you can init a filebrowser without any options40 Defaults are path amp quicknav as shown below no sorting no callbacks41 42 The input object passed to all callbacks contains these fields43 - path -- the full path (dir + + file)44 - file -- the file part of the currently selected path45 - dir -- the directory part of the currently selected path46 - noload -- set to true to inhibit directory loading (see onPathChange)47 48 Note path file amp dir are unvalidated user input49 50 Note on sorting disabling initial sorting improves user interaction while loading

rarr˓the51 directory ie to select filesdirs while the loader is running This may52 be an option especially for large directories The user can still sort manually53 54 Methods55 - getInput() -- retrieve input object56 - setPath(newpath reload) -- add trailing slash to enter dir wo file

rarr˓selection57 - sortList(by dir) -- sort file list58 - loadDir() -- trigger directory reload59 - stopLoad() -- abort directory loading60 - newDir() -- open create directory sub dialog61 62

63 $(myfilebrowser)filebrowser(64 path sd65 quicknav [sd store]66 filter null see Filter examples below67 sortBy name or size or date or null (disable)68 sortDir 1 or -1 for reverse69 onUpdate function(input) 70 This is called after any widget configuration update use for custom

rarr˓extensions71 $(log)append(onUpdate + JSONstringify(input) + n)72 73 onPathChange function(input) 74 Called whenever the path changes75 $(log)append(onPathChange + JSONstringify(input) + n)76 To inhibit loading the directory for the new path set inputnoload to true77 if (inputdirindexOf(DCIM) gt= 0 || inputfileindexOf(txt) gt= 0) 78 $(log)append(inhibiting directory loadingn)79 inputnoload = true80 81 82 onAction function(input)

(continues on next page)

331 TLDR Examples 295

Open Vehicles

(continued from previous page)

83 This is called when the user doubleclicks an entry or presses Enter in ararr˓directory

84 $(log)append(onAction + JSONstringify(input) + n)85 86 )87

88 $(action-setpath)on(click function(ev) 89 $(myfilebrowser)filebrowser(setPath sdlogslog true)90 )91 $(action-stopload)on(click function(ev) 92 $(myfilebrowser)filebrowser(stopLoad)93 )94 $(action-sortoff)on(click function(ev) 95 $(myfilebrowser)filebrowser(sortList )96 )97

98 Filter example99 $(action-filteron)on(click function(ev)

100 $(myfilebrowser)filebrowser(101 The list filter may be given as a string (regular expression applied to file

rarr˓name)102 filter zip$103 A string filter always lists directories104

105 For advanced usage you may alternatively specify a filter callback like this106 filter function(f) return fisdir || fnamematch(zip$) 107 The function is called per list entry object with108 - isdir true = is sub directory109 - name the name part (file or directory dir with trailing )110 - path the full path of this entry111 - size formatted size (68k)112 - date formatted date (23-Nov-2018 1742)113 - bytes size in bytes -1 for directories114 - isodate ISO style date YYYY-mm-dd HHMM115 - class can be used to add a custom row class116 Return true to allow the entry to be added to the list117

118 Note list filters do not restrict the allowed path input To do so119 register onPathChange or onAction and check the input in your callback120 See FileDialog widget select option handling for an example121 )122 )123 $(action-filteroff)on(click function(ev) 124 $(myfilebrowser)filebrowser(125 filter null126 )127 )128

129 ltscriptgt

33112 Slider Widget

input-sliderhtm (hint right click save as)

296 Chapter 33 Web Framework amp Plugins

Open Vehicles

1 ltstylegt2 Align multiple slider inputs by suitably fixing their value width 3 form-inline form-controlslider-value 4 width 80px5 6 ltstylegt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtSlider Widgetltdivgt

10 ltdiv class=panel-bodygt11

12 lth3gtStandard Numerical Inputslth3gt13

14 ltpgtThe number input is just the bootstrap defaultltpgt15

16 ltinput class=form-control type=number id=input-num1 name=num1 value=80rarr˓min=0 max=100 step=1gt

17 ltbrgt18

19 ltpgtThe range input has some styling optimization for touch devicesltpgt20

21 ltinput class=form-control type=range id=input-rng1 name=rng1 value=80rarr˓min=0 max=100 step=1gt

22 ltbrgt23

24 lth3gtSlider Widgetlth3gt25

26 ltpgt27 In many cases youd like to give especially the touchscreen user a combination

rarr˓of these input28 elements and as sliding may be too imprecise you also need large buttons for

rarr˓single step changes29 Thats what the slider widget does It also adds the option of a checkbox and a

rarr˓default value to30 reflect if the user control shall be applied31 ltpgt32

33 ltdiv class=rowgt34 ltdiv class=col-md-9gt35

36 ltpgtSliders can easily be created from minimal markup using the ltcodegtslider()rarr˓ltcodegt plugin

37 with configuration given by data attributes andor dynamic optionsltpgt38

39 ltdiv class=form-control slider id=sld1 data-min=-5 data-max=50 data-rarr˓step=05

40 data-default=40 data-unit= data-disabled=false data-checked=truerarr˓data-value=10 gt

41 ltbrgt42

43 ltdiv class=form-control slider id=sld2 gt44 ltbrgt45

46 ltpgtand slider state limits and value can be controlled using the samerarr˓methodltbrgt

47 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(rarr˓value42 )gt

(continues on next page)

331 TLDR Examples 297

Open Vehicles

(continued from previous page)

48 Set sld1 value to 4249 ltbuttongt50 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(

rarr˓checkedtrue )gt51 Check sld152 ltbuttongt53 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(

rarr˓disabledtrue )gt54 Disable sld155 ltbuttongt56 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(

rarr˓disabledfalse )gt57 Enable sld158 ltbuttongt59 ltpgt60 ltbrgt61

62 ltpgtIf you need even more control you can create the slider markup yourselfrarr˓as wellltpgt

63

64 ltdiv class=form-control slider id=sld3 data-default=50 data-reset=falserarr˓

65 data-value=80 data-min=-10 data-max=100 data-step=1gt66 ltdiv class=slider-control form-inlinegt67 ltinput class=slider-enable type=checkbox checkedgt68 ltinput class=form-control slider-value type=number id=input-sld3

rarr˓name=sld3gt69 ltspan class=slider-unitgtltspangt70 ltinput class=btn btn-default slider-down type=button value=gt71 ltinput class=btn btn-default slider-set type=button value=Lo data-

rarr˓set=25gt72 ltinput class=btn btn-default slider-set type=button value=Hi data-

rarr˓set=75gt73 ltinput class=btn btn-default slider-up type=button value=gt74 ltdivgt75 ltinput class=slider-input type=rangegt76 ltdivgt77 ltbrgt78

79 ltdivgt80 ltdiv class=col-md-3gt81

82 ltpgtltugtEvents ampamp valuesltugtltpgt83 ltpre id=show-sldevgtltpregt84

85 ltdivgt86 ltdivgt87

88 ltbrgt89

90 ltpgt91 Checkbox buttons and unit are optional You can reduce the widget to just a

rarr˓number or92 just a range input the input then needs to have the ltcodegtslider-inputltcodegt

rarr˓class93 ltpgt94

(continues on next page)

298 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

95 ltpgt96 The checkbox element defines the default value to be set on unchecking in97 ltcodegtdata-defaultltcodegt By default the checkbox will restore the previous

rarr˓user98 value when re-checked to disable this set ltcodegtdata-resetltcodegt to true99 To reset the value to the default from a script call the ltcodegtslider()ltcodegt

100 method with ltcodegtvalue nullltcodegt (this resets both the actual and the stored101 user value)102 ltpgt103

104 ltpgt105 Values and checkbox status need to be consistent on init or be set by your

rarr˓script106 To hook into value changes attach event handlers to events ltcodegtinputltcodegt107 andor ltcodegtchangeltcodegt as usual Read the ltcodegtcheckedltcodegt property to

rarr˓get the108 checkbox state109 ltpgt110

111 ltdivgt112 ltdivgt113

114 ltscriptgt115 (function()116

117 Show page source 118 var pagesrc = $(main)html()119 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +120 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)121 $(action-showsrc)on(click function() 122 $(ltdivgt)dialog(123 title Source Code124 body ltpre style=font-size85 heightcalc(100vh - 230px)gt125 + encode_html(pagesrc) + ltpregt126 size lg127 )128 )129

130 Init sliders 131 $(slider)slider()132 $(sld2)slider( min-10 max10 step01 default25 unitkW

rarr˓checkedfalse value-38 )133

134 Show slider events amp values 135 var sldev = 136 $(input-sld1 input-sld2 input-sld3)on(input change function(ev) 137 sldev[thisname] = $extend(sldev[thisname] checked thischecked )138 Note thisvalue is unvalidated here for a direct entry but the validation is

rarr˓simple139 sldev[thisname][evtype] = Mathmax(thismin Mathmin(thismax 1thisvalue))140 $(show-sldev)text(JSONstringify(sldev null 2))141 )142

143 )()144 ltscriptgt

331 TLDR Examples 299

Open Vehicles

33113 Regen Brake Monitor

This plugin defines a page including an acceleration level gauge chart number metrics for the acceleration speed andbattery power and two large indicators for the regen brake light and the brake pedal state

Itrsquos useful to fine tune the regen brake settings as you can monitor the actual deceleration levels while driving andcheck the smoothing level

Install add the source as a page plugin eg devregenmon

regenmonhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltstylegt6 indicator gt label 7 font-size 1508 line-height 2009 margin 10px

10 padding 10px11 display block12 border-radius 50px13 14 metricnumber label 15 min-width 8em16

(continues on next page)

300 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

17 metricnumber 18 display block19 float none20 text-align center21 22 ltstylegt23

24 ltdiv class=panel panel-primarygt25 ltdiv class=panel-headinggtRegen Brake Monitorltdivgt26 ltdiv class=panel-bodygt27

28 ltdiv class=receiver id=regenmon-receivergt29

30 ltdiv class=rowgt31 ltdiv class=col-sm-6gt32 ltdiv class=metric chart data-metric=vpacceleration style=height300px

rarr˓gt33 ltdiv class=chart-box gaugechart id=accel-gaugegt34 ltdivgt35 ltdiv class=metric number data-metric=vpacceleration data-prec=2gt36 ltspan class=labelgtAccelerationltspangt37 ltspan class=valuegtltspangt38 ltspan class=unitgtms2ltspangt39 ltdivgt40 ltdiv class=metric number data-metric=vpspeed data-prec=1gt41 ltspan class=labelgtSpeedltspangt42 ltspan class=valuegtltspangt43 ltspan class=unitgtkphltspangt44 ltdivgt45 ltdiv class=metric number data-metric=vbpower data-prec=1gt46 ltspan class=labelgtBattery powerltspangt47 ltspan class=valuegtltspangt48 ltspan class=unitgtkWltspangt49 ltdivgt50 ltbr class=clearfixgt51 ltdivgt52 ltdiv class=col-sm-6gt53 ltdiv class=indicator data-metric=veregenbrakegt54 ltspan class=label label-defaultgtREGENltspangt55 ltdivgt56 ltdiv class=indicator data-metric=vefootbrakegt57 ltspan class=label label-defaultgtFOOTltspangt58 ltdivgt59 ltdivgt60 ltdivgt61

62 ltdivgt63

64 ltdivgt65 ltdivgt66

67 ltscriptgt68 (function()69

70 Init acceleration gauge 71 $(accel-gauge)chart(72 chart

(continues on next page)

331 TLDR Examples 301

Open Vehicles

(continued from previous page)

73 type gauge74 spacing [0 0 0 0]75 margin [0 0 0 0]76 animation duration 250 easing easeOutExpo 77 78 title text Acceleration verticalAlign middle y 75 79 credits enabled false 80 tooltip enabled false 81 plotOptions 82 gauge dataLabels enabled false overshoot 5 83 84 pane [85 startAngle -120 endAngle 120 size 100 center [50 60]86 ]87 yAxis [88 title text ms2 89 className accel90 reversed false91 min -2 max 292 minorTickInterval 01 minorTickLength 5 minorTickPosition inside93 tickInterval 05 tickPosition inside tickLength 1394 labels step 1 distance -28 x 0 y 5 zIndex 2 95 ]96 series [97 name Acceleration data [0]98 className accel99 animation duration 0

100 pivot radius 10 101 dial radius 88 topWidth 1 baseLength 20 baseWidth 10

rarr˓rearLength 20 102 ]103 Update method 104 onUpdate function(update) 105 Create gauge data set from metric106 var data = [ metrics[vpacceleration] ]107 Update chart108 thisseries[0]setData(data)109 110 )111

112 Init indicators 113 $(regenmon-receiver)on(msgmetrics function(e update) 114 $(this)find(indicator)each(function() 115 var $el = $(this) metric = $eldata(metric) val = update[metric]116 if (val == null)117 return118 else if (val = 0)119 $elchildren()removeClass(label-default)addClass(label-danger)120 else if (val == 0)121 $elchildren()removeClass(label-danger)addClass(label-default)122 )123 )124

125 )()126 ltscriptgt

302 Chapter 33 Web Framework amp Plugins

Open Vehicles

33114 Dashboard

A refined and configurable version of this plugin has been added to the standard OVMS web UI and gets automaticallyconfigured by the vehicle modules with their respective vehicle parameters

Itrsquos a good example of the Highcharts gauge chart options and shows how to combine multiple gauge charts into asingle container (div gaugeset1) and how to style the charts using CSS

It also includes a simple test data generator so can be tested without actual vehicle data

To add a new vehicle parameter set for the standard dashboard simply override the GetDashboardConfig()method in your vehicle class Have a look at the existing overrides (for example Twizy Kia Soul Smart ED )

Install not necessary for the standard dashboard If yoursquore going to build your own dashboard from this install it asa page type plugin

dashboardhtm (hint right click save as)

1 lt-- Main --gt2

3 ltstylegt4 media (max-width 767px) 5 panel-single panel-body 6 padding 2px7 8 9 dashboard highcharts-data-label text

10 font-size 2em11 12 dashboard overlay 13 position absolute14 z-index 1015 top 6216 text-align center17 left 018 right 019 20 dashboard overlay value 21 color 04282b22 background 97b59723 padding 2px 5px

(continues on next page)

331 TLDR Examples 303

Open Vehicles

(continued from previous page)

24 margin-right 02em25 text-align center26 border 1px inset c3c3c38027 font-family Monaco Menlo Consolas QuickType Mono Lucida Console

rarr˓Roboto Mono Ubuntu Mono DejaVu Sans Mono Droid Sans Mono monospace28 display inline-block29 30 night dashboard overlay value 31 color fff32 background 25252533 34 dashboard overlay unit 35 color 66636 font-size 12px37 38 dashboard overlay range-value value 39 margin-left 10px40 width 100px41 42 dashboard overlay energy-value 43 margin-top 4px44 45 dashboard overlay energy-value value 46 margin-left 18px47 width 100px48 font-size 12px49 50 ltstylegt51

52 ltdiv class=panel panel-primary id=panel-dashboardgt53 ltdiv class=panel-headinggtDashboardltdivgt54 ltdiv class=panel-bodygt55

56 ltdiv class=receiver get-window-resize id=livestatusgt57 ltdiv class=dashboard style=position relative width 100 height 300px

rarr˓margin 0 autogt58 ltdiv class=overlaygt59 ltdiv class=range-valuegtltspan class=valuegt0 0ltspangtltspan class=unitgtkm

rarr˓ltspangtltdivgt60 ltdiv class=energy-valuegtltspan class=valuegt00 00ltspangtltspan class=

rarr˓unitgtkWhltspangtltdivgt61 ltdivgt62 ltdiv id=gaugeset1 style=width 100 height 100gtltdivgt63 ltdivgt64 ltdivgt65

66 ltdivgt67 ltdivgt68

69

70 lt-- Chart --gt71

72 ltstylegt73 highcharts-plot-band highcharts-pane 74 fill-opacity 075 76 highcharts-plot-bandborder

(continues on next page)

304 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

77 stroke 66666678 stroke-width 1px79 80

81 green-band 82 fill 55BF3B83 fill-opacity 0484 85 yellow-band 86 fill DDDF0D87 fill-opacity 0588 89 red-band 90 fill DF535391 fill-opacity 0692 93 violet-band 94 fill 9622ff95 fill-opacity 0696 97 night violet-band 98 fill 9622ff99 fill-opacity 08

100 101

102 highcharts-gauge-series highcharts-pivot 103 stroke-width 1px104 stroke 757575105 fill-opacity 1106 fill black107 108 highcharts-gauge-seriesauxgauge highcharts-pivot 109 fill-opacity 1110 fill fff111 stroke-width 0112 113 night highcharts-gauge-seriesauxgauge highcharts-pivot 114 fill 000115 116 highcharts-gauge-series highcharts-dial 117 fill d80000118 stroke 000119 stroke-width 05px120 121 highcharts-yaxis-grid highcharts-grid-line122 highcharts-yaxis-grid highcharts-minor-grid-line 123 display none124 125 highcharts-yaxis highcharts-tick 126 stroke-width 2px127 stroke 666666128 129 night highcharts-yaxis highcharts-tick 130 stroke e0e0e0131 132 highcharts-yaxis highcharts-minor-tick 133 stroke-width 18px

(continues on next page)

331 TLDR Examples 305

Open Vehicles

(continued from previous page)

134 stroke 00000085135 stroke-dasharray 6136 stroke-dashoffset -48137 stroke-linecap round138 139 night highcharts-yaxis highcharts-minor-tick 140 stroke ffffff85141 142 highcharts-axis-labels 143 fill 000144 font-weight bold145 font-size 09em146 147 night highcharts-axis-labels 148 fill ddd149 150 highcharts-data-label text 151 fill 333333152 153 night highcharts-data-label text 154 fill fff155 156

157 highcharts-axis-labelsspeed 158 font-size 12em159 160 ltstylegt161

162 ltscript type=textjavascriptgt163

164 Vehicle specific configuration165

166 var vehicle_config_twizy = 167 yAxis [168 Speed169 min 0 max 120170 plotBands [171 from 0 to 70 className green-band 172 from 70 to 100 className yellow-band 173 from 100 to 120 className red-band ]174 175 Voltage176 min 45 max 60177 plotBands [178 from 45 to 475 className red-band 179 from 475 to 50 className yellow-band 180 from 50 to 60 className green-band ]181 182 SOC183 min 0 max 100184 plotBands [185 from 0 to 125 className red-band 186 from 125 to 25 className yellow-band 187 from 25 to 100 className green-band ]188 189 Efficiency190 min 0 max 300

(continues on next page)

306 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

191 plotBands [192 from 0 to 150 className green-band 193 from 150 to 250 className yellow-band 194 from 250 to 300 className red-band ]195 196 Power197 min -10 max 30198 plotBands [199 from -10 to 0 className violet-band 200 from 0 to 15 className green-band 201 from 15 to 25 className yellow-band 202 from 25 to 30 className red-band ]203 204 Charger temperature205 min 20 max 80 tickInterval 20206 plotBands [207 from 20 to 65 className normal-band border 208 from 65 to 80 className red-band border ]209 210 Battery temperature211 min -15 max 65 tickInterval 25212 plotBands [213 from -15 to 0 className red-band border 214 from 0 to 50 className normal-band border 215 from 50 to 65 className red-band border ]216 217 Inverter temperature218 min 20 max 80 tickInterval 20219 plotBands [220 from 20 to 70 className normal-band border 221 from 70 to 80 className red-band border ]222 223 Motor temperature224 min 50 max 125 tickInterval 25225 plotBands [226 from 50 to 110 className normal-band border 227 from 110 to 125 className red-band border ]228 ]229 230

231 var vehicle_config_default = 232 yAxis [233 Speed234 min 0 max 120235 plotBands [236 from 0 to 70 className green-band 237 from 70 to 100 className yellow-band 238 from 100 to 120 className red-band ]239 240 Voltage241 min 310 max 410242 plotBands [243 from 310 to 325 className red-band 244 from 325 to 340 className yellow-band 245 from 340 to 410 className green-band ]246 247 SOC

(continues on next page)

331 TLDR Examples 307

Open Vehicles

(continued from previous page)

248 min 0 max 100249 plotBands [250 from 0 to 125 className red-band 251 from 125 to 25 className yellow-band 252 from 25 to 100 className green-band ]253 254 Efficiency255 min 0 max 400256 plotBands [257 from 0 to 200 className green-band 258 from 200 to 300 className yellow-band 259 from 300 to 400 className red-band ]260 261 Power262 min -50 max 200263 plotBands [264 from -50 to 0 className violet-band 265 from 0 to 100 className green-band 266 from 100 to 150 className yellow-band 267 from 150 to 200 className red-band ]268 269 Charger temperature270 min 20 max 80 tickInterval 20271 plotBands [272 from 20 to 65 className normal-band border 273 from 65 to 80 className red-band border ]274 275 Battery temperature276 min -15 max 65 tickInterval 25277 plotBands [278 from -15 to 0 className red-band border 279 from 0 to 50 className normal-band border 280 from 50 to 65 className red-band border ]281 282 Inverter temperature283 min 20 max 80 tickInterval 20284 plotBands [285 from 20 to 70 className normal-band border 286 from 70 to 80 className red-band border ]287 288 Motor temperature289 min 50 max 125 tickInterval 25290 plotBands [291 from 50 to 110 className normal-band border 292 from 110 to 125 className red-band border ]293 ]294 295

296 var vehicle_config = vehicle_config_twizy297

298 var gaugeset1299

300 function get_dashboard_data() 301 var rmin = metrics[vbrangeest]||0 rmax = metrics[vbrangeideal]||0302 var euse = metrics[vbenergyused]||0 erec = metrics[vbenergyrecd]||0303 if (rmin gt rmax) var x = rmin rmin = rmax rmax = x 304 var md =

(continues on next page)

308 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

305 range value + rmaxtoFixed(0) + + rmintoFixed(0) 306 energy value + eusetoFixed(1) + + erectoFixed(1) 307 series [308 data [metrics[vpspeed]] 309 data [metrics[vbvoltage]] 310 data [metrics[vbsoc]] 311 data [metrics[vbconsumption]] 312 data [metrics[vbpower]] 313 data [metrics[vctemp]] 314 data [metrics[vbtemp]] 315 data [metrics[vitemp]] 316 data [metrics[vmtemp]] ]317 318 return md319 320

321 function update_dashboard() 322 var md = get_dashboard_data()323 $(range-value value)text(mdrangevalue)324 $(energy-value value)text(mdenergyvalue)325 gaugeset1update( series mdseries )326 327

328 function init_gaugeset1() 329 var chart_config = 330 chart 331 type gauge332 spacing [0 0 0 0]333 margin [0 0 0 0]334 animation duration 0 easing swing 335 336 title text null 337 credits enabled false 338 tooltip enabled false 339

340 pane [341 startAngle -125 endAngle 125 center [50 45] size 80

rarr˓Speed342 startAngle 70 endAngle 110 center [-20 20] size 100

rarr˓Voltage343 startAngle 70 endAngle 110 center [-20 60] size 100 SOC344 startAngle -110 endAngle -70 center [120 20] size 100

rarr˓Efficiency345 startAngle -110 endAngle -70 center [120 60] size 100

rarr˓Power346 startAngle -45 endAngle 45 center [20 100] size 30

rarr˓Charger temperature347 startAngle -45 endAngle 45 center [40 100] size 30

rarr˓Battery temperature348 startAngle -45 endAngle 45 center [60 100] size 30

rarr˓Inverter temperature349 startAngle -45 endAngle 45 center [80 100] size 30 ]

rarr˓Motor temperature350

351 responsive 352 rules [353 condition minWidth 0 maxWidth 400

(continues on next page)

331 TLDR Examples 309

Open Vehicles

(continued from previous page)

354 chartOptions 355 pane [356 size 60 Speed357 center [-20 20] Voltage358 center [-20 60] SOC359 center [120 20] Efficiency360 center [120 60] Power361 center [15 100] size 25 Charger temperature362 center [3833 100] size 25 Battery temperature363 center [6166 100] size 25 Inverter temperature364 center [85 100] size 25 ] Motor temperature365 yAxis [ labels step 1 ] Speed366 367 368 condition minWidth 401 maxWidth 450 369 chartOptions 370 pane [371 size 70 Speed372 center [-15 20] Voltage373 center [-15 60] SOC374 center [115 20] Efficiency375 center [115 60] Power376 center [15 100] size 275 Charger temperature377 center [3833 100] size 275 Battery temperature378 center [6166 100] size 275 Inverter temperature379 center [85 100] size 275 ] Motor temperature380 381 382 condition minWidth 451 maxWidth 600 383 chartOptions 384 pane [385 size 80 Speed386 center [-10 20] Voltage387 center [-10 60] SOC388 center [110 20] Efficiency389 center [110 60] ] Power390 391 392 condition minWidth 601 393 chartOptions 394 pane [395 size 85 Speed396 center [0 20] Voltage397 center [0 60] SOC398 center [100 20] Efficiency399 center [100 60] ] Power400 401 ]402 403

404 yAxis [405 Speed axis406 pane 0 className speed title text kmh 407 reversed false408 minorTickInterval auto minorTickLength 5 minorTickPosition inside409 tickPixelInterval 30 tickPosition inside tickLength 13410 labels step 2 distance -28 x 0 y 5 zIndex 2

(continues on next page)

310 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

411 412 Voltage axis413 pane 1 className voltage title text Volt align low x 90 y

rarr˓35 414 reversed true415 minorTickInterval auto minorTickLength 5 minorTickPosition inside416 tickPixelInterval 30 tickPosition inside tickLength 13417 labels step 1 distance -25 x 0 y 5 zIndex 2 418 419 SOC axis420 pane 2 className soc title text SOC align low x 85 y 35 421 reversed true422 minorTickInterval auto minorTickLength 5 minorTickPosition inside423 tickPixelInterval 30 tickPosition inside tickLength 13424 labels step 1 distance -25 x 0 y 5 zIndex 2 425 426 Efficiency axis427 pane 3 className efficiency title text Whkm align low x -125

rarr˓ y 35 428 reversed false429 minorTickInterval auto minorTickLength 5 minorTickPosition inside430 tickPixelInterval 30 tickPosition inside tickLength 13431 labels step 1 distance -25 x 0 y 5 zIndex 2 432 433 Power axis434 pane 4 className power title text kW align low x -115 y 35

rarr˓435 reversed false436 minorTickInterval auto minorTickLength 5 minorTickPosition inside437 tickPixelInterval 30 tickPosition inside tickLength 13438 labels step 1 distance -25 x 0 y 5 zIndex 2 439 440 Charger temperature axis441 pane 5 className temp-charger title text CHG degC y 10 442 tickPosition inside tickLength 10 minorTickInterval null443 labels step 1 distance 3 x 0 y 0 zIndex 2 444 445 Battery temperature axis446 pane 6 className temp-battery title text BAT degC y 10 447 tickPosition inside tickLength 10 minorTickInterval null448 labels step 1 distance 3 x 0 y 0 zIndex 2 449 450 Inverter temperature axis451 pane 7 className temp-inverter title text PEM degC y 10 452 tickPosition inside tickLength 10 minorTickInterval null453 labels step 1 distance 3 x 0 y 0 zIndex 2 454 455 Motor temperature axis456 pane 8 className temp-motor title text MOT degC y 10 457 tickPosition inside tickLength 10 minorTickInterval null458 labels step 1 distance 3 x 0 y 0 zIndex 2 459 ]460

461 plotOptions 462 gauge 463 dataLabels enabled false 464 overshoot 1

(continues on next page)

331 TLDR Examples 311

Open Vehicles

(continued from previous page)

465 466 467 series [468 Speed value469 yAxis 0 name Speed className speed fullgauge data [0]470 pivot radius 10 471 dial radius 88 topWidth 1 baseLength 20 baseWidth 10

rarr˓rearLength 20 472 473 Voltage value474 yAxis 1 name Voltage className voltage auxgauge data [0]475 pivot radius 85 476 dial radius 95 baseWidth 5 baseLength 90 477 478 SOC value479 yAxis 2 name SOC className soc auxgauge data [0]480 pivot radius 85 481 dial radius 95 baseWidth 5 baseLength 90 482 483 Efficiency value484 yAxis 3 name Efficiency className efficiency auxgauge data [0]485 pivot radius 85 486 dial radius 95 baseWidth 5 baseLength 90 487 488 Power value489 yAxis 4 name Power className power auxgauge data [0]490 pivot radius 85 491 dial radius 95 baseWidth 5 baseLength 90 492 493 Charger temperature value494 yAxis 5 name Charger temperature className temp-charger tempgauge

rarr˓data [0]495 dial radius 90 baseWidth 3 baseLength 90 496 497 Battery temperature value498 yAxis 6 name Battery temperature className temp-battery tempgauge

rarr˓data [0]499 dial radius 90 baseWidth 3 baseLength 90 500 501 Inverter temperature value502 yAxis 7 name Inverter temperature className temp-inverter tempgauge

rarr˓data [0]503 dial radius 90 baseWidth 3 baseLength 90 504 505 Motor temperature value506 yAxis 8 name Motor temperature className temp-motor tempgauge data

rarr˓[0]507 dial radius 90 baseWidth 3 baseLength 90 508 ]509 510

511 Inject vehicle config512 for (var i = 0 i lt chart_configyAxislength i++) 513 $extend(chart_configyAxis[i] vehicle_configyAxis[i])514 515

516 gaugeset1 = Highchartschart(gaugeset1 chart_config(continues on next page)

312 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

517 function (chart) 518 chartupdate( chart animation duration 1000 easing swing )519 $(livestatus)on(msgmetrics function(e update)520 update_dashboard()521 )on(window-resize function(e)522 chartreflow()523 )524 525 )526 527

528 function init_charts() 529 init_gaugeset1()530 531

532 if (windowHighcharts) 533 init_charts()534 else 535 $ajax(536 url windowassetscharts_js537 dataType script538 cache true539 success function() init_charts() 540 )541 542

543 ltscriptgt544

545

546

547 lt-- TESTDATENGENERATOR --gt548 ltbr class=clearfixgt549 ltdiv id=viewportinfogtWxHltdivgt550 ltdiv id=debugfsgtltdivgt551 ltbutton class=btn btn-info id=mkmetricsgtMake test metricsltbuttongt552 ltbr class=clearfixgt553 ltscript type=textjavascriptgt554 $(mkmetrics)on(click function()555 var msg = 556 metrics 557 vbrangeest Mathrandom()80558 vbrangeideal Mathrandom()80559 vbenergyused Mathrandom()20560 vbenergyrecd Mathrandom()20561 vpspeed Mathrandom()120562 vbvoltage 45 + Mathrandom()15563 vbsoc Mathrandom()100564 vbconsumption Mathrandom()300565 vbpower Mathrandom()40 - 10566 vctemp Mathrandom()80567 vbtemp Mathrandom()80568 vitemp Mathrandom()80569 vmtemp Mathrandom()80570 571 572 $extend(metrics msgmetrics)573 $(receiver)trigger(msgmetrics msgmetrics)

(continues on next page)

331 TLDR Examples 313

Open Vehicles

(continued from previous page)

574 )575 $(window)on(resize function()576 $(viewportinfo)text($(window)width() + x + $(window)height())577 )trigger(resize)578 ltscriptgt

33115 Twizy Dashboard Tuning Plugin

This plugin adds two sliders to adjust neutral and braking recuperation levels to the dashboard

The sliders listen to driving profile changes and update accordingly

If not yet logged in the sliders are disabled

Install add the plugin as a hook type to page dashboard hook bodypre

dashboard-tunesliderhtm (hint right click save as)

1 lt--2 Hook plugin for dashboardbodypre or bodypost3 - add sliders to adjust recuperation power levels

(continues on next page)

314 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

4 --gt5

6 ltstylegt7 tuneslider 8 margin 10px 8px 09

10 form-inline form-controlslider-value 11 width 80px12 13 ltstylegt14

15 ltdiv class=receiver id=tuneslider style=displaynonegt16 ltdiv class=form-groupgt17 ltlabel class=control-label for=input-neutralgtNeutral recuperationltlabelgt18 ltdiv class=form-control slider id=neutral gt19 ltdivgt20 ltdiv class=form-groupgt21 ltlabel class=control-label for=input-brakegtBrake recuperationltlabelgt22 ltdiv class=form-control slider id=brake gt23 ltdivgt24 ltdivgt25

26 ltscriptgt27 (function()28

29 Init sliders30 $(neutral)slider( min0 max100 step1 unit default18 value18

rarr˓checkedfalse )31 $(brake)slider( min0 max100 step1 unit default18 value18

rarr˓checkedfalse )32

33 Update sliders on profile changes34 var profile35 $(tuneslider)on(msgmetrics function(ev update) 36 if (update[xrtcfgprofile] = null) 37 profile = update[xrtcfgprofile]38 var neutral = profile[7] brake = profile[8] see cfgconvc tagnames for

rarr˓profile structure39 $(neutral)slider( checked (neutral=-1) value (neutral=-1) neutral

rarr˓null )40 $(brake)slider( checked (brake=-1) value (brake=-1) brake null )41 42 )43

44 Update profile on slider changes45 $(tuneslider slider-value)on(change function(ev) 46 var neutral = $(input-neutral)prop(checked) $(input-neutral)val() -

rarr˓147 brake = $(input-brake)prop(checked) $(input-brake)val() -148 autorecup_minprc = profile[43] autorecup_ref = profile[44]49 var cmd = xrt cfg recup + neutral + + brake + + autorecup_ref + +

rarr˓autorecup_minprc50 loadcmd(cmd loadres)51 )52

53 Install into panel54 $(main)one(load function(ev)

(continues on next page)

331 TLDR Examples 315

Open Vehicles

(continued from previous page)

55 if (loggedin) 56 $(tuneslider slider)slider( disabled true )57 58 $(tuneslider)appendTo(panel-dashboard panel-body)show()59 )60

61 )()62 ltscriptgt

33116 Twizy Tuning Profile Editor

This plugin has been added to the Twizy code Itrsquos used here as a more complex example of what can be done byplugins

Itrsquos a full featured SEVCON tuning profile editor including dialogs to load amp save profiles from the OVMS configura-tion and to create amp read base64 profile codes

See Twizy documentation for details on tuning profiles and capabilities

Install not necessary if vehicle Twizy is configured (see ldquoTwizyrdquo menu) If yoursquod like to test this for another vehicleadd as a page plugin eg testprofed

profile-editorhtm (hint right click save as)

1 lt--2 Twizy page plugin Tuning Profile Editor3 Note included in firmware v32

(continues on next page)

316 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

4 --gt5

6 ltstylegt7 form-inline form-controlslider-value 8 width 70px9

10 radio-list 11 height 313px12 overflow-y auto13 overflow-x hidden14 padding-right 15px15 16 radio-list radio 17 overflow hidden18 19 radio-list key 20 min-width 20px21 display inline-block22 text-align center23 margin 0 10px24 25 radio-list kbd 26 min-width 60px27 display inline-block28 text-align center29 margin 0 20px 0 10px30 31 radio-list radio label 32 width 10033 text-align left34 padding 8px 30px35 36 radio-list radio labelactive 37 background-color 337ab738 color fff39 outline none40 41 radio-list radio labelactive input 42 outline none43 44 night radio-list radio labelhover 45 color fff46 47 ltstylegt48

49 ltdiv class=panel panel-primarygt50 ltdiv class=panel-headinggtTuning Profile ltspan id=headkeygtEditorltspangtltdivgt51 ltdiv class=panel-bodygt52 ltform action=gt53

54 ltdiv class=form-groupgt55 ltdiv class=flex-groupgt56 ltbutton type=button class=btn btn-default action-newgtNewltbuttongt57 ltbutton type=button class=btn btn-default action-loadgtLoadltbuttongt58 ltinput type=hidden id=input-key name=key value=gt59 ltinput type=hidden id=input-base64-reset name=base64-reset value=gt60 ltinput type=text class=form-control font-monospace placeholder=Base64

rarr˓profile code (continues on next page)

331 TLDR Examples 317

Open Vehicles

(continued from previous page)

61 name=base64 id=input-base64 value= autocapitalize=none autocorrect=rarr˓off

62 autocomplete=off spellcheck=falsegt63 ltdivgt64 ltdivgt65

66 ltul class=nav nav-tabsgt67 ltli class=activegtlta data-toggle=tab href=tab-drive aria-expanded=truegt

rarr˓Driveltagtltligt68 ltli class=gtlta data-toggle=tab href=tab-recup aria-expanded=falsegtRecup

rarr˓ltagtltligt69 ltli class=gtlta data-toggle=tab href=tab-ramps aria-expanded=falsegtRamps

rarr˓ltagtltligt70 ltulgt71 ltdiv class=tab-contentgt72

73 ltdiv id=tab-drive class=tab-pane section-drive active ingt74

75 ltfieldset id=part-speedgt76 ltlegendgtSpeedltlegendgt77 ltdiv class=form-horizontalgt78 ltdiv class=form-groupgt79 ltlabel class=control-label col-sm-2 for=input-speedgtMax speedlt

rarr˓labelgt80 ltdiv class=col-sm-10gtltdiv class=form-control slider id=speed gtlt

rarr˓divgt81 ltdivgt82 ltdiv class=form-groupgt83 ltlabel class=control-label col-sm-2 for=input-warngtWarn speedlt

rarr˓labelgt84 ltdiv class=col-sm-10gtltdiv class=form-control slider id=warn gtlt

rarr˓divgt85 ltdivgt86 ltdivgt87 ltfieldsetgt88

89 ltfieldset id=part-powergt90 ltlegendgtPowerltlegendgt91 ltdiv class=form-horizontalgt92 ltdiv class=form-groupgt93 ltlabel class=control-label col-sm-2 for=input-currentgtCurrentlt

rarr˓labelgt94 ltdiv class=col-sm-10gtltdiv class=form-control slider id=current gt

rarr˓ltdivgt95 ltdivgt96 ltdiv class=form-groupgt97 ltlabel class=control-label col-sm-2 for=input-torquegtTorqueltlabelgt98 ltdiv class=col-sm-10gtltdiv class=form-control slider id=torque gtlt

rarr˓divgt99 ltdivgt

100 ltdiv class=form-groupgt101 ltlabel class=control-label col-sm-2 for=input-power_lowgtPower lowlt

rarr˓labelgt102 ltdiv class=col-sm-10gtltdiv class=form-control slider id=power_low

rarr˓gtltdivgt103 ltdivgt104 ltdiv class=form-groupgt

(continues on next page)

318 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

105 ltlabel class=control-label col-sm-2 for=input-power_highgtPower highrarr˓ltlabelgt

106 ltdiv class=col-sm-10gtltdiv class=form-control slider id=power_highrarr˓gtltdivgt

107 ltdivgt108 ltdivgt109 ltfieldsetgt110

111 ltfieldset id=part-drivegt112 ltlegendgtDriveltlegendgt113 ltdiv class=form-horizontalgt114 ltdiv class=form-groupgt115 ltlabel class=control-label col-sm-2 for=input-drivegtDrive levellt

rarr˓labelgt116 ltdiv class=col-sm-10gtltdiv class=form-control slider id=drive gtlt

rarr˓divgt117 ltdivgt118 ltdiv class=form-groupgt119 ltlabel class=control-label col-sm-2 for=input-autodrive_refgtAuto 100

rarr˓ refltlabelgt120 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autodrive_

rarr˓ref gtltdivgt121 ltdivgt122 ltdiv class=form-groupgt123 ltlabel class=control-label col-sm-2 for=input-autodrive_minprcgtAuto

rarr˓min levelltlabelgt124 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autodrive_

rarr˓minprc gtltdivgt125 ltdivgt126 ltdivgt127 ltfieldsetgt128

129 ltfieldset id=part-tsmapdgt130 ltlegendgtTorqueSpeed-Map Driveltlegendgt131 ltdiv class=form-horizontalgt132 ltdiv class=form-groupgt133 ltlabel class=control-label col-sm-2 for=input-tsd_prc1gtTrq level 1

rarr˓ltlabelgt134 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc1 gt

rarr˓ltdivgt135 ltdivgt136 ltdiv class=form-groupgt137 ltlabel class=control-label col-sm-2 for=input-tsd_spd1gtat speed

rarr˓ltlabelgt138 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd1 gt

rarr˓ltdivgt139 ltdivgt140 ltdiv class=form-groupgt141 ltlabel class=control-label col-sm-2 for=input-tsd_prc2gtTrq level 2

rarr˓ltlabelgt142 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc2 gt

rarr˓ltdivgt143 ltdivgt144 ltdiv class=form-groupgt145 ltlabel class=control-label col-sm-2 for=input-tsd_spd2gtat speed

rarr˓ltlabelgt146 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd2 gt

rarr˓ltdivgt (continues on next page)

331 TLDR Examples 319

Open Vehicles

(continued from previous page)

147 ltdivgt148 ltdiv class=form-groupgt149 ltlabel class=control-label col-sm-2 for=input-tsd_prc3gtTrq level 3

rarr˓ltlabelgt150 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc3 gt

rarr˓ltdivgt151 ltdivgt152 ltdiv class=form-groupgt153 ltlabel class=control-label col-sm-2 for=input-tsd_spd3gtat speed

rarr˓ltlabelgt154 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd3 gt

rarr˓ltdivgt155 ltdivgt156 ltdiv class=form-groupgt157 ltlabel class=control-label col-sm-2 for=input-tsd_prc4gtTrq level 4

rarr˓ltlabelgt158 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc4 gt

rarr˓ltdivgt159 ltdivgt160 ltdiv class=form-groupgt161 ltlabel class=control-label col-sm-2 for=input-tsd_spd4gtat speed

rarr˓ltlabelgt162 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd4 gt

rarr˓ltdivgt163 ltdivgt164 ltdivgt165 ltfieldsetgt166

167 ltdivgt168

169 ltdiv id=tab-recup class=tab-pane section-recupgt170

171 ltfieldset id=part-recupgt172 ltlegendgtRecupltlegendgt173 ltdiv class=form-horizontalgt174 ltdiv class=form-groupgt175 ltlabel class=control-label col-sm-2 for=input-neutralgtNeutral level

rarr˓ltlabelgt176 ltdiv class=col-sm-10gtltdiv class=form-control slider id=neutral gt

rarr˓ltdivgt177 ltdivgt178 ltdiv class=form-groupgt179 ltlabel class=control-label col-sm-2 for=input-brakegtBrake levellt

rarr˓labelgt180 ltdiv class=col-sm-10gtltdiv class=form-control slider id=brake gtlt

rarr˓divgt181 ltdivgt182 ltdiv class=form-groupgt183 ltlabel class=control-label col-sm-2 for=input-autorecup_refgtAuto 100

rarr˓ refltlabelgt184 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autorecup_

rarr˓ref gtltdivgt185 ltdivgt186 ltdiv class=form-groupgt187 ltlabel class=control-label col-sm-2 for=input-autorecup_minprcgtAuto

rarr˓min levelltlabelgt188 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autorecup_

rarr˓minprc gtltdivgt (continues on next page)

320 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

189 ltdivgt190 ltdivgt191 ltfieldsetgt192

193 ltfieldset id=part-tsmapngt194 ltlegendgtTorqueSpeed-Map Neutralltlegendgt195 ltdiv class=form-horizontalgt196 ltdiv class=form-groupgt197 ltlabel class=control-label col-sm-2 for=input-tsn_prc1gtTrq level 1

rarr˓ltlabelgt198 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc1 gt

rarr˓ltdivgt199 ltdivgt200 ltdiv class=form-groupgt201 ltlabel class=control-label col-sm-2 for=input-tsn_spd1gtat speed

rarr˓ltlabelgt202 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd1 gt

rarr˓ltdivgt203 ltdivgt204 ltdiv class=form-groupgt205 ltlabel class=control-label col-sm-2 for=input-tsn_prc2gtTrq level 2

rarr˓ltlabelgt206 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc2 gt

rarr˓ltdivgt207 ltdivgt208 ltdiv class=form-groupgt209 ltlabel class=control-label col-sm-2 for=input-tsn_spd2gtat speed

rarr˓ltlabelgt210 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd2 gt

rarr˓ltdivgt211 ltdivgt212 ltdiv class=form-groupgt213 ltlabel class=control-label col-sm-2 for=input-tsn_prc3gtTrq level 3

rarr˓ltlabelgt214 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc3 gt

rarr˓ltdivgt215 ltdivgt216 ltdiv class=form-groupgt217 ltlabel class=control-label col-sm-2 for=input-tsn_spd3gtat speed

rarr˓ltlabelgt218 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd3 gt

rarr˓ltdivgt219 ltdivgt220 ltdiv class=form-groupgt221 ltlabel class=control-label col-sm-2 for=input-tsn_prc4gtTrq level 4

rarr˓ltlabelgt222 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc4 gt

rarr˓ltdivgt223 ltdivgt224 ltdiv class=form-groupgt225 ltlabel class=control-label col-sm-2 for=input-tsn_spd4gtat speed

rarr˓ltlabelgt226 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd4 gt

rarr˓ltdivgt227 ltdivgt228 ltdivgt229 ltfieldsetgt

(continues on next page)

331 TLDR Examples 321

Open Vehicles

(continued from previous page)

230

231 ltfieldset id=part-tsmapbgt232 ltlegendgtTorqueSpeed-Map Brakeltlegendgt233 ltdiv class=form-horizontalgt234 ltdiv class=form-groupgt235 ltlabel class=control-label col-sm-2 for=input-tsb_prc1gtTrq level 1

rarr˓ltlabelgt236 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc1 gt

rarr˓ltdivgt237 ltdivgt238 ltdiv class=form-groupgt239 ltlabel class=control-label col-sm-2 for=input-tsb_spd1gtat speed

rarr˓ltlabelgt240 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd1 gt

rarr˓ltdivgt241 ltdivgt242 ltdiv class=form-groupgt243 ltlabel class=control-label col-sm-2 for=input-tsb_prc2gtTrq level 2

rarr˓ltlabelgt244 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc2 gt

rarr˓ltdivgt245 ltdivgt246 ltdiv class=form-groupgt247 ltlabel class=control-label col-sm-2 for=input-tsb_spd2gtat speed

rarr˓ltlabelgt248 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd2 gt

rarr˓ltdivgt249 ltdivgt250 ltdiv class=form-groupgt251 ltlabel class=control-label col-sm-2 for=input-tsb_prc3gtTrq level 3

rarr˓ltlabelgt252 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc3 gt

rarr˓ltdivgt253 ltdivgt254 ltdiv class=form-groupgt255 ltlabel class=control-label col-sm-2 for=input-tsb_spd3gtat speed

rarr˓ltlabelgt256 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd3 gt

rarr˓ltdivgt257 ltdivgt258 ltdiv class=form-groupgt259 ltlabel class=control-label col-sm-2 for=input-tsb_prc4gtTrq level 4

rarr˓ltlabelgt260 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc4 gt

rarr˓ltdivgt261 ltdivgt262 ltdiv class=form-groupgt263 ltlabel class=control-label col-sm-2 for=input-tsb_spd4gtat speed

rarr˓ltlabelgt264 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd4 gt

rarr˓ltdivgt265 ltdivgt266 ltdivgt267 ltfieldsetgt268

269 ltdivgt270

(continues on next page)

322 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

271 ltdiv id=tab-ramps class=tab-pane section-rampsgt272

273 ltfieldset id=part-rampsglobalgt274 ltlegendgtGeneralltlegendgt275 ltdiv class=form-horizontalgt276 ltdiv class=form-groupgt277 ltlabel class=control-label col-sm-2 for=input-ramplimit_accelgtLimit

rarr˓upltlabelgt278 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramplimit_

rarr˓accel gtltdivgt279 ltdivgt280 ltdiv class=form-groupgt281 ltlabel class=control-label col-sm-2 for=input-ramplimit_decelgtLimit

rarr˓downltlabelgt282 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramplimit_

rarr˓decel gtltdivgt283 ltdivgt284 ltdiv class=form-groupgt285 ltlabel class=control-label col-sm-2 for=input-smoothgtSmoothinglt

rarr˓labelgt286 ltdiv class=col-sm-10gtltdiv class=form-control slider id=smooth gtlt

rarr˓divgt287 ltdivgt288 ltdivgt289 ltfieldsetgt290

291 ltfieldset id=part-rampsgt292 ltlegendgtRamp Speedsltlegendgt293 ltdiv class=form-horizontalgt294 ltdiv class=form-groupgt295 ltlabel class=control-label col-sm-2 for=input-ramp_startgtStart

rarr˓reverseltlabelgt296 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_start

rarr˓gtltdivgt297 ltdivgt298 ltdiv class=form-groupgt299 ltlabel class=control-label col-sm-2 for=input-ramp_accelgtAccelerate

rarr˓ltlabelgt300 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_accel

rarr˓gtltdivgt301 ltdivgt302 ltdiv class=form-groupgt303 ltlabel class=control-label col-sm-2 for=input-ramp_decelgtDecelerate

rarr˓ltlabelgt304 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_decel

rarr˓gtltdivgt305 ltdivgt306 ltdiv class=form-groupgt307 ltlabel class=control-label col-sm-2 for=input-ramp_neutralgtNeutral

rarr˓ltlabelgt308 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_neutral

rarr˓ gtltdivgt309 ltdivgt310 ltdiv class=form-groupgt311 ltlabel class=control-label col-sm-2 for=input-ramp_brakegtBrakelt

rarr˓labelgt312 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_brake

rarr˓gtltdivgt (continues on next page)

331 TLDR Examples 323

Open Vehicles

(continued from previous page)

313 ltdivgt314 ltdivgt315 ltfieldsetgt316

317 ltdivgt318

319 ltdivgt320

321 ltbrgt322 ltdiv class=form-horizontalgt323 ltdiv class=form-groupgt324 ltlabel class=control-label col-sm-2 for=input-labelgtLabelltlabelgt325 ltdiv class=col-sm-10gt326 ltinput type=text class=form-control placeholder=Short button label327 name=label id=input-label value= autocapitalize=none autocorrect=

rarr˓off328 autocomplete=off spellcheck=falsegt329 ltdivgt330 ltdivgt331 ltdiv class=form-groupgt332 ltlabel class=control-label col-sm-2 for=input-titlegtTitleltlabelgt333 ltdiv class=col-sm-10gt334 ltinput type=text class=form-control placeholder=optional titlename335 name=title id=input-title value= autocapitalize=none autocorrect=

rarr˓off336 autocomplete=off spellcheck=falsegt337 ltdivgt338 ltdivgt339 ltdivgt340

341 ltbrgt342 ltdiv class=text-centergt343 ltbutton type=button class=btn btn-default action-resetgtResetltbuttongt344 ltbutton type=button class=btn btn-default action-saveasgtSave asltbuttongt345 ltbutton type=button class=btn btn-primary action-savegtSaveltbuttongt346 ltdivgt347

348 ltformgt349 ltdivgt350 ltdivgt351

352 ltdiv id=key-dialog gt353

354 ltscriptgt355 (function()356

357 init sliders358

359 $(speed)slider( unitkph min6 max120 default80 value80rarr˓checkedfalse )

360 $(warn)slider( unitkph min6 max120 default89 value89 checkedfalserarr˓)

361

362 $(current)slider( unit min10 max123 default100 value100rarr˓checkedfalse )

363 $(torque)slider( unit min10 max130 default100 value100rarr˓checkedfalse )

(continues on next page)

324 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

364 $(power_low)slider( unit min10 max139 default100 value100rarr˓checkedfalse )

365 $(power_high)slider( unit min10 max130 default100 value100rarr˓checkedfalse )

366

367 $(drive)slider( unit min10 max100 default100 value100rarr˓checkedfalse )

368 $(autodrive_ref)slider( unitkW min0 max25 step01 default0 value0rarr˓ checkedfalse )

369 $(autodrive_minprc)slider( unit min0 max100 default0 value0rarr˓checkedfalse )

370

371 $(tsd_prc1)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

372 $(tsd_spd1)slider( unitkph min0 max120 default33 value33rarr˓checkedfalse )

373 $(tsd_prc2)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

374 $(tsd_spd2)slider( unitkph min0 max120 default39 value39rarr˓checkedfalse )

375 $(tsd_prc3)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

376 $(tsd_spd3)slider( unitkph min0 max120 default50 value50rarr˓checkedfalse )

377 $(tsd_prc4)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

378 $(tsd_spd4)slider( unitkph min0 max120 default66 value66rarr˓checkedfalse )

379

380 $(neutral)slider( unit min0 max100 default18 value18rarr˓checkedfalse )

381 $(brake)slider( unit min0 max100 default18 value18 checkedfalse rarr˓)

382 $(autorecup_ref)slider( unitkW min0 max25 step01 default0 value0rarr˓ checkedfalse )

383 $(autorecup_minprc)slider( unit min0 max100 default0 value0rarr˓checkedfalse )

384

385 $(tsn_prc1)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

386 $(tsn_spd1)slider( unitkph min0 max120 default33 value33rarr˓checkedfalse )

387 $(tsn_prc2)slider( unit min0 max100 default80 value80rarr˓checkedfalse )

388 $(tsn_spd2)slider( unitkph min0 max120 default39 value39rarr˓checkedfalse )

389 $(tsn_prc3)slider( unit min0 max100 default50 value50rarr˓checkedfalse )

390 $(tsn_spd3)slider( unitkph min0 max120 default50 value50rarr˓checkedfalse )

391 $(tsn_prc4)slider( unit min0 max100 default20 value20rarr˓checkedfalse )

392 $(tsn_spd4)slider( unitkph min0 max120 default66 value66rarr˓checkedfalse )

393

394 $(tsb_prc1)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

(continues on next page)

331 TLDR Examples 325

Open Vehicles

(continued from previous page)

395 $(tsb_spd1)slider( unitkph min0 max120 default33 value33rarr˓checkedfalse )

396 $(tsb_prc2)slider( unit min0 max100 default80 value80rarr˓checkedfalse )

397 $(tsb_spd2)slider( unitkph min0 max120 default39 value39rarr˓checkedfalse )

398 $(tsb_prc3)slider( unit min0 max100 default50 value50rarr˓checkedfalse )

399 $(tsb_spd3)slider( unitkph min0 max120 default50 value50rarr˓checkedfalse )

400 $(tsb_prc4)slider( unit min0 max100 default20 value20rarr˓checkedfalse )

401 $(tsb_spd4)slider( unitkph min0 max120 default66 value66rarr˓checkedfalse )

402

403

404 $(ramplimit_accel)slider( unit min1 max100 default30 value30rarr˓checkedfalse )

405 $(ramplimit_decel)slider( unit min0 max100 default30 value30rarr˓checkedfalse )

406 $(smooth)slider( unit min0 max100 default70 value70 checkedfalserarr˓)

407

408 $(ramp_start)slider( unitpermil min1 max250 default40 value40rarr˓checkedfalse )

409 $(ramp_accel)slider( unit min1 max100 default25 value25rarr˓checkedfalse )

410 $(ramp_decel)slider( unit min0 max100 default20 value20rarr˓checkedfalse )

411 $(ramp_neutral)slider( unit min0 max100 default40 value40rarr˓checkedfalse )

412 $(ramp_brake)slider( unit min0 max100 default40 value40rarr˓checkedfalse )

413

414 profile handling415

416 const keys = [417 checksum418 speed419 warn420 torque421 power_low422 power_high423 drive424 neutral425 brake426 tsd_spd1427 tsd_spd2428 tsd_spd3429 tsd_spd4430 tsd_prc1431 tsd_prc2432 tsd_prc3433 tsd_prc4434 tsn_spd1435 tsn_spd2436 tsn_spd3

(continues on next page)

326 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

437 tsn_spd4438 tsn_prc1439 tsn_prc2440 tsn_prc3441 tsn_prc4442 tsb_spd1443 tsb_spd2444 tsb_spd3445 tsb_spd4446 tsb_prc1447 tsb_prc2448 tsb_prc3449 tsb_prc4450 ramp_start451 ramp_accel452 ramp_decel453 ramp_neutral454 ramp_brake455 smooth456 brakelight_on457 brakelight_off458 ramplimit_accel459 ramplimit_decel460 autorecup_minprc461 autorecup_ref462 autodrive_minprc463 autodrive_ref464 current465 ]466

467 const scale = 468 autodrive_ref 01469 autorecup_ref 01470 471

472 var profile = 473

474 var plist = [475 label - title Working Set 476 label PWR title Power 477 label ECO title Economy 478 label ICE title Winter 479 ]480

481 load profile list482 var plistloader = loadcmd(config list xrt)then(function(data) 483 var lines = datasplit(n) line i key484 for (i = 0 i lt lineslength i++) 485 line = lines[i]match(profile([0-9]2)([^]) ())486 if (line ampamp linelength == 4) 487 key = Number(line[1])488 if (key lt 1 || key gt 99) continue489 if (plist[key]) plist[key] = 490 plist[key][line[2]||profile] = line[3]491 492 493 )

(continues on next page)

331 TLDR Examples 327

Open Vehicles

(continued from previous page)

494

495 current control rarr power ranges496 function currentControl(on trigger) 497 if (on) 498 $(input-torque input-power_low input-power_high)

rarr˓slider( max 254 )499 else 500 $(input-torque input-power_high)slider( max 130 )501 $(input-power_low)slider( max 139 )502 503 504 $(input-current)on(change function(ev) 505 currentControl(thischecked)506 $(input-torque input-power_low input-power_high)trigger(change)507 )508

509 load profile into sliders510 function loadProfile() 511 currentControl(profile[current] gt= 0)512 $map(profile function(val key) 513 $(input-+key)slider( value (val gt= 0) (val (scale[key]||1)) null

rarr˓checked (val gt= 0) )514 )515 516

517 calculate profile checksum518 function calcChecksum() 519 var checksum i520 checksum = 0x0101521 for (i=1 iltkeyslength i++)522 checksum += profile[keys[i]] + 1523 if ((checksum amp 0x0ff) == 0)524 checksum gtgt= 8525 return (checksum amp 0x0ff) - 1526 527

528 load a base64 string into profile529 function loadBase64(base64) 530 var bin = atob(base64)531 $map(keys function(key i) profile[key] = (bincharCodeAt(i)||0) - 1 )532 if (profile[checksum] == calcChecksum()) 533 loadProfile()534 return true535 else 536 confirmdialog(Profile Error Invalid base64 code (checksum mismatch) [

rarr˓Close])537 return false538 539 540

541 make a base64 string from profile542 function makeBase64() 543 profile[checksum] = calcChecksum()544 var u8 = new Uint8Array(keyslength)545 $map(keys function(key i) u8[i] = profile[key] + 1 )546 return btoa(StringfromCharCodeapply(null u8))547

(continues on next page)

328 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

548

549 load a profile550 function loadKey(key) 551 if (key lt 0 || key gt 99) return552 plistloaderthen(function() 553 $(input-label)val(plist[key] ampamp plist[key][label] || )554 $(input-title)val(plist[key] ampamp plist[key][title] || )555 loadcmd(xrt cfg get + key)fail(function(request textStatus errorThrown) 556 confirmdialog(Load Profile xhrErrorInfo(request textStatus errorThrown)

rarr˓[Close])557 )done(function(res) 558 var base64559 if (resmatch(errori))560 base64 = AQ561 else562 base64 = ressubstr(reslastIndexOf( )+1)563 if (loadBase64(base64)) 564 $(input-key)val(key)565 $(input-base64 input-base64-reset)val(base64)566 $(headkey)text( + key)567 568 )569 )570 571

572 save profile573 function saveKey(key) 574 if (key lt 0 || key gt 99) return575 var base64 = $(input-base64)val()576 label = $(input-label)val()replace(g )577 title = $(input-title)val()replace(g )578 ckey = profile + ((keylt10)0) + key579 var cmd = xrt cfg set + key + + base64 + + label + + title +

rarr˓580 loadcmd(cmd)fail(function(request textStatus errorThrown) 581 confirmdialog(Save Profile xhrErrorInfo(request textStatus errorThrown) [

rarr˓Close])582 )done(function(res) 583 confirmdialog(Save Profile res [Close])584 if (resmatch(errori)) 585 if (key gt 0) 586 if (plist[key]) plist[key] = 587 plist[key][label] = label588 plist[key][title] = title589 590 $(input-key)val(key)591 $(input-base64-reset)val(base64)592 $(headkey)text( + key)593 594 )595 596

597 base64 input598 $(input-base64)on(change function(ev) 599 var base64 = $(this)val() || AQ600 if (loadBase64(base64))601 $(input-base64-reset)val(base64)

(continues on next page)

331 TLDR Examples 329

Open Vehicles

(continued from previous page)

602 )603

604 update profile amp base64 on slider changes605 $(slider-value)on(change function(ev) 606 var key = thisname607 var val = Mathmax(thismin Mathmin(thismax 1thisvalue))608 profile[key] = thischecked (val (scale[key]||1)) -1609 var base64 = makeBase64()610 $(input-base64)val(base64)611 )612

613 prep key dialog614 $(key-dialog)dialog(615 show false616 onShow function(input) 617 var $this = $(this)618 $thisaddClass(loading)619 plistloaderthen(function(data) 620 var curkey = $(input-key)val() || 0 i label title621 $plist = $(ltdiv class=radio-list data-toggle=buttons gt)622 for (i = 0 i lt= Mathmin(99 plistlength + 2) i++) 623 if (plist[i] ampamp (i==0 || plist[i]profile)) 624 label = plist[i]label || -625 title = plist[i]title || (plist[i]profilesubstr(0 10) + )626 else 627 label = -628 title = -new-629 630 $plistappend(ltdiv class=radiogtltlabel class=btngt +631 ltinput type=radio name=key value= + i + gtltspan class=keygt +632 ((i==0) WS ( + ((ilt10)0) + i)) + ltspangt ltkbdgt +633 encode_html(label) + ltkbdgt + encode_html(title) + ltlabelgtltdivgt)634 635 $thisfind(modal-body)append($plist)find(input[value=+curkey+])636 prop(checked true)parent()addClass(active)637 $plist638 on(dblclick labelbtn function(ev) $thisdialog(triggerButton

rarr˓1) )639 on(keypress function(ev) if (evwhich==13) $thisdialog(triggerButton

rarr˓ 1) )640 $thisremoveClass(loading)641 )642 643 onShown function(input) 644 $(this)find(btnactive)focus()645 646 onHide function(input) 647 var $this = $(this) dlg = $thisdata(dialog)648 var key = $thisfind(input[name=key]checked)val()649 if (key == undefined ampamp inputbutton ampamp inputbuttonindex)650 dlgoptionsonActioncall(this key)651 652 )653

654 buttons655 $(action-new)on(click function(ev) 656 $(slider)slider( value null )

(continues on next page)

330 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

657 $(headkey)text(Editor)658 $(input-base64 input-label input-title)val()trigger(change)659 )660 $(action-reset)on(click function(ev) 661 $(input-base64)val($(input-base64-reset)val())trigger(change)662 )663 $(action-load)on(click function(ev) 664 $(key-dialog)dialog(665 show true title Load Profile body 666 buttons [ label Cancel btnClass default label Load btnClass

rarr˓primary ]667 onAction function(key) loadKey(key) 668 )669 )670 $(action-saveas)on(click function(ev) 671 $(key-dialog)dialog(672 show true title Save Profile body 673 buttons [ label Cancel btnClass default label Save btnClass

rarr˓primary ]674 onAction function(key) saveKey(key) 675 )676 )677 $(action-save)on(click function(ev) 678 var key = $(input-key)val()679 if (key === )680 $(action-saveas)trigger(click)681 else682 saveKey(key)683 )684

685 start load profile open load dialog686 if (pageparams[key] == undefined)687 loadKey(pageparams[key])688 else689 $(action-load)trigger(click)690

691 )()692 ltscriptgt

331 TLDR Examples 331

Open Vehicles

33117 Twizy Drivemode Button Editor

This plugin has been added to the Twizy code Itrsquos used here as a more complex example of what can be done byplugins

Itrsquos an editor for the drivemode buttons the Twizy adds to the dashboard for quick tuning profile changes The editorallows to change the layout (number and order of buttons) and the profiles to use

It includes a profile selector built with the dialog widget that retrieves the available profiles from the OVMS configstore

Install not necessary if vehicle Twizy is configured (see ldquoTwizyrdquo menu) If yoursquod like to test this for another vehicleadd as a page plugin eg testdmconfig

drivemode-confightm (hint right click save as)

1 lt--2 Twizy page plugin Drivemode Button Configuration3 Note included in firmware v324 --gt5

6 ltstylegt7 fullscreened panel-single panel-body 8 padding 10px9

10

11 btn-group-lggtbtn12 btn-lg 13 padding 10px 3px14 overflow hidden15 16 loadmenu btn 17 font-weight bold18 19 btn-groupbtn-group-lgexchange 20 width 221

(continues on next page)

332 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

22 editor btnhover 23 background-color e6e6e624 25 editor btn-group-lggtbtn26 editor btn-lg 27 padding 10px 0px28 font-size 15px29 30 editor exchange btn 31 font-weight bold32 33 night editor btn 34 color 00035 background 88836 37 night editor btnfocus38 night editor btnfocus39 night editor btnhover 40 background-color e0e0e041 42

43 radio-list 44 height 313px45 overflow-y auto46 overflow-x hidden47 padding-right 15px48 49 radio-list radio 50 overflow hidden51 52 radio-list key 53 min-width 20px54 display inline-block55 text-align center56 margin 0 10px57 58 radio-list kbd 59 min-width 60px60 display inline-block61 text-align center62 margin 0 20px 0 10px63 64 radio-list radio label 65 width 10066 text-align left67 padding 8px 30px68 69 radio-list radio labelactive 70 background-color 337ab771 color fff72 outline none73 74 radio-list radio labelactive input 75 outline none76 77 night radio-list radio labelhover 78 color fff

(continues on next page)

331 TLDR Examples 333

Open Vehicles

(continued from previous page)

79 80 ltstylegt81

82 ltdiv class=panel panel-primarygt83 ltdiv class=panel-headinggtDrivemode Button Configurationltdivgt84 ltdiv class=panel-bodygt85 ltform action=gt86

87 ltp id=infogtLoading button configurationltpgt88

89 ltdiv id=loadmenu class=btn-group btn-group-justifiedgtltdivgt90 ltdiv id=editor class=btn-group btn-group-justifiedgt91 ltdiv class=btn-group btn-group-lg add backgt92 ltbutton type=button class=btn title=Add buttongtltbuttongt93 ltdivgt94 ltdivgt95

96 ltbrgt97 ltbrgt98 ltdiv class=text-centergt99 ltbutton type=button class=btn btn-default onclick=reloadpage()gtResetlt

rarr˓buttongt100 ltbutton type=button class=btn btn-primary action-savegtSaveltbuttongt101 ltdivgt102

103 ltformgt104 ltdivgt105 ltdiv class=panel-footergt106 lta class=btn btn-sm btn-default target=main href=dashboardgtDashboardltagt107 lta class=btn btn-sm btn-default target=main href=xrtdrivemodegtDrivemodelt

rarr˓agt108 ltdivgt109 ltdivgt110

111 ltdiv id=key-dialog gt112

113 ltscriptgt114 (function()115

116 var $menu = $(loadmenu) $edit = $(editor) $back = $editfind(back)117

118 var pbuttons = [0123]119 var plist = [120 label STD title Standard 121 label PWR title Power 122 label ECO title Economy 123 label ICE title Winter 124 ]125

126 load profile list amp button config127 $(panel)addClass(loading)128 var plistloader = loadcmd(config list xrt)then(function(data) 129 var lines = datasplit(n) line i key130 for (i = 0 i lt lineslength i++) 131 line = lines[i]match(profile([0-9]2)([^]) ())132 if (line ampamp linelength == 4) 133 key = Number(line[1])

(continues on next page)

334 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

134 if (key lt 1 || key gt 99) continue135 if (plist[key]) plist[key] = 136 plist[key][line[2]||profile] = line[3]137 continue138 139 line = lines[i]match(profile_buttons ())140 if (line ampamp linelength == 2) 141 try 142 pbuttons = JSONparse([ + line[1] + ])143 catch (e) 144 consoleerror(e)145 146 147 148 )149

150 prep key dialog151 $(key-dialog)dialog(152 show false153 title Select Profile154 buttons [ label Cancel btnClass default label Select btnClass

rarr˓primary ]155 onShow function(input) 156 var $this = $(this) dlg = $thisdata(dialog)157 $thisaddClass(loading)158 plistloaderthen(function(data) 159 var curkey = dlgoptionskey || 0 i label title160 $plist = $(ltdiv class=radio-list data-toggle=buttons gt)161 for (i = 0 i lt= Mathmin(99 plistlength-1) i++) 162 if (plist[i] ampamp (i==0 || plist[i]profile)) 163 label = plist[i]label || -164 title = plist[i]title || (plist[i]profilesubstr(0 10) + )165 else 166 label = -167 title = -new-168 169 $plistappend(ltdiv class=radiogtltlabel class=btngt +170 ltinput type=radio name=key value= + i + gtltspan class=keygt +171 ((i==0) STD ( + ((ilt10)0) + i)) + ltspangt ltkbdgt +172 encode_html(label) + ltkbdgt + encode_html(title) + ltlabelgtltdivgt)173 174 $thisfind(modal-body)html($plist)find(input[value=+curkey+])175 prop(checked true)parent()addClass(active)176 $plist177 on(dblclick labelbtn function(ev) $thisdialog(triggerButton

rarr˓1) )178 on(keypress function(ev) if (evwhich==13) $thisdialog(triggerButton

rarr˓ 1) )179 $thisremoveClass(loading)180 )181 182 onShown function(input) 183 $(this)find(btnactive)focus()184 185 onHide function(input) 186 var $this = $(this) dlg = $thisdata(dialog)187 var key = $thisfind(input[name=key]checked)val()

(continues on next page)

331 TLDR Examples 335

Open Vehicles

(continued from previous page)

188 if (key == undefined ampamp inputbutton ampamp inputbuttonindex)189 dlgoptionsonActioncall(this key)190 191 )192

193 profile selection194 $(loadmenu)on(click button function(ev) 195 var $this = $(this)196 $(key-dialog)dialog(197 show true198 key $thisval()199 onAction function(key) 200 var prof = plist[key] || 201 $thisval(key)202 $thisattr(title proftitle || )203 $thistext(proflabel || (+((keylt10)0)+key))204 205 )206 )207

208 create buttons209

210 function addButton(key front) 211 var prof = plist[key] || 212 if ($menu[0]childElementCount == 0) 213 $backbefore(214 ltdiv class=btn-group btn-group-lg add frontgt215 ltbutton type=button class=btn title=Add buttongtltbuttongt216 ltdivgt217 ltdiv class=btn-group btn-group-lg removegt218 ltbutton type=button class=btn title=Remove buttongtltbuttongt219 ltdivgt)220 else 221 $backbefore(222 ltdiv class=btn-group btn-group-lg exchangegt223 ltbutton type=button class=btn title=Exchange buttonsgtltbuttongt224 ltdivgt225 ltdiv class=btn-group btn-group-lg removegt226 ltbutton type=button class=btn title=Remove buttongtltbuttongt227 ltdivgt)228 229 var $btn = $(230 ltdiv class=btn-group btn-group-lggt231 ltbutton type=button value=key class=btn btn-default title=titlegt

rarr˓labelltbuttongt232 ltdivgt233 replace(key key)234 replace(title encode_html(proftitle || ))235 replace(label encode_html(proflabel || +((keylt10)0)+key)))236 if (front)237 $menuprepend($btn)238 else239 $menuappend($btn)240 241

242 plistloaderthen(function() 243 var key prof

(continues on next page)

336 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

244 for (var i = 0 i lt pbuttonslength i++) 245 addButton(pbuttons[i])246 247 $(panel)removeClass(loading)248 $(info)text(Click button to select profile)249 )250

251 editor buttons252 $(editor)on(click add btn function(ev) 253 addButton(0 $(this)parent()hasClass(front))254 )on(click remove btn function(ev) 255 var $this = $(this) pos = $editfind(btn)index(this) gtgt 1256 $($menuchildren()get(pos))detach()257 if (pos gt 0 || $menu[0]childElementCount == 0)258 $thisparent()prev()detach()259 else if ($menu[0]childElementCount = 0)260 $thisparent()next()detach()261 $thisparent()detach()262 )on(click exchange btn function(ev) 263 var pos = $editfind(btn)index(this) gtgt 1264 if (pos gt 0) $($menuchildren()get(pos))insertBefore($($menuchildren()get(pos-

rarr˓1)))265 )266

267 save268 $(action-save)on(click function(ev) 269 pbuttons = []270 $menufind(btn)each(function() pbuttonspush(thisvalue) )271 loadcmd(config set xrt profile_buttons + pbuttonstoString())272 fail(function(request textStatus errorThrown) 273 confirmdialog(Save Configuration xhrErrorInfo(request textStatus

rarr˓errorThrown) [Close])274 )275 done(function(res) 276 confirmdialog(Save Configuration res [Close])277 )278 )279

280 )()281 ltscriptgt

332 Installing Plugins

The framework supports installing user content as pages or extensions to pages To install an example

1 Menu Config rarr Web Plugins

2 Add plugin type ldquoPagerdquo name eg ldquodevmetricsrdquo (used as the file name in storeplugin)

3 Save rarr Edit

4 Set page to eg ldquousrdevmetricsrdquo label to eg ldquoDev Metricsrdquo

5 Set the menu to eg ldquoToolsrdquo and auth to eg ldquoNonerdquo

6 Paste the page source into the content area

332 Installing Plugins 337

Open Vehicles

7 Save rarr the page is now accessible in the ldquoToolsrdquo menu

Hint use the standard editor (tools menu) in a second session to edit a plugin repeatedly during test development

333 Basics

The OVMS web framework is based on HTML 5 Bootstrap 3 and jQuery 3 Plenty documentation and guides onthese basic web technologies is available on the web a very good resource is w3schoolscom

For charts the framework includes Highcharts 6 Info and documentation on this is available on Highchartscom

The framework is ldquoAJAXrdquo based The index page loads the framework assets and defines a default container structureincluding a menu and a main container Content pages are loaded into the main container The window URLincludes the page URL after the hash mark

bull httpovmslocalstatus ndash this loads page status into main

bull httpovmslocaldashboardnm=1 ndash this loads the dashboard and activates night mode

Links and forms having id targets are automatically converted to AJAX by the framework

bull lta href=editpath=sdindextxt target=maingtEdit indextxtltagt ndash loadthe editor

Pages can be loaded outside the framework as well (eg httpovmslocalstatus) See index source onframework scripts and styles to include if yoursquod like to design standalone pages using the framework methods

If file system access is enabled all URLs not handled by the system or a user plugin (see below) are mapped onto thefile system under the configured web root Of course files can be loaded into the framework as well For example ifthe web root is sd (default)

bull httpovmslocalmypagehtm ndash load file sdmypagehtm into main

bull httptest1locallogs ndash load directory listing sdlogs into main

Important Note the framework has a global shared context (ie the window object) To avoid polluting the globalcontext with local variables good practice is to wrap your local scripts into closures Pattern

ltscriptgt(function()

insert your code here )()ltscriptgt

334 Authorization

Page access can be restricted to authorized users either session based or per access File access can be restricted usingdigest authentication

The module password is used for all authorizations A user account or API key administration is not yet included themain username is admin

To create a session call the login page and store the resulting cookie

1 curl -c auth -b auth http19216841login -d username=admin -dpassword=

2 curl -c auth -b auth http19216841apiexecutecommand=xrt+cfg+info

338 Chapter 33 Web Framework amp Plugins

Open Vehicles

To issue a single call eg to execute a command from a Wifi button supply the password as apikey

bull curl http19216841apiexecuteapikey=passwordampcommand=xrt+cfg+info

bull curl http19216841apiexecuteapikey=passwordamptype=jsampcommand=print(Duktapeversion)

335 Web UI Development Framework

To simplify and speed up UI and plugin development you can simply run a local web server from the dev directoryof the ovms_webserver component source

Preparation create your local git clone if you donrsquot have one already

gt cd ~gt git clone httpsgithubcomopenvehiclesOpen-Vehicle-Monitoring-System-3git

Local web server options List of static web servers

Example

gt cd ~Open-Vehicle-Monitoring-System-3vehicleOVMSV3componentsovms_webserverdevgt python3 -m httpserver 8000Serving HTTP on 0000 port 8000 (http00008000)

Now open the development framework in your browser at URI httplocalhost8000 If that doesnrsquot workcheck your firewall settings for port 8000 on localhost

You should see the examples home Edit indexhtm to add custom menus edit homehtm to add custom homebuttons

Hint to test your plugin for mobile devices use the mobile emulation mode of your browserrsquos development toolkitMobile mode allows to test small screen resolutions rotation and touch events

A static local HTTP server allows to use all frontend features but cannot emulate the backend API (commandscriptexecution) If using a CGI capable HTTP server you can also add a proxy handler for apiexecute that forwardsthe requests to your module by HTTP or SSH

If you want to add your results to a C++ module use the tools mksrc and mksrcf to convert your HTML files intoC++ compatible strings mksrc is meant for static strings mksrcf for strings with printf style placeholders

335 Web UI Development Framework 339

Open Vehicles

340 Chapter 33 Web Framework amp Plugins

CHAPTER 34

Scripting

341 Example Foglight

This is an example for combining a script module implementing some functional extension with a web plugin toprovide a user interface

The plugin realizes a fog light with automatic speed adaption ie the light will be turned off above a configurablespeed and on again when the vehicle slows down again It also switches off automatically when the vehicle is parked

The plugin shows how to

bull read custom config variables

bull use module state variables

341

Open Vehicles

bull react to events

bull send custom events

bull read metrics

bull execute system commands

bull provide new commands

bull provide a web UI

3411 Installation

bull Save foglightjs as storescriptslibfoglightjs (add the lib directory as necessary)

bull Add foglighthtm as a web hook type plugin at page dashboard hook bodypre

bull Execute script eval foglight = require(libfoglight)

Optionally

bull To test the module execute script eval foglightinfo() ndash it should print config and state

bull To automatically load the module on boot add the line foglight = require(libfoglight) tostorescriptsovmsmainjs

3412 Commands Functions

The module provides two public API functions

Function Descriptionfoglightset(onoff) switch fog light on (1) off (0)foglightinfo() output config amp state in JSON format

To call these from a shell use script eval Example

bull script eval foglightset(1)

3413 Configuration

Wersquoll add the configuration for this to the vehicle section

Config Default Descriptionfoglightport 1 EGPIO output port numberfoglightauto no yes = speed automationfoglightspeedon 45 auto turn on below this speedfoglightspeedoff 55 auto turn off above this speed

Note You can add arbitrary config instances to defined sections simply by setting them config set vehiclefoglightauto yes

342 Chapter 34 Scripting

Open Vehicles

Update Beginning with firmware release 32009 a general configuration section usr is provided for plugins Werecommend using this for all custom parameters now Keep in mind to prefix all instances introduced by the pluginname so your plugin can nicely coexist with others

To store the config for simple amp quick script access and implement the defaults we introduce an internal modulemember object cfg

Listing 1 Module Plugin

28 var cfg = 29 foglightport 130 foglightauto no31 foglightspeedon 4532 foglightspeedoff 5533

By foglight = require() the module is added to the global name space as a javascript object This objectcan contain any internal standard javascript variables and functions Internal members are hidden by default if youwould like to expose the cfg object you would simply add a reference to it to the exports object as is done belowfor the API methods

Reading OVMS config variables from a script currently needs to be done by executing config list and parsingthe output This is done by the readconfig() function

42 function readconfig() 43 var cmdres lines cols i44 cmdres = OvmsCommandExec(config list vehicle)45 lines = cmdressplit(n)46 for (i=0 iltlineslength i++) 47 if (lines[i]indexOf(foglight) gt= 0) 48 cols = lines[i]substr(2)split( )49 cfg[cols[0]] = cols[1]50 51

Update OVMS release 32009 adds the OvmsConfigGetValues() API To use this we would now omit theldquofoglightrdquo prefix from our cfg properties Reading the foglight configuration can then be reduced to a single line

Objectassign(cfg OvmsConfigGetValues(vehicle foglight))

3414 Listen to Events

The module needs to listen to three events

bull configchanged triggers reloading the configuration

bull ticker1 is used to check the speed once per second

bull vehicleoff automatically also turns off the fog light

The per second ticker is only necessary when the speed adaption is enabled so we can use this to show how todynamically add and remove event handlers through the PubSub API

341 Example Foglight 343

Open Vehicles

Listing 2 Module Plugin

52 update ticker subscription53 if (cfg[foglightauto] == yes ampamp stateticker) 54 stateticker = PubSubsubscribe(ticker1 checkspeed)55 else if (cfg[foglightauto] = yes ampamp stateticker) 56 PubSubunsubscribe(stateticker)57 stateticker = false58

state is another internal object for our state variables

3415 Send Events

Sending custom events is a lightweight method to inform the web UI (or other plugins) about simple state changes Inthis case wersquod like to inform listeners when the fog light actually physically is switched on or off so the web UI cangive visual feedback to the driver on this

Beginning with firmware release 32006 there is a native API OvmsEventsRaise() available to send events

Before 32006 we simply use the standard command event raise

Listing 3 Module Plugin

61 EGPIO port control62 function toggle(onoff) 63 if (stateport = onoff) 64 OvmsCommandExec(egpio output + cfg[foglightport] + + onoff)65 stateport = onoff66 OvmsCommandExec(event raise usrfoglight + (onoff on off))67 68

The web plugin subscribes to the foglight events just as to any system event

Listing 4 Web Plugin

64 Listen to foglight events65 $(foglight)on(msgevent function(e event) 66 if (event == usrfoglighton)67 update( state port 1 )68 else if (event == usrfoglightoff)69 update( state port 0 )70 else if (event == vehicleoff) 71 update( state on 0 )72 $(action-foglight-output)empty()73 74 )

Note You can raise any event you like but you shouldnrsquot raise system events without good knowledge of theireffects Event codes are simply strings so yoursquore free to extend them Use the prefix usr for custom events to avoidpotential conflicts with future system event additions

344 Chapter 34 Scripting

Open Vehicles

3416 Read Metrics

Reading metrics is straight forward through the OvmsMetrics API

Listing 5 Module Plugin

74 var speed = OvmsMetricsAsFloat(vpspeed)

Use Value() instead of AsFloat() for non-numerical metrics

Note You cannot subscribe to metrics changes directly (yet) Metrics can change thousands of times per secondwhich would overload the scripting capabilities To periodically check a metric register for a ticker event (as shownhere)

3417 Provide Commands

To add commands simply expose their handler functions through the exports object By this users will be able tocall these functions using the script eval command from any shell or from any script by referencing them viathe global module variable foglight in our case

Listing 6 Module Plugin

99 API method foglightinfo()100 exportsinfo = function() 101 JSONprint( cfg cfg state state )102

JSONprint() is a convenient way to communicate with a web plugin as that wonrsquot need to parse some potentiallyambigous textual output but can simply use JSONparse() to read it into a variable

Listing 7 Web Plugin

82 Init amp install83 $(main)one(load function(ev) 84 loadcmd(script eval foglightinfo())then(function(output) 85 update(JSONparse(output))

Note Keep in mind commands should always output some textual response indicating their action and result If acommand does nothing it should tell the user so If a command is not intended for shell use it should still providesome clue about this when called from the shell

3418 Module Plugin

foglightjs (hint right click save as)

1 2 storescriptslibfoglightjs3 4 Module plugin5 Foglight control with speed adaption and auto off on vehicle off

(continues on next page)

341 Example Foglight 345

Open Vehicles

(continued from previous page)

6 7 Version 10 Michael Balzer ltdexterdexters-webdegt8 9 Enable

10 - install at above path11 - add to storescriptsovmsmainjs12 foglight = require(libfoglight)13 - script reload14 15 Config16 - vehicle foglightport EGPIO output port number17 - vehicle foglightauto yes = speed automation18 - vehicle foglightspeedon auto turn on below this speed19 - vehicle foglightspeedoff auto turn off above this speed20 21 Usage22 - script eval foglightset(1) toggle foglight on23 - script eval foglightset(0) toggle foglight off24 - script eval foglightinfo() show config amp state (JSON)25 26 27

28 var cfg = 29 foglightport 130 foglightauto no31 foglightspeedon 4532 foglightspeedoff 5533 34

35 var state = 36 on 0 foglight onoff37 port 0 current port output state38 ticker false ticker subscription39 40

41 Read config42 function readconfig() 43 var cmdres lines cols i44 cmdres = OvmsCommandExec(config list vehicle)45 lines = cmdressplit(n)46 for (i=0 iltlineslength i++) 47 if (lines[i]indexOf(foglight) gt= 0) 48 cols = lines[i]substr(2)split( )49 cfg[cols[0]] = cols[1]50 51 52 update ticker subscription53 if (cfg[foglightauto] == yes ampamp stateticker) 54 stateticker = PubSubsubscribe(ticker1 checkspeed)55 else if (cfg[foglightauto] = yes ampamp stateticker) 56 PubSubunsubscribe(stateticker)57 stateticker = false58 59 60

61 EGPIO port control62 function toggle(onoff)

(continues on next page)

346 Chapter 34 Scripting

Open Vehicles

(continued from previous page)

63 if (stateport = onoff) 64 OvmsCommandExec(egpio output + cfg[foglightport] + + onoff)65 stateport = onoff66 OvmsCommandExec(event raise usrfoglight + (onoff on off))67 68 69

70 Check speed71 function checkspeed() 72 if (stateon)73 return74 var speed = OvmsMetricsAsFloat(vpspeed)75 if (speed lt= cfg[foglightspeedon])76 toggle(1)77 else if (speed gt= cfg[foglightspeedoff])78 toggle(0)79 80

81 API method foglightset(onoff)82 exportsset = function(onoff) 83 if (onoff) 84 stateon = 185 if (cfg[foglightauto] == yes) 86 checkspeed()87 print(Foglight AUTO moden)88 else 89 toggle(1)90 print(Foglight ONn)91 92 else 93 stateon = 094 toggle(0)95 print(Foglight OFFn)96 97 98

99 API method foglightinfo()100 exportsinfo = function() 101 JSONprint( cfg cfg state state )102 103

104 Init105 readconfig()106 PubSubsubscribe(configchanged readconfig)107 PubSubsubscribe(vehicleoff function() exportsset(0) )

3419 Web Plugin

foglighthtm (hint right click save as)

1 lt--2 foglighthtm Web plugin for hook dashboardbodypre3 - add button to activatedeactivate foglight4 - add indicator to show current foglight state5

(continues on next page)

341 Example Foglight 347

Open Vehicles

(continued from previous page)

6 Requires module plugin foglightjs7

8 Version 10 Michael Balzer ltdexterdexters-webdegt9 --gt

10

11 ltstylegt12 foglight 13 margin 10px 8px 014 15 foglight indicator gt label 16 font-size 13017 line-height 16018 margin 0px19 padding 10px20 display block21 border-radius 50px22 23 ltstylegt24

25 ltdiv class=receiver id=foglight style=displaynonegt26 ltformgt27 ltdiv class=form-groupgt28 ltdiv class=col-xs-6gt29 ltdiv class=indicator indicator-foglightgt30 ltspan class=label label-defaultgtFOGLIGHTltspangt31 ltdivgt32 ltdivgt33 ltdiv class=col-xs-6gt34 ltdiv class=btn-group btn-group-justified action-foglight-set data-toggle=

rarr˓buttonsgt35 ltlabel class=btn btn-default action-foglight-0gtltinput type=radio name=

rarr˓foglight value=0gtOFFltlabelgt36 ltlabel class=btn btn-default action-foglight-1gtltinput type=radio name=

rarr˓foglight value=1gtONAUTOltlabelgt37 ltdivgt38 ltsamp id=action-foglight-output class=text-centergtltsampgt39 ltdivgt40 ltdivgt41 ltformgt42 ltdivgt43

44 ltscriptgt45 (function()46

47 var foglight = cfg state on 0 port 0 48 var $indicator = $(foglight indicator-foglight gt label)49 var $actionset = $(foglight action-foglight-set gt label)50

51 State amp UI update52 function update(data) 53 $extend(true foglight data)54 update indicator55 if (foglightstateport)56 $indicatorremoveClass(label-default)addClass(label-danger)57 else58 $indicatorremoveClass(label-danger)addClass(label-default)59 update buttons

(continues on next page)

348 Chapter 34 Scripting

Open Vehicles

(continued from previous page)

60 $actionsetremoveClass(active)61 $actionsetfind(input[value=+foglightstateon+])prop(checked true)

rarr˓parent()addClass(active)62 63

64 Listen to foglight events65 $(foglight)on(msgevent function(e event) 66 if (event == usrfoglighton)67 update( state port 1 )68 else if (event == usrfoglightoff)69 update( state port 0 )70 else if (event == vehicleoff) 71 update( state on 0 )72 $(action-foglight-output)empty()73 74 )75

76 Button action77 $(foglight action-foglight-set input)on(change function(e) 78 foglightstateon = $(this)val()79 loadcmd(script eval foglightset(+foglightstateon+) action-foglight-

rarr˓output)80 )81

82 Init amp install83 $(main)one(load function(ev) 84 loadcmd(script eval foglightinfo())then(function(output) 85 update(JSONparse(output))86 $(foglight)appendTo(panel-dashboard panel-body)show()87 )88 )89

90 )()91 ltscriptgt

341 Example Foglight 349

Open Vehicles

350 Chapter 34 Scripting

CHAPTER 35

CANopen

351 CANopen Basics

3511 Communication Objects

A CANopen network consists of ldquomastersrdquo and ldquoslavesrdquo masters are clients slaves are servers At most one mastermay be active at a time

CANopen supports addressing of up to 127 slaves on a bus using node IDs 1-127 Node address 0 is used for broadcaststo all nodes Node addressing is simply mapped onto CAN IDs by adding the node id to a base ID

The CANopen protocol mainly consists of

bull PDO (process data objects)

bull SDO (service data objects)

bull NMT (network management)

bull SYNC (synchronisation)

bull EMCY (emergency events)

PDO are regular normally periodical status update frames for example sensor data You can log them using theCAN monitor (can log start monitor ) PDOs can be sent at any CAN ID except those reserved forother CANopen services

SDO are memory registers of nodes that can be read and written by masters on request SDO requests are normally sentat ID 0x600 + nodeid responses at ID 0x580 + nodeid SDOs are addressed by a 16 bit index + 8 bit subindex Reg-isters and data types for a given device are documented by the device specific object dictionary normally representedas an EDS (electronic data sheet) file

NMT are short datagrams to control node startup shutdown Therersquos a special node state ldquopre-operationalrdquo allowingaccess to all operation and communication parameters of a node in a standardized way NMT requests are sent at ID0x000 responses and unsolicited updates (aka heartbeats) are sent at ID 0x700 + nodeid with length 1

SYNC messages are datagrams of length 0 normally sent at ID 0x080

351

Open Vehicles

EMCY messages are sent if a node encounters some kind of alert or warning condition they are normally sent at ID0x080 + nodeid with a length of 8 bytes

CAN IDs Communication objects0x000 NMT requests0x080 SYNC0x081 - 0x0FF EMCY0x581 - 0x5FF SDO responses0x601 - 0x67F SDO requests0x701 - 0x77F NMT responses heartbeats

So if any of these IDs look familiar to you chances are yoursquove got a CANopen network

Note CANopen coexists nicely with OBD-II and often does in a vehicle (ie Renault Twizy) OBD-II devicesnormally are addressed at IDs gt 0x780 so are outside the CANopen ID range Even if they use non-standard IDs thedevices normally will detect and ignore frames not matching their protocol

3512 SDO Addresses

The SDO address space layout is standardized

Index (hex) Object0000 not used0001-001F Static Data Types0020-003F Complex Data Types0040-005F Manufacturer Specific Complex Data Types0060-007F Device Profile Specific Static Data Types0080-009F Device Profile Specific Complex Data Types00A0-0FFF Reserved for further use1000-1FFF Communication Profile Area2000-5FFF Manufacturer Specific Profile Area6000-9FFF Standardised Device Profile AreaA000-BFFF Standardised Interface Profile AreaC000-FFFF Reserved for further use

See CiA DS301 for details on standard SDOs

For example a device shall tell about the PDOs it transmits or listens to their IDs update frequency and contentstructure at SDO registers 1400-1BFF This is mandatory in theory but real devices may not fully comply to that rule

CANopen compliant standard device types like motor controllers need to implement some standard profile registersSee CiA DS401 for the generic IO device class definition and CiA DS402 for motor controllers

Most devices will require some kind of login before allowing you to change operational parameters This is also doneusing SDO writes but there is no standard for this so yoursquoll need to dig into the device documentation

Of course therersquos a lot more on CANopen but this should get you going

3513 CAN in Automation

More info on the standard and specific device profiles can be found on the CiA website

352 Chapter 35 CANopen

Open Vehicles

httpswwwcan-ciaorg

CAN in Automation (CiA) is the international usersrsquo and manufacturersrsquo group for the CAN network (Controller AreaNetwork) internationally standardized in the ISO 11898 series The nonprofit association was established in 1992The aim is to provide an unbiased platform for future developments of the CAN protocol and to promote the image ofthe CAN technology

352 How to detect and identify CANopen nodes

So yoursquove got a CAN bus with some devices but you donrsquot know which of them speaks ldquoCANopenrdquo if any TheOVMS v3 will help you to detect them and open their CANs )

3521 Before you begin

you need to activate the CAN bus(es) yoursquore going to use As a CANopen master needs to write to the networkyou need to start the interfaces in active mode ie

OVMS can can1 start active 500000OVMS can can2 start active 125000

and then start the CANopen master for the bus(es) ie

OVMS copen can1 startOVMS copen can2 start

3522 Detecting CANopen nodes

The ldquoopenrdquo in ldquoCANopenrdquo means any implementation can decide how much of the standard it implements There aresome few mandatory features though a CANopen slave has to implement if it wants to comply with the standard

The mandatory features helping to detect and identify CANopen nodes on a CAN bus are

bull NMT (network management) especially RESET and PREOP

bull NMT bootup event messages

bull Standard SDO access in pre-operational mode

If yoursquove got CANopen nodes on a bus even silent ones issuing copen nmt reset will tell all of them toreboot and as bootup messages are mandatory you will see them in the OVMS log output like this

I (162904) canopen can1 node 1 new state Booting

The OVMS CANopen master continously monitors the network for NMT and EMCY messages After bootup of allnodes you can get a list of all nodes that have been detected by issuing metrics list co

OVMS metrics list cococan1nd1emcycodecocan1nd1emcytypecocan1nd1state Operational

Note if you request a reset nodes may decide to boot into pre-operational state That may produce some errormessages Donrsquot worry you can resolve this anytime by issuing copen nmt start

352 How to detect and identify CANopen nodes 353

Open Vehicles

3523 Identifying CANopen nodes

In pre-operational state a CANopen node must be accessible at the CANopen default IDs That means if the nodesupports SDO access we can query some standard attributes from it

Thatrsquos what copen info and copen scan do

bull copen info queries the standard device attributes from a specific node

bull copen scan queries all 127 node IDs

Caution There may be non-CANopen devices on the bus producing regular data frames at CANopen responseIDs andor reading and possibly misinterpreting CANopen requests sent to node IDs not planned by the manufac-turer Chances are low this triggers problems but you should be ready to switch off the vehicle when doing a scanndash just in case

A complete scan takes about 20 seconds A typical scan could look like this

OVMS level debug canopenOVMS copen can1 scanScan 1-127Node 1

Device type 0x00000000Error state 0x00Vendor ID 0x0000001eProduct 0x0712302dRevision 0x00010019SN 0x47c5Device name Gen4 (Renault Twizy)11 November 2011 12HW version 0x00000003SW version 07120001

Node 23 SDO access failedNode 25 SDO access failedNode 27 SDO access failedNode 30 SDO access failedNode 87 SDO access failedDoneD (227994) canopen ReadSDO 23 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (228194) canopen ReadSDO 25 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (228444) canopen ReadSDO 27 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (228844) canopen ReadSDO 30 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (238384) canopen ReadSDO 87 0x100000 InitUpload failed CANopen error coderarr˓0xffffffff

This means one CANopen node was found and some non-CANopen frames were received on IDs 0x580 +23 +25+27 +30 and +87

3524 Great What now

As you now know therersquos a CANopen node you can look for documentation on it You can also try to access moredefault SDOs to see if you can control and configure the node

354 Chapter 35 CANopen

Open Vehicles

bull If yoursquore lucky the device will provide its own EDS file at SDO 102100 You can check that by issuing

OVMS copen ltbusgt readsdo ltnodeidgt 1021 0

bull Check out the CiA specifications for CANopen standards for example

ndash DS301 for details on general standard SDOs

ndash DS401 for the generic IO device class definition

ndash DS402 for motor controller SDOs

bull Look up the manufacturer of your device by itrsquos vendor ID

httpswwwcan-ciaorgservicescanopen-vendor-id

bull Contact the manufacturer of your device for specific documentation and EDS files

353 CANopen Shell Commands

Show status report

copen status

Start stop workers

copen ltbusgt startcopen ltbusgt stop

bull stop will fail if clients are still running

Send NMT commands

copen ltbusgt nmt ltstart|stop|preop|reset|commresetgt [id=0] [timeout_ms=0]

bull id 0 = broadcast

bull timeout gt 0 wait for state change (heartbeat) 3 tries Note state change response is not a mandatoryCANopen feature

Read SDO

copen ltbusgt readsdo ltidgt ltindex_hexgt ltsubindex_hexgt [timeout_ms=50]

bull index amp subindex hexadecimal without ldquo0xrdquo or ldquohrdquo

bull defaults to 3 tries on timeout

Write SDO

copen ltbusgt writesdo ltidgt ltindex_hexgt ltsubindex_hexgt ltvaluegt [timeout_ms=50]

bull index amp subindex hexadecimal without ldquo0xrdquo or ldquohrdquo

bull value prefix ldquo0xrdquo = hex else decimal string if no decimal

bull defaults to 3 tries on timeout

Show node core attributes

353 CANopen Shell Commands 355

Open Vehicles

copen ltbusgt info ltidgt [timeout_ms=50]

bull prints device type error register device name etc

bull Note some attributes read are optional and may be emptyzero

Scan bus for nodes

copen ltbusgt scan [[startid=1][-][endid=127]] [timeout_ms=50]

bull loops ldquoinfordquo over multiple node ids (default all)

bull Note a full scan with default timeout takes ~20 seconds

354 CANopen API Usage

3541 Synchronous API

The synchronous use is very simple all you need is a CANopenClient instance

On creation the client automatically connects to the active CANopen worker or starts a new worker instance if neces-sary

The CANopenClient methods will block until the job is done (or has failed) Job results andor error details arereturned in the caller provided job

Caution Do not make synchronous calls from code that may run in a restricted context eg within a metricupdate handler Avoid using synchronous calls from time critical code eg a CAN or event handler

Example

include canopenh

find CAN interfacecanbus bus = (canbus) MyPcpAppFindDeviceByName(can1) or simply use m_can1 if youre a vehicle subclass

create CANopen clientCANopenClient client(bus)

a CANopen job holds request and response dataCANopenJob job

read value from node 1 SDO 0x100800uint32_t valueif (clientReadSDO(ampjob 1 0x1008 0x00 (uint8_t)ampvalue sizeof(value)) == COR_OK) read result is now in value

start node 2 wait for presenceif (clientSendNMT(ampjob 2 CONC_Start true) == COR_OK)

node 2 is now started

(continues on next page)

356 Chapter 35 CANopen

Open Vehicles

(continued from previous page)

write value into node 3 SDO 0x234518if (clientWriteSDO(ampjob 3 0x2345 0x18 (uint8_t)ampvalue 0) == COR_OK)

value has now been written into register 0x234518

Main API methods

SendNMT send NMT request and optionally wait for NMT state change

aka heartbeat message

Note NMT responses are not a part of the CANopen NMT protocol and

sending heartbeat NMT state updates is optional for CANopen nodes

If the node sends no state info waiting for it will result in timeout

even though the state has in fact changed -- theres no way to know

if the node doesnt tell

CANopenResult_t SendNMT(CANopenJobamp job

uint8_t nodeid CANopenNMTCommand_t commandbool wait_for_state=false int resp_timeout_ms=1000 int max_tries=3)

ReceiveHB wait for next heartbeat message of a node

return state received

Use this to read the current state or synchronize to the heartbeat

Note heartbeats are optional in CANopen

CANopenResult_t ReceiveHB(CANopenJobamp job

uint8_t nodeid CANopenNMTState_t statebuf=NULLint recv_timeout_ms=1000 int max_tries=1)

ReadSDO read bytes from SDO server into buffer

- reads data into buf (up to bufsize bytes)

- returns data length read in jobsdoxfersize

- and data length available in jobsdocontsize (if known)

- remaining buffer space will be zeroed

- on result COR_ERR_BufferTooSmall the buffer has been filled up to bufsize

- on abort the CANopen error code can be retrieved from jobsdoerror

Note result interpretation is up to caller (check device object dictionary

for data types amp sizes) As CANopen is little endian as ESP32 we dont

need to check lengths on numerical results ie anything from int8_t to

uint32_t can simply be read into a uint32_t buffer

CANopenResult_t ReadSDO(CANopenJobamp job

uint8_t nodeid uint16_t index uint8_t subindex uint8_t buf size_t bufsizeint resp_timeout_ms=50 int max_tries=3)

WriteSDO write bytes from buffer into SDO server

- sends bufsize bytes from buf

- or 4 bytes from buf if bufsize is 0 (use for integer SDOs of unknown type)(continues on next page)

354 CANopen API Usage 357

Open Vehicles

(continued from previous page)

- returns data length sent in jobsdoxfersize

- on abort the CANopen error code can be retrieved from jobsdoerror

Note the caller needs to know data type amp size of the SDO register (check

device object dictionary) As CANopen servers normally are intelligent

anything from int8_t to uint32_t can simply be sent as a uint32_t with

bufsize=0 the server will know how to convert it

CANopenResult_t WriteSDO(CANopenJobamp job

uint8_t nodeid uint16_t index uint8_t subindex uint8_t buf size_t bufsizeint resp_timeout_ms=50 int max_tries=3)

If you want to create custom jobs use the low level method ExecuteJob() to execute them

3542 Asynchronous API

The CANopenAsyncClient class provides the asynchronous interface and the response queue

To use the asynchronous API you need to handle asynchronous responses which normally means adding a dedicatedtask for this A minimal handling would be to simply discard the responses (just empty the queue) if you donrsquot needto care about the results

Example

Instantiate the async client for a CAN bus and a queue size like this

CANopenAsyncClient m_async(m_can1 50)

Example response handler task

void MyAsyncTask()

CANopenJob jobwhile (true) if (m_asyncReceiveDone(job portMAX_DELAY) = COR_ERR_QueueEmpty)

process job results

Sending requests is following the same scheme as with the synchronous API Standard result code is COR_WAIT anerror may occur if the queue is full

if (m_asyncWriteSDO(m_nodeid index subindex (uint8_t)value 0) = COR_WAIT) handle error

Main API methods

The API methods are similar to the synchronous methods (see above)

358 Chapter 35 CANopen

Open Vehicles

CANopenResult_t SendNMT(uint8_t nodeid CANopenNMTCommand_t commandbool wait_for_state=false int resp_timeout_ms=1000 int max_tries=3)

CANopenResult_t ReceiveHB(uint8_t nodeid CANopenNMTState_t statebuf=NULLint recv_timeout_ms=1000 int max_tries=1)

CANopenResult_t ReadSDO(uint8_t nodeid uint16_t index uint8_t subindexuint8_t buf size_t bufsizeint resp_timeout_ms=100 int max_tries=3)

CANopenResult_t WriteSDO(uint8_t nodeid uint16_t index uint8_t subindexuint8_t buf size_t bufsizeint resp_timeout_ms=100 int max_tries=3)

CANopenJob objects are created automatically by these methods Jobs done need to be fetched by loopingReceiveDone() until it returns COR_ERR_QueueEmpty

If you want to create custom jobs use the low level method SubmitJob() to add them to the worker queue

3543 Error Handling

If an error occurs it will be given as a CANopenResult_t other than COR_OK or COR_WAIT either by a methodresult or by the CANopenJobresult field

Result codes are

COR_OK = 0

API levelCOR_WAIT job waiting to be processedCOR_ERR_UnknownJobTypeCOR_ERR_QueueFullCOR_ERR_QueueEmptyCOR_ERR_NoCANWriteCOR_ERR_ParamRangeCOR_ERR_BufferTooSmall

Protocol levelCOR_ERR_TimeoutCOR_ERR_SDO_AccessCOR_ERR_SDO_SegMismatch

General purpose application levelCOR_ERR_DeviceOffline = 0x80COR_ERR_UnknownDeviceCOR_ERR_LoginFailedCOR_ERR_StateChangeFailed

Additionally if an SDO readwrite error occurs an abortion error code may be given by the slave These codes followthe CANopen standard and may be extended by device specific codes

To translate a CANopenResult_t andor a known SDO abort code into a string use the CANopen class utilitymethods

stdstring GetAbortCodeName(const uint32_t abortcode)stdstring GetResultString(const CANopenResult_t result)

(continues on next page)

354 CANopen API Usage 359

Open Vehicles

(continued from previous page)

stdstring GetResultString(const CANopenResult_t result const uint32_t abortcode)stdstring GetResultString(const CANopenJobamp job)

Example

if (jobresult = COR_OK) ESP_LOGE(TAG Result for s sCANopenGetJobName(job)c_str()CANopenGetResultString(job)c_str())

3544 Custom Address Schemes

The standard clients use the CiA DS301 default IDs for node addressing ie

NMT request rarr 0x000NMT response rarr 0x700 + nodeidSDO request rarr 0x600 + nodeidSDO response rarr 0x580 + nodeid

If you need another address scheme create a sub class of CANopenAsyncClient or CANopenClient and over-ride the Init() methods as necessary

3545 More Code Examples

bull See shell commands in canopen_shellcpp

bull See classes SevconClient and SevconJob in the Twizy SEVCON module

360 Chapter 35 CANopen

CHAPTER 36

OVMS Server

361 Welcome

The OVMS (Open Vehicle Monitoring System) team is a group of enthusiasts who are developing a means to remotelycommunicate with our cars and are having fun while doing it

The OVMS module is a low-cost hardware device that you install in your car simply by installing a SIM card con-necting the module to your carrsquos Diagnostic port connector and positioning a cellular antenna Once connected theOVMS module enables remote control and monitoring of your car

This guide documents the installation and operation of an OVMS server

You should however start by asking yourself the question lsquodo I need thisrsquo You donrsquot need to run your own OVMSserver as you can just use one of the public Open Vehicles OVMS servers The choice is yours

362 Installation

3621 Prerequisites

Yoursquoll need a Linux OSX BSD or other flavour of Unix server with a public IP address and a shell account able tosetup a daemon listening on a port Yoursquoll need a modern version of perl running on that server and a bunch of perlmodules (from cpan)

Yoursquoll need a MYSQL server running on the same machine or another machine and credentials to be able to create adatabase and accounts

This could possibly run on a windows server but you are on your own -) [ let us know instructions if you manage toget it running ]

3622 Clone from GitHub

Start the installation with a clone from GitHub

361

Open Vehicles

git clone httpsgithubcomopenvehiclesOpen-Vehicle-Servergit

You can then change into the v3server directory and start the installation process

3623 Perl Module Installation

You will need at a minimum the following modules from CPAN (or from your distributionrsquos package manager)

bull ConfigIniFiles

bull DigestMD5

bull DigestHMAC

bull CryptRC4XS

bull MIMEBase64

bull DBI

bull DBDmysql

bull EV

bull AnyEvent

bull AnyEventHTTP

bull AnyEventHTTPD

bull HTTPParserXS

bull DataUUID

bull EmailMIME

bull EmailSenderSimple

bull NetSSLeay

bull JSONXS

bull ProtocolWebSocket

bull TimePiece

3624 MySQL Setup

Create a mysql database ldquoopenvehiclesrdquo and use the ovms_serversql script to create the necessary ovms_ tablesCreate a mysql username and password with access to the database

Insert a record into the ovms_cars table to give you access to your own car

vehicleid DEMOowner 1carpass DEMOuserpass DEMOcryptscheme 0v_ptokenv_lastupdate 0000-00-00 000000

362 Chapter 36 OVMS Server

Open Vehicles

Obviously change the vehicleid carpass and userpass as necessary The only required fields are vehicleid and carpass

If you are upgrading from server v2 to v3 you can instead source the ovms_server_v2_to_v3sql code to migrate yourdatabase schema

3625 OVMS Server Configuration

Copy confovms_serverconfdefault to confovms_serverconf to provide a template for your configuration Thenmodify the configuration as appropriate

3626 OVMS Server Access to MySQL

In the configovms_serverconf file define the access to the mysql database

[db]path=DBImysqldatabase=openvehicleshost=127001user=ltmysqlusernamegtpass=ltmysqlpasswordgt

If the host is remote change the host= parameter to be the remote IP address Use 127001 for local

Test the connection with

$ mysql -h 127001 -u ltmysqlusernamegt -pEnter password ltmysqlpasswordgtWelcome to the MySQL monitor Commands end with or g

If you get ldquoERROR 1044 (42000) Access deniedrdquo fix it before proceeding The most likely cause is a mistake inyour mysql user grant rights

3627 Enable SSL (optional)

If you want to support SSL connections to your server (port 6869 for the REST API port 6870 for OVMS MP) youneed to supply a certificate You can create a self-signed certificate or get a certificate signed by some root CA foryour server

In both cases you need to merge the private key PEM and the chain PEM into the file ldquoovms_serverpemrdquo located inthe same directory as the ldquoovms_serverplrdquo Also take care to secure the file as it now contains your private key

To create a self-signed certificate do

$ openssl req -sha256 -newkey rsa4096 -nodes -keyout privkeypem -x509 -days 365 -rarr˓out fullchainpem$ cat privkeypem fullchainpem gtconfovms_serverpem$ chmod 0600 confovms_serverpem

Or if you want to reuse eg your Letrsquos Encrypt server certificate do this as root

cat etcletsencryptliveyourhostprivkeypem etcletsencryptliveyourhostrarr˓fullchainpem gtconfovms_serverpem chmod 0600 confvms_serverpem chown youruid confovms_serverpem

and add a cron job or certbot hook to check for renewals and redo these steps as necessary

362 Installation 363

Open Vehicles

3628 Configure the Plugins

The OVMS Server v3 is based on a pluggable architecture The plugins themselves are stored in pluginssystem andpluginslocal directories You must configure (in confovms_serverconf) the plugins that you require

We recommend the following

[plugins]load=ltltEOTVECEDbDBIAuthDrupalApiV2PushPushAPNSPushGCMPushMAILApiHttpApiHttpCoreApiHttpMqapiEOT

3629 Run The Server

You can run the server manually with

$ ovms_serverpl

If your linux host is running systemd you can also look at supportovms_serverservice and supportovmslogrotate asexamples for how you can run this as a background daemon

7 ENJOY

Any questionscomments please let us know

Mark Webb-Johnson March 2020

363 Plugins

3631 ApiHttp

This plugin provides an HTTP (and optional HTTPS) server and is used by subsequent API plugins to provide HTTPservices The HTTP server is on port tcp6868 If you provide a confovms_serverpem file it will also use that tolaunch a HTTPS server on port tcp6869

3632 ApiHttpCore

This plugin provides support for the HTTP API in OVMS Server v3 It supports the api HTTP endpoint

If you want to use this plugin you need to also include lsquoApiHttprsquo before loading this

364 Chapter 36 OVMS Server

Open Vehicles

3633 ApiHttpFile

This plugin provides support serving static files from the httpfiles directory It supports the file HTTP endpoint

If you want to use this plugin you need to also include lsquoApiHttprsquo before loading this

3634 ApiHttpMqapi

This plugin provides support for Mosquitto API functions for authentication and ACL access control It supports themqapi HTTP endpoint

If you want to use this plugin you need to also include lsquoApiHttprsquo before loading this

You will also need to configure your mosquittoconf to include

auth_opt_superusers ltyour-superuser-usernamegtauth_opt_acl_cacheseconds 300auth_opt_auth_cacheseconds 300auth_opt_backends httpauth_opt_http_ip 127001auth_opt_http_port 6868auth_opt_http_getuser_uri mqapiauthauth_opt_http_superuser_uri mqapisuperuserauth_opt_http_aclcheck_uri mqapiacl

3635 ApiV2

This plugin provides support for the v2 OVMS protocol including crypto protocols 0x30 and 0x31 It provides a rawv2 protocol server on tcp6867 If you provide a confovms_serverpem file it will also launch an SSL enabled v2protocol server on tcp6870

3636 AuthDrupal

This plugin provides support for authentication via the Drupal database It also provides a facility to periodicallysynchronise drupal users to OVMS owner table records

Note that only one Auth plugin should be enabled

3637 AuthNone

This is a stub authentication plugin It will always fail authentication and is only provided as an example (or for usein systems where user authentication is not required)

Note that only one Auth plugin should be enabled

3638 DbDBI

This is the core database plugin for perl DBI style SQL databases It is used for example to provide access to MySQLdatabases

363 Plugins 365

Open Vehicles

3639 Push

This provides the core support for Push Notifications The actual notifications themselves are issued by sub-pluginswhich register with this

36310 PushAPNS

This plugin supports the lsquoapnsrsquo notification type for push notifications to Apple devices (iPhones iPadsetc) It requires apple certificates in PEM format to be placed in confovms_apns_sandboxpem andconfovms_apns_productionpem

36311 PushGCM

This plugin supports the lsquogcmrsquo notification type for push notifications to Android devices It requires a google APIkey to be placed in the confovms_serverconf file under [gcm] section parameter lsquoapikeyrsquo You can obtain that keyby

Log in to your Google account Open httpsdevelopersgooglecommobileadd Select platform ldquoAndroidrdquo Enter an arbitrary project name eg ldquoMyOvmsServerrdquo Package name should be ldquocomopenvehiclesOVMSrdquo Activate ldquoCloud Messagingrdquo and generate the key Note the API key and project number (= GCM sender ID)

36312 PushMAIL

This plugin supports the lsquomailrsquo notification type for push notifications by eMail It simply requires a sendmail stylemailer installed on the server

You can configure confovms_serverconf [mail] section parameter lsquosenderrsquo as the sender address to be used (otherwisedefaulting to lsquonotificationsopenvehiclescomrsquo

36313 VECE

This plugin extends the notification system to translate error codes into textual error messgaes It uses files in the vecedirectory named ltvehicletypegtvece (for example trvece vavece etc)

The vece files themselves are ini style files

366 Chapter 36 OVMS Server

CHAPTER 37

OVMS Protocol v2

371 Welcome

The OVMS (Open Vehicle Monitoring System) team is a group of enthusiasts who are developing a means to remotelycommunicate with our cars and are having fun while doing it

The OVMS module is a low-cost hardware device that you install in your car simply by installing a SIM card con-necting the module to your carrsquos Diagnostic port connector and positioning a cellular antenna Once connected theOVMS module enables remote control and monitoring of your car

This developerrsquos guide documents version 2 of the OVMS protocol

372 Terms

Server The OVMS server

Car The OVMS car module

App An OVMS client application one of

bull Active client interactive user applications ie mobile App (Note the car module will raise the updatefrequency when active clients are connected)

bull Batch client a non-interactive application ie shell script

373 Startup

On startup there is no bannerwelcome message from the server The caller initiates the protocol by sending a welcomemessage to the server

1 For cars

MP-C ltprotection schemegt lttokengt ltdigestgt ltcar idgt

367

Open Vehicles

2 For interactive user apps

MP-A ltprotection schemegt lttokengt ltdigestgt ltcar idgt

3 For noninteractive batch apps

MP-B ltprotection schemegt lttokengt ltdigestgt ltcar idgt

4 For servers

MP-S ltprotection schemegt lttokengt ltdigestgt ltcar idgt

The server responds with a welcome message to the caller

MP-S ltprotection schemegt lttokengt ltdigestgt

374 Encryption Scheme 0x30

This scheme is based on using shared secrets hmac digest for authentication and encryption key negotiation withRC4 stream cipher and base64 encoding

Upon startup both the server and callers generate random tokens (encoded as textual characters) Each party thenhmac-md5s the token with the shared secret to create a digest base64 encoded

Note that the server will only issue itrsquos welcome message after receiving and validating the callerrsquos welcome message

Validation of the welcome message is performed by

1 Checking the received token to ensure that it is different from its own token and aborting the connection if thesame

2 Hmac-md5s the received token with the shared secret and comparing the result to the received digest

3 If the digest match then the partner had authenticated itself (proven it knows the shared secret or has listenedto a previous conversation)

4 If the digests donrsquot match then abort the connection as the partner doesnrsquot agree with the shared secret

Once the partner has been authenticated

1 Create a new hmac-md5 based on the client and server tokens concatenated with the shared secret

2 Use the new hmac digest as the key for symmetric rc4 encryption

3 Generate and discard 1024 bytes of cipher text

From this point on messages are rc4 encrypted and base64 encoded before transmission Lines are terminated withCR+LF

375 Encryption Scheme 0x31

This scheme is based on server authentication and is supported in OVMS server v3 and later Typically serversprovide two methods of authentication

bull Username + Password The usual username and associated password as used when registering on the server

bull Username + ApiToken An API token based authentication scheme where each user may maintain one or moreaccess tokens (which can be created or revoked at will)

The arguments to the MP- startup command are

bull ltprotection schemegt Must be set to lsquo1rsquo (0x31)

368 Chapter 37 OVMS Protocol v2

Open Vehicles

bull lttokengt Must be the username pre-registered with the server

bull ltdigestgt Must be the password or api token for that user

bull ltcar idgt Must be the vehicle ID to connect to or the special value lsquorsquo to request connection to the first vehicleon that userrsquos account

Once the partner has been authenticated a response lsquoMP-S 1 ltusergt ltvehicleidgt ltlist-of-all-other-vehiclesgtrsquo will besent from the server to indicate a successful authentication

From then onwards the messages are in plaintext with no further encryption or encoding Lines are terminated withCR+LF

Note that this scheme is intended to be used with external encryption schemes such as SSLTLS

376 Auto Provisioning

A caller can perform auto-provisioning at any time (authenticated or not) However only one auto-provision can beperformed for each connection

Auto-Provisioning relies on two secrets known both to the server and client The first is usually the VIN of the vehicleand the second is usually the ICCID of the SIM card in the vehicle module The reason these two are chosen is thatthey can be auto-determined by the vehicle module but also clearly seen by the user (for entry into the server)

The mechanism works by the client module first determining its VIN and ICCID secrets then connecting to the serverand sending a AP-C message to the server proving its VIN The server will then lookup the auto-provisioning recordand reply with that to the client (via a AP-S or AP-X message)

The auto-provisioning record itself is platform dependent but will typically be an ordered space separated list ofparameter values For OVMS hardware and OVMSX PIC firmware these are merely parameters 0 1 2 etc tobe stored in the car module

3761 Auto Provisioning Protection Scheme 0x30

1 For cars

AP-C ltprotection schemegt ltapkeygt

2 For servers

AP-S ltprotection schemegt ltserver tokengt ltserver digestgt ltprovisioninggt

AP-X

When the provisioning record is created at the server a random token is generated (encoded as textual characters) Theserver then hmac-md5s this token with the shared secret (usually the ICCID known by the server) to create a digestbase64 encoded Using this hmac digest the server generates and discards 1024 bytes of cipher text The serverthen rc4 encrypts and base64 encodes the provisioning information and stores its token digest and encoded provisionrecord ready for the client to request

The car knows its VIN and ICCID With this information it makes a connection to the OVMS service on the serverand provides the VIN as the ltapkeygt in a AP-C message to the server

The server will ensure that it only responds to one AP-C message for any one connection Once responded allsubsequent AP-C requests will always be replied with a AP-X message

Upon receiving the AP-C message the server looks up any provisioning records it has for the given ltapkeygt If it hasnone it replies with an AP-X message

376 Auto Provisioning 369

Open Vehicles

If the server does find a matching provisioning record it replies with an AP-S message sending the previously savedserver token digest and encoded provisioning record to the car

If the car receives an AP-X message it knows that auto-provisioning was not successful

If the car receives an AP-S message it can first validate the server authenticity By producing its own hmac-md5 ofthe server token and secret ICCID the car can validate the server-provided digest is as expected If this validation stepdoes not succeed the car should abort the auto-provisioning

If acceptable the car can decrypt the provisioning record by first generating and discarding 1024 bytes of cipher textthen decoding the provisioning record provided by the server

377 Backwards Compatibility

Typically comma-separated lists are used to transmit parameters Applications Servers and the Car firmware shouldin general ignore extra parameters not expected In this way the protocol messages can be extended by adding extraparameters without breaking old AppsCars that donrsquot expect the new parameters

Similarly unrecognized messages should due ignored Unrecognised commands in the ldquoCrdquo (command) messageshould be responded to with a generic ldquounrecognizedrdquo response (in the ldquocrdquo (command response) messages)

378 Messages

3781 Car lt-gt Server lt-gt App

After discarding CR+LF line termination and base64 decoding the following protocol messages are defined

ltmessagegt = ltmagicgt ltversiongt ltspacegt ltprotmsggt

ltmagicgt = MP-

ltversiongt = 1 byte version number - this protocol is 0x30

ltspacegt = lsquo lsquo (ascii 0x20)

ltprotmsggt = ltservertocargt | ltcartoservergt | ltservertoappgt | ltapptoservergt

ltservertocargt - ldquoSrdquo ltpayloadgt

ltcartoservergt = ldquoCrdquo ltpayloadgt

ltservertoappgt = ldquosrdquo ltpayloadgt

ltapptoservergt = ldquocrdquo ltpayloadgt

ltpayloadgt = ltcodegt ltdatagt

ltcodegt = 1 byte instruction code

ltdatagt = N bytes data (dependent on instruction code)

3782 Ping message 0x41 ldquoArdquo

This message may be sent by any party to test the link The expected response is a 0x61 ping acknowledgementThere is no expected payload to this message an any given can be discarded

370 Chapter 37 OVMS Protocol v2

Open Vehicles

3783 Ping Acknowledgement message 0x61 ldquoardquo

This message is sent in response to a 0x41 ping message There is no expected payload to this message an any givencan be discarded

3784 Command message 0x43 ldquoCrdquo

This message is sent ltapptoservergt then ltservertocargt and carries a command to be executed on the car The messagewould normally be paranoid-encrypted

ltdatagt is a comma-separated list of

bull command (a command code 065535)

bull parameters (dependent on the command code)

For further information on command codes and parameters see the command section below

3785 Command response 0x63 ldquocrdquo

This message is sent ltcartoservergt then ltservertoappgt and carries the response to a command executed on the carThe message would normally be paranoid-encrypted

ltdatagt is a comma-separated list of

bull command (a command code 065535)

bull result (0=ok 1=failed 2=unsupported 3=unimplemented)

bull parameters (dependent on the command code and result)

For result=0 the parameters depend on the command being responded to (see the command section below for furtherinformation)

For result=1 the parameter is a textual string describing the fault

For result=2 or 3 the parameter is not used

3786 Car Environment message 0x44 ldquoDrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the environment settings of the vehicle

ltdatagt is comma-separated list of

Door state 1

bull bit0 = Left Door (open=1closed=0)

bull bit1 = Right Door (open=1closed=0)

bull bit2 = Charge port (open=1closed=0)

bull bit3 = Pilot present (true=1false=0) (always 1 on my 25)

bull bit4 = Charging (true=1false=0)

bull bit5 = always 1

bull bit6 = Hand brake applied (true=1false=0)

bull bit7 = Car ON (ldquoignitionrdquo) (true=1false=0)

378 Messages 371

Open Vehicles

Door state 2

bull bit3 = Car Locked (locked=1unlocked=0)

bull bit4 = Valet Mode (active=1inactive=0)

bull bit6 = Bonnet (open=1closed=0)

bull bit7 = Trunk (open=1closed=0)

LockUnlock state

bull 4 = car is locked

bull 5 = car is unlocked

Temperature of the PEM (celcius)

Temperature of the Motor (celcius)

Temperature of the Battery (celcius)

Car trip meter (in 110th of a distance unit)

Car odometer (in 110th of a distance unit)

Car speed (in distance units per hour)

Car parking timer (0 for not parked or number of seconds car parked for)

Ambient Temperature (in Celcius)

Door state 3

bull bit0 = Car awake (turned on=1 off=0)

bull bit1 = Cooling pump (on=1off=0)

bull bit6 = 1=Logged into motor controller

bull bit7 = 1=Motor controller in configuration mode

Stale PEMMotorBattery temps indicator (-1=none 0=stale gt0 ok)

Stale ambient temp indicator (-1=none 0=stale gt0 ok)

Vehicle 12V line voltage

Door State 4

bull bit2 = alarm sounds (on=1off=0)

Reference voltage for 12v power

Door State 5

bull bit0 = Rear left door (open=1closed=0)

bull bit1 = Rear right door (open=1closed=0)

bull bit2 = Frunk (open=1closed=0)

bull bit4 = 12V battery charging

bull bit5 = Auxiliary 12V systems online

bull bit7 = HVAC running

372 Chapter 37 OVMS Protocol v2

Open Vehicles

Temperature of the Charger (celsius)

Vehicle 12V current (ie DC converter output)

Cabin temperature (celsius)

3787 Paranoid-mode encrypted message 0x45 ldquoErdquo

This message is sent for any of the four message ltprotmsggt types and represents an encrypted transmission that theserver should just relay (or is relaying) without being able to interpret it The encryption is based on a shared secretbetween the car and the apps to which the server is not privy

ltdatagt is

bull ltparanoidtokengt | ltparanoidcodegt

bull ltparanoidtokengt = ldquoTrdquo ltptokengt

bull ltparanoidcodegt = ldquoMrdquo ltcodegt ltdatagt

In the case of ltparanoidtokengt the ltptokengt is a random token that represent the encryption key It can only besent ltcartoservergt or ltservertoappgt Upon receiving this token the server discards all previously stored paranoidmessages sends it on to all connected apps and then stores the token Every time an app connects the server alsosends this token to the app

In the case of ltparanoidcodegt the ltcodegt is a sub-message code and can be any of the codes listed in this document(except for ldquoArdquo ldquoardquo and ldquoErdquo) The ltdatagt is the corresponding encrypted payload message The encryption isperformed on the ltdatagt by

bull Create a new hmac-md5 based on the ltptokengt with the shared secret

bull Use the new hmac digest as the key for symmetric rc4 encryption

bull Generate and discard 1024 bytes of cipher text

and the data is base64 encoded Upon receiving a paranoid message from the car the server forwards it on the allconnected apps and then stores the message Every time an app connects the server sends all such stored messagesUpon receiving a paranoid message from an app if the car is connected the server merely forwards it on to the carotherwise discarding it

3788 Car firmware message 0x46 ldquoFrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the firmware versions of the vehicle

ltdatagt is comma-separated list of

bull OVMS firmware version

bull VIN (vehicle identification number)

bull Current network signal quality (Wifi GSM in SQ units)

bull Write-enabled firmware (0=read-only 1=write-enabled)

bull Vehicle type code (eg TR = Tesla Roadster see command output vehicle list)

bull Current network name (Wifi SSID GSM provider)

bull Distance to next scheduled maintenanceservice [km]

bull Time to next scheduled maintenanceservice [seconds]

bull OVMS hardware version

378 Messages 373

Open Vehicles

3789 Server firmware message 0x66 ldquofrdquo

This message is sent ltservertocargt ldquoSrdquo or ltservertoappgt ldquosrdquo and transmits the firmware versions of the server

ltdatagt is comma-separated list of

bull Server firmware version

37810 Car group subscription message 0x47 ldquoGrdquo

This message is sent ltapptoservergt ldquoArdquo and requests subscription to the specified group

ltdatagt is comma-separated list of

bull Group name

37811 Car group update message 0x67 ldquogrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits a group location message for the vehicle

ltdatagt is comma-separated list of

bull Vehicle ID (only ltservertoappgt not sent ltcartoservergt)

bull Group name

bull Car SOC

bull Car Speed

bull Car direction

bull Car altitude

bull Car GPS lock (0=nogps 1=goodgps)

bull Stale GPS indicator (-1=none 0=stale gt0 ok)

bull Car latitude

bull Car longitude

37812 Historical Data update message 0x48 ldquoHrdquo

This message is sent ltcartoservergt ldquoC and transmits a historical data message for storage on the server

ltdatagt is comma-separated list of

bull type (unique storage class identification type)

bull recordnumber (integer record number)

bull lifetime (in seconds)

bull data (a blob of data to be dealt with as the application requires)

The lifetime is specified in seconds and indicates to the server the minimum time the vehicle expects the server toretain the historical data for Consideration should be made as to server storage and bandwidth requirements

The type is composed of ltvehicletypegt - ltclassgt - ltpropertygt

ltVehicletypegt is the usual vehicle type or lsquorsquo to indicate generic storage suitable for all vehicles

374 Chapter 37 OVMS Protocol v2

Open Vehicles

ltClassgt is one of

bull PWR (power)

bull ENG (engine)

bull TRX (transmission)

bull CHS (chassis)

bull BDY (body)

bull ELC (electrics)

bull SAF (safety)

bull SEC (security)

bull CMF (comfort)

bull ENT (entertainment)

bull COM (communications)

bull X (unclassified and experimental with replaced with 2 digits code)

ltPropertygt is a property code which the vehicle decides

The server will timestamp the incoming historical records and will set an expiry date of timestamp + ltlifetimegtseconds The server will endeavor to retain the records for that time period but may expend data earlier if necessary

37813 Historical Data update+ack message 0x68 ldquohrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltsevertocargt ldquocrdquo and transmitsacknowledges historical data message forstorage on the server

For ltcartoservergt the ltdatagt is comma-separated list of

bull ackcode (an acknowledgement code)

bull timediff (in seconds)

bull type (unique storage class identification type)

bull recordnumber (integer record number)

bull lifetime (in seconds)

bull data (a blob of data to be dealt with as the application requires)

The ackcode is a numeric acknowledgement code - if the server successfully receives the message it will reply withldquohrdquo and this ackcode to acknowledge reception

The timediff is the time difference in seconds to use when storing the record (eg -3600 would indicate the recorddata is from one hour ago)

The lifetime is specified in seconds and indicates to the server the minimum time the vehicle expects the server toretain the historical data for Consideration should be made as to server storage and bandwidth requirements

For ltservertocargt the ltdatagt is

bull ackcode (an acknowledgement code)

The ltcartoservergt message sends the data to the server The ltservertocargt message acknowledges the data

378 Messages 375

Open Vehicles

37814 Push notification message 0x50 ldquoPrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo When used by the car it requests the server to send atextual push notification alert message to all apps registered for this car The ltdatagt is 1 byte alert type followed by Nbytes of textual message The server will use this message to send the notification to any connected apps and can alsosend via external mobile frameworks for unconnected apps

37815 Push notification subscription 0x70 ldquoprdquo

This message is sent ltapptoservergt Ardquo It is used by app to register for push notifications and is normally at the startof a connection The ltdatagt is made up of

ltappidgtltpushtypegtltpushkeytypegtltvehicleidgtltnetpassgtltpushkeyvaluegt

The server will verify the credentials for each vehicle and store the required notification information

Note As of June 2020 only one vehicleid can be subscribed at a time If multiple vehicles are required then theyshould each be subscribed in individual messages

37816 Server -gt Server Record message 0x52 ldquoRrdquo

This message is sent ltservertoservergt ldquoSrdquo and transmits an update to synchronized database table records

Sub-type RV (Vehicle record) ltdatagt is comma-separated list of

bull Vehicleid

bull Owner

bull Carpass

bull v_server

bull deleted

bull changed

Sub-type RO (Owner record) ltdatagt is comma-separated list of

bull Ownerid

bull OwnerName

bull OwnerMail

bull PasswordHash

bull OwnerStatus

bull deleted

bull changed

37817 Server -gt Server Message Replication message 0x72 ldquorrdquo

This message is sent ltservertoservergt ldquoSrdquo and replicates a message for a particular car

ltdatagt is comma-separated list of

bull vehicleid

bull message code

376 Chapter 37 OVMS Protocol v2

Open Vehicles

bull message data

37818 Car state message 0x53 ldquoSrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the last known status of the vehicle

ltdatagt is comma-separated list of

bull SOC

bull Units (ldquoMrdquo for miles ldquoKrdquo for kilometers)

bull Line voltage

bull Charge current (amps)

bull Charge state (charging topoff done prepare heating stopped)

bull Charge mode (standard storage range performance)

bull Ideal range

bull Estimated range

bull Charge limit (amps)

bull Charge duration (minutes)

bull Charger B4 byte (tba)

bull Charge energy consumed (110 kWh)

bull Charge sub-state

bull Charge state (as a number)

bull Charge mode (as a number)

bull Charge Timer mode (0=onplugin 1=timer)

bull Charge Timer start time

bull Charge timer stale (-1=none 0=stale gt0 ok)

bull Vehicle CAC100 value (calculated amp hour capacity in Ah)

bull ACC Mins remaining until car will be full

bull ACC Mins remaining until car reaches charge limit

bull ACC Configured range limit

bull ACC Configured SOC limit

bull Cooldown Car is cooling down (0=no 1=yes)

bull Cooldown Lower limit for battery temperature

bull Cooldown Time limit (minutes) for cooldown

bull ACC charge time estimation for current charger capabilities (min)

bull Charge ETR for range limit (min)

bull Charge ETR for SOC limit (min)

bull Max ideal range

378 Messages 377

Open Vehicles

bull Chargeplug type ID according to OpenChargeMapsorg connectiontypes (see httpapiopenchargemapiov2referencedata)

bull Charge power output (kW)

bull Battery voltage (V)

bull Battery SOH (state of health) ()

bull Charge power input (kW)

bull Charger efficiency ()

bull Battery current (A)

bull Battery ideal range gainloss speed (mphkph gain=positive)

37819 Car update time message 0x53 ldquoTrdquo

This message is sent ltservertoappgt ldquosrdquo and transmits the last known update time of the vehicle

ltdatagt is the number of seconds since the car last sent an update message

37820 Car location message 0x4C ldquoLrdquo

This message is sent ltcartoservergt ldquoCrdquo and transmits the last known location of the vehicle

ltdatagt is comma-separated list of

bull Latitude

bull Longitude

bull Car direction

bull Car altitude

bull Car GPS lock (0=nogps 1=goodgps)

bull Stale GPS indicator (-1=none 0=stale gt0 ok)

bull Car speed (in distance units per hour)

bull Car trip meter (in 110th of a distance unit)

bull Drive mode (car specific encoding of current drive mode)

bull Battery power level (in kW negative = charging)

bull Energy used (in Wh)

bull Energy recovered (in Wh)

bull Inverter motor power (kW) (positive = output)

bull Inverter efficiency ()

bull GPS mode indicator (see below)

bull GPS satellite count

bull GPS HDOP (see below)

bull GPS speed (in distance units per hour)

378 Chapter 37 OVMS Protocol v2

Open Vehicles

GPS mode indicator this shows the NMEA receiver mode If using the SIM5360 modem for GPS this is a twocharacter string The first character represents the GPS receiver mode the second the GLONASS receiver mode Eachmode character may be one of

bull N = No fix Satellite system not used in position fix or fix not valid

bull A = Autonomous Satellite system used in non-differential mode in position fix

bull D = Differential (including all OmniSTAR services) Satellite system used in differential mode in position fix

bull P = Precise Satellite system used in precision mode Precision mode is defined as no deliberate degradation(such as Selective Availability) and higher resolution code (P-code) is used to compute position fix

bull R = Real Time Kinematic Satellite system used in RTK mode with fixed integers

bull F = Float RTK Satellite system used in real time kinematic mode with floating integers

bull E = Estimated (dead reckoning) Mode

bull M = Manual Input Mode

bull S = Simulator Mode

GPS HDOP HDOP = horizontal dilution of precision This is a measure for the currently achievable precision ofthe horizontal coordinates (latitude amp longitude) which depends on the momentary relative satellite positions andvisibility to the device

The lower the value the higher the precision Values up to 2 mean high precision up to 5 is good If the value ishigher than 20 coordinates may be off by 300 meters from the actual position

See httpsenwikipediaorgwikiDilution_of_precision_(navigation) for further details

37821 Car Capabilities message 0x56 ldquoVrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the vehicle capabilities It was introducedwith v2 of the protocol

ltdata is comma-separated list of vehicle capabilities of the form

bull Cltcmdgt indicates vehicle support command ltcmdgt

bull CltcmdLgt-ltcmdHgt indicates vehicle will support all commands in the specified range

37822 Car TPMS message 0x57 ldquoWrdquo (oldobsolete)

Note Message ldquoWrdquo has been replaced by ldquoYrdquo (see below) for OVMS V3 The V3 module will still send ldquoWrdquomessages along with ldquoYrdquo for old clients for some time Clients shall adapt to using ldquoYrdquo if available ASAP ldquoWrdquomessages will be removed from V3 in the near future

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the last known TPMS values of thevehicle

ltdatagt is comma-separated list of

bull front-right wheel pressure (psi)

bull front-right wheel temperature (celcius)

bull rear-right wheel pressure (psi)

bull rear-right wheel temperature (celcius)

378 Messages 379

Open Vehicles

bull front-left wheel pressure (psi)

bull front-left wheel temperature (celcius)

bull rear-left wheel pressure (psi)

bull rear-left wheel temperature (celcius)

bull Stale TPMS indicator (-1=none 0=stale gt0 ok)

37823 Car TPMS message 0x59 ldquoYrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the last known TPMS values of thevehicle

ltdatagt is comma-separated list of

bull number of defined wheel names

bull list of defined wheel names

bull number of defined pressures

bull list of defined pressures (kPa)

bull pressures validity indicator (-1=undefined 0=stale 1=valid)

bull number of defined temperatures

bull list of defined temperatures (Celcius)

bull temperatures validity indicator (-1=undefined 0=stale 1=valid)

bull number of defined health states

bull list of defined health states (Percent)

bull health states validity indicator (-1=undefined 0=stale 1=valid)

bull number of defined alert levels

bull list of defined alert levels (0=none 1=warning 2=alert)

bull alert levels validity indicator (-1=undefined 0=stale 1=valid)

Note Pressures are transported in kPa now instead of the former PSI To convert to PSI multiply by014503773773020923

37824 Peer connection message 0x5A ldquoZrdquo

This message is sent ltservertocargt or ltservertoappgt to indicate the connection status of the peer (car for ltserver-toappgt interactive apps for ltservertocargt) It indicates how many peers are currently connected

It is suggested that the car should use this to immediately report on and to increase the report frequency of status - inthe case that one or more interactive Apps are connected and watching the car

Batch client connections do not trigger any peer count change for the car but they still receive the car peer status fromthe server

ltdatagt is

bull Number of peers connected expressed as a decimal string

380 Chapter 37 OVMS Protocol v2

Open Vehicles

37825 Car export power message 0x47 ldquoGrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits ldquovgrdquo metrics from the vehicle

ltdatagt is comma-separated list of

bull vggenerating (1 = currently delivering power)

bull vgpilot (1 = pilot present)

bull vgvoltage (in V)

bull vgcurrent (in A)

bull vgpower (in kW)

bull vgefficiency (in )

bull vgtype (eg ldquochademordquo)

bull vgstate (eg ldquoexportingrdquo)

bull vgsubstate (eg ldquoonrequestrdquo)

bull vgmode (eg ldquostandardrdquo)

bull vgclimit (in A)

bull vglimitrange (in km)

bull vglimitsoc (in )

bull vgkwh (in kWh)

bull vgkwhgrid (in kWh)

bull vgkwhgridtotal (in kWh)

bull vgtime (in s)

bull vgtimermode (1 = generator timer enabled)

bull vgtimerstart

bull vgdurationempty (in min)

bull vgdurationrange (in min)

bull vgdurationsoc (in min)

bull vgtemp (in deg C)

Refer httpsdocsopenvehiclescomenlatestuserguidemetricshtml

379 Commands

3791 Commands and Expected Responses

For message types ldquoCrdquo and ldquocrdquo the following commands and responses are expected to be supported

379 Commands 381

Open Vehicles

3792 1 - Request feature list

Command parameters are unused and ignored by the car

Response is a sequence of individual messages with each message containing the following parameters

bull feature number

bull maximum number of features

bull feature value

Registered features are

bull 0 Digital SPEEDO (experimental)

bull 8 Location STREAM mode (consumes more bandwidth)

bull 9 Minimum SOC

bull 15 CAN bus can write-enabled

Note that features 0 through 7 are lsquovolatilersquo and will be lost (reset to zero value) if the power is lost to the car moduleor module is reprogrammed These features are considered extremely experimental and potentially dangerous

Features 8 through 15 are lsquopermanentrsquo and will be stored as parameters 23 through 31 These features are consideredmore stable but optional

3793 2 - Set feature

Command parameters are

bull feature number to set

bull value to set

Response parameters are unused and will merely indicate the success or not of the result

3794 3 - Request parameter list

Command parameters are unused and ignored by the car

Response is a sequence of individual messages with each message containing the following parameters

bull parameter number

bull maximum number of parameters

bull parameter value

Registered parameters are

bull 0 Registered telephone number

bull 1 Registration Password

bull 2 Miles Kilometer flag

bull 3 Notification method list

bull 4 Server IP

bull 5 GPRS APN

bull 6 GPRS User

382 Chapter 37 OVMS Protocol v2

Open Vehicles

bull 7 GPRS Password

bull 8 Vehicle ID

bull 9 Network Password

bull 10 Paranoid Password

Note that some parameters (24 through 31) are tied directly to the features system (for permanent features) and arethus not directly maintained by the parameter system or shown by this command

3795 4 - Set parameter

Command parameters are

bull parameter number to set

bull value to set

Response parameters are unused and will merely indicate the success or not of the result

3796 5 - Reboot

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result Shortly after sending theresponse the module will reboot

3797 6 - Charge Alert

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result Shortly after sending theresponse the module will issue a charge alert

3798 7 - Execute SMS command

Command parameter is

bull SMS command with parameters

Response is the output of the SMS command that would otherwise have been sent as the reply SMS with LF charactersconverted to CR

The caller id is set to the registered phone number Return code 1 is used for all errors ie authorization failurecommand failure and unknownunhandled commands

Note SMS commands with multiple replies are not yet supported only the last reply will be returned

3799 10 - Set Charge Mode

Command parameters are

bull mode (0=standard 1=storage3=range4=performance)

Response parameters are unused and will merely indicate the success or not of the result

379 Commands 383

Open Vehicles

37910 11 - Start Charge

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

37911 12 - Stop Charge

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

37912 15 - Set Charge Current

Command parameters are

bull current (specified in Amps)

Response parameters are unused and will merely indicate the success or not of the result

37913 16 - Set Charge Mode and Current

Command parameters are

bull mode (0=standard 1=storage3=range4=performance)

bull current (specified in Amps)

Response parameters are unused and will merely indicate the success or not of the result

37914 17 - Set Charge Timer Mode and Start Time

Command parameters are

bull timermode (0=plugin 1=timer)

bull start time (0x059F for midnight GMT 0x003B for 1am GMT etc)

Response parameters are unused and will merely indicate the success or not of the result

37915 18 - Wakeup car

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

37916 19 - Wakeup temperature subsystem

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

384 Chapter 37 OVMS Protocol v2

Open Vehicles

37917 20 - Lock Car

Command parameters are

bull pin (the car pin to use for locking)

Response parameters are unused and will merely indicate the success or not of the result

NB unlocklock may not affect the immobilizer+alarm (when fitted)

37918 21 - Activate Valet Mode

Command parameters are

bull pin (the car pin to activate valet mode)

Response parameters are unused and will merely indicate the success or not of the result

37919 22 - Unlock Car

Command parameters are

bull pin (the car pin to use for unlocking)

Response parameters are unused and will merely indicate the success or not of the result

NB unlocklock does not affect the immobilizer+alarm (when fitted)

37920 23 - Deactivate Value Mode

Command parameters are

bull pin (the car pin to use for deactivating value mode)

Response parameters are unused and will merely indicate the success or not of the result

37921 24 - Home Link

Command parameters are

bull button (home link button 0 1 or 2)

Response parameters are unused and will merely indicate the success or not of the result

37922 25 - Cooldown

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

379 Commands 385

Open Vehicles

37923 30 - Request GPRS utilization data

Command parameters are unused and ignored by the car

Response is a sequence of individual messages with each message containing the following parameters

bull record number

bull maximum number of records

bull date

bull car received bytes

bull car transmitted bytes

bull apps received bytes

bull apps transmitted bytes

Note that this request is handled by the server not the car so must not be sent in paranoid mode The response (fromthe server) will also not be sent in paranoid mode

NB Dates (and GPRS utilization data) are in UTC

37924 31 - Request historical data summary

Command parameters are

bull since (optional timestamp condition)

Response is a sequence of individual messages with each message containing the following parameters

bull type number

bull maximum number of types

bull type value

bull number of unique records (per type)

bull total number of records (per type)

bull storage usage (in bytes per type)

bull oldest data timestamp (per type)

bull newest data timestamp (per type)

NB Timestamps are in UTC

37925 32 - Request historical data records

Command parameters are

bull type (the record type to retrieve)

bull since (optional timestamp condition)

Response is a sequence of individual messages with each message containing the following parameters

bull response record number

bull maximum number of response records

bull data record type

386 Chapter 37 OVMS Protocol v2

Open Vehicles

bull data record timestamp

bull data record number

bull data record value

37926 40 - Send SMS

Command parameters are

bull number (telephone number to send sms to)

bull message (sms message to be sent)

Response parameters are unused and will merely indicate the success or not of the submission (not delivery) of theSMS

37927 41 - Send MMIUSSD Codes

Command parameters are

bull USSD_CODE (the ussd code to send)

Response parameters are unused and will merely indicate the success or not of the submission (not delivery) of therequest

37928 49 - Send raw AT Command

Command parameters are

bull at (the AT command to send - including the AT prefix)

Response parameters are unused and will merely indicate the success or not of the submission (not delivery) of therequest

379 Commands 387

Open Vehicles

388 Chapter 37 OVMS Protocol v2

CHAPTER 38

OVMS HTTP API

381 Welcome

For some time now Irsquove wanted to offer an HTTP API for OVMS The existing carlt-gtserver and serverlt-gtapp protocolis cool but requires going through some hoops (perl whatever) to handle the encryption and protocol level stuff AnHTTP API would make this much easier to externally script and would be great for pulling down logs and other suchthings

This document describes this HTTP API

Mark February 2013

382 Format

The API is a RESTfull service running at

bull httpapiopenvehiclescom6868api

bull httpsapiopenvehiclescom6869api

Other OVMS servers should provide this API on the same ports but for the rest of this manual we will simply refer toapiopenvehiclescom as the server being used

The return data is a json formatted array of hashes Each record is one for one vehicle and shows you the vehicle idas well as counts for the number of apps currently connected to that vehicle and whether the vehicle is connected tothe net (server) or not

From the server point of view we can treat an api session just like an app session From the vehicle point of view therewill be no difference - once an API connects to a vehicle the server will send a ldquoZ 1rdquo message to tell the module it hasa connection If the session times out or is logged out the server will inform the modules in the vehicles

389

Open Vehicles

3821 Example

For example once authenticated you can request a list of vehicles on your account

$ curl -v -X GET -b cookiejar httpapiopenvehiclescom6868apivehicles

About to connect() to apiopenvehiclescom port 6868 (0)

Trying apiopenvehiclescom

connected

Connected to tmcopenvehiclescom (641117040) port 6868 (0)gt GET apivehicles HTTP11User-Agent curl7240 (x86_64-apple-darwin120) libcurl7240OpenSSL098r zlib125Host apiopenvehiclescom6868Accept Cookie ovmsapisession=9ed66d0e-5768-414e-b06d-476f13be40ff

HTTP 10 assume close after bodylt HTTP10 200 Logout oklt Connection closelt Content-Length 280lt Cache-Control max-age=0lt Content-Type applicationjsonlt Date Fri 22 Feb 2013 124441 GMTlt Expires Fri 22 Feb 2013 124441 GMTlt[

idDEMOv_apps_connected0v_net_connected1idMARKSCARv_apps_connected1v_net_connected1idQCCARv_apps_connected0v_net_connected0idRALLYCARv_apps_connected0v_net_connected0idTESTCARv_apps_connected0v_net_connected0

]

(note that the above is re-formatted slightly to make it clearer to read)

383 Authentication

3831 Alternatives

Each API call must be authenticated and there are currently three options for this

Username+Passsword authentication Specify parameters lsquousernamersquo and lsquopasswordrsquo in the URL and they will bevalidated against registered users on the server Username+ApiToken authentication Specify parameter lsquousernamersquoas the registered user and lsquopasswordrsquo as a registered API token in the URL and they will be validated againstregistered API tokens for that user on the server Cookie authentication A cookie may be obtained (by either of theabove two authentication methods) and then used for subsequent API calls

3832 Cookie Based Authentication

Cookie based authentication avoids the requirement to authenticate each time It is also a requirement for sessionbased API calls This is done with a http ldquoGET apicookierdquo passing parameters lsquousernamersquo and lsquopasswordrsquo as yourwwwopenvehiclescom username and password (or API token) respectively

390 Chapter 38 OVMS HTTP API

Open Vehicles

$ curl -v -X GET -c cookiejarhttpapiopenvehiclescom6868apicookieusername=USERNAMEamppassword=PASSWORD

About to connect() to tmcopenvehiclescom port 6868 (0)

Trying 641117040

connected

Connected to tmcopenvehiclescom (641117040) port 6868 (0)GET apicookieusername=USERNAMEamppassword=PASSWORD HTTP11User-Agent curl7240 (x86_64-apple-darwin120) libcurl7240OpenSSL098r zlib125Host tmcopenvehiclescom6868Accept

HTTP 10 assume close after bodylt HTTP10 200 Authentication oklt Connection closelt Content-Length 9lt Cache-Control max-age=0lt Content-Type textplain

Added cookie ovmsapisession=9ed66d0e-5768-414e-b06d-476f13be40ff for domain tmcrarr˓openvehiclescom path api expire 0lt Set-Cookie ovmsapisession=9ed66d0e-5768-414e-b06d-476f13be40fflt Date Fri 22 Feb 2013 124356 GMTlt Expires Fri 22 Feb 2013 124356 GMTltLogin ok

Once logged in all subsequent requests should pass the cookie (ovmsapisession) The session will expire after 3minutes of no use or you can specifically terminate logout the session by calling ldquoDELETE apicookierdquo

The cookie can be destroyed (and session logged out) using the DELETE method (passing the original cookie)

$ curl -v -X DELETE -b cookiejarhttpapiopenvehiclescom6868apicookie

3833 API Token Maintenance

An API token can be created with a POST to the apitoken API endpoint

$ curl -v -X POST -F application=ltappgt -F purpose=ltpurposegt -F permit=ltpermitgthttpapiopenvehiclescom6868apitoken

Note that the lsquopurposersquo and lsquoapplicationrsquo fields are comments attached to the token and are intended to identify theapplication that createduses the token and the purpose that token is used for

The lsquopermitrsquo field defines the list of rights granted to the user of this token

Any of the three authentication mechanisms can be used for this so long as the permissions include either lsquoto-kenadminrsquo or lsquoadminrsquo rights

An API token can be deleted with a DELETE to the apitokenltTOKENgt API endpoint

$ curl -v -X DELETE httpapiopenvehiclescom6868apitokenltTOKENgt

383 Authentication 391

Open Vehicles

384 Requests

3841 GET apicookie

Login and return a session cookie

3842 DELETE apicookie

Delete the session cookie and logout

All vehicles still connected (via apivehicle) will be disconnected automatically

3843 GET apitoken

Return a list of registered API tokens

3844 POST apitoken

Create an API token

3845 DELETE apitokenltTOKENgt

Delete the specified API token

3846 GET apivehicles

Return a list of registered vehicles

bull id Vehicle ID

bull v_net_connected Number of vehicles currently connected

bull v_apps_connected Number of apps currently connected

bull v_btcs_connected Number of batch clients currently connected

3847 GET apivehicleltVEHICLEIDgt

Connect to the vehicle and return vehicle information

bull m_msgage_s age (seconds) of last status (S) message received if available

bull m_msgtime_s time stamp (UTC) of last status (S) message received if available

bull v_apps_connected number of apps currently connected (including the API connection)

bull v_btcs_connected number of batch clients currently connected

bull v_first_peer 01 1 = the API connection is the first peer connecting to the car

bull v_net_connected 01 1 = the car is currently connected to the server

392 Chapter 38 OVMS HTTP API

Open Vehicles

While no application is connected to the vehicle the module will send status updates using the configured ldquoidlerdquointerval to reduce data volume and energy consumption

Connecting to the car tells the module (if connected) to send status updates in the normally shorter ldquoconnectedrdquointervals (as configured) If yoursquore the first peer and the car is online the module will send a full status update withinthe next second after receiving the new peer count Depending on the connection speed you should give the car modulesome seconds to transmit the first update before proceeding to other status queries

You can also check m_msgage_s and m_msgtime_s to see if the status record is up to date (yet) These fields arealso included in the other status responses eg apichargeltVEHICLEIDgt

3848 DELETE apivehicleltVEHICLEIDgt

Disconnect from the vehicle

This is optional on session logout or expiry all vehicles will be disconnected automatically

3849 GET apiprotocolltVEHICLEIDgt

Return raw protocol records (no vehicle connection)

bull m_msgtime Datetime message received

bull m_paranoid Paranoid mode flag

bull m_ptoken Paranoid mode token

bull m_code Message code

bull m_msg Message body

38410 GET apistatusltVEHICLEIDgt

Return vehicle status

bull soc

bull units

bull idealrange

bull idealrange_max

bull estimatedrange

bull mode

bull chargestate

bull cac100

bull soh

bull cooldown_active

bull fl_dooropen

bull fr_dooropen

bull cp_dooropen

bull pilotpresent

384 Requests 393

Open Vehicles

bull charging

bull caron

bull carlocked

bull valetmode

bull bt_open

bull tr_open

bull temperature_pem

bull temperature_motor

bull temperature_battery

bull temperature_charger

bull temperature_cabin

bull tripmeter

bull odometer

bull speed

bull parkingtimer

bull temperature_ambient

bull carawake

bull staletemps

bull staleambient

bull charging_12v

bull vehicle12v

bull vehicle12v_ref

bull vehicle12v_current

bull alarmsounding

bull m_msgage_s age (seconds) of last status (S) message received if available

bull m_msgtime_s time stamp (UTC) of last status (S) message received if available

bull m_msgage_d age (seconds) of last doorsenv (D) message received if available

bull m_msgtime_d time stamp (UTC) of last doorsenv (D) message received if available

38411 GET apitpmsltVEHICLEIDgt

Return tpms status

bull fr_pressure

bull fr_temperature

bull rr_pressure

bull rr_temperature

bull fl_pressure

394 Chapter 38 OVMS HTTP API

Open Vehicles

bull fl_temperature

bull rl_pressure

bull rl_temperature

bull staletpms

bull m_msgage_w age (seconds) of last TPMS (W) message received if available

bull m_msgtime_w time stamp (UTC) of last TPMS (W) message received if available

38412 GET apilocationltVEHICLEIDgt

Return vehicle location

bull latitude

bull longitude

bull direction

bull altitude

bull gpslock

bull stalegps

bull speed

bull tripmeter

bull drivemode

bull power

bull energyused

bull energyrecd

bull m_msgage_l age (seconds) of last location (L) message received if available

bull m_msgtime_l time stamp (UTC) of last location (L) message received if available

38413 GET apichargeltVEHICLEIDgt

Return vehicle charge status

bull linevoltage

bull battvoltage

bull chargecurrent

bull chargepower

bull chargetype

bull chargestate

bull soc

bull units

bull idealrange

bull estimatedrange

384 Requests 395

Open Vehicles

bull mode

bull chargelimit

bull chargeduration

bull chargeb4

bull chargekwh

bull chargesubstate

bull chargetimermode

bull chargestarttime

bull chargetimerstale

bull cac100

bull soh

bull charge_etr_full

bull charge_etr_limit

bull charge_limit_range

bull charge_limit_soc

bull cooldown_active

bull cooldown_tbattery

bull cooldown_timelimit

bull charge_estimate

bull charge_etr_range

bull charge_etr_soc

bull idealrange_max

bull cp_dooropen

bull pilotpresent

bull charging

bull caron

bull temperature_pem

bull temperature_motor

bull temperature_battery

bull temperature_charger

bull temperature_ambient

bull temperature_cabin

bull carawake

bull staletemps

bull staleambient

bull charging_12v

396 Chapter 38 OVMS HTTP API

Open Vehicles

bull vehicle12v

bull vehicle12v_ref

bull vehicle12v_current

bull m_msgage_s age (seconds) of last status (S) message received if available

bull m_msgtime_s time stamp (UTC) of last status (S) message received if available

bull m_msgage_d age (seconds) of last doorsenv (D) message received if available

bull m_msgtime_d time stamp (UTC) of last doorsenv (D) message received if available

38414 GET apihistoricalltVEHICLEIDgt

Request historical data summary (as array of)

bull h_recordtype

bull distinctrecs

bull totalrecs

bull totalsize

bull first

bull last

38415 GET apihistoricalltVEHICLEIDgtltDATATYPEgt

Request historical data records

bull h_timestamp

bull h_recordnumber

bull h_data

38416 Not Yet Implemented

bull PUT apichargeltVEHICLEIDgt Set vehicle charge status

bull DELETE apichargeltVEHICLEIDgt Abort a vehicle charge

bull GET apilockltVEHICLEIDgt Return vehicle lock status

bull PUT apilockltVEHICLEIDgt Lock a vehicle

bull DELETE apilockltVEHICLEIDgt Unlock a vehicle

bull GET apivaletltVEHICLEIDgt Return valet status

bull PUT apivaletltVEHICLEIDgt Enable valet mode

bull DELETE apivaletltVEHICLEIDgt Disable valet mode

bull GET apifeaturesltVEHICLEIDgt Return vehicle features

bull PUT apifeatureltVEHICLEIDgt Set a vehicle feature

bull GET apiparametersltVEHICLEIDgt Return vehicle parameters

384 Requests 397

Open Vehicles

bull PUT apiparameterltVEHICLEIDgt Set a vehicle parameter

bull PUT apiresetltVEHICLEIDgt Reset the module in a particular vehicle

bull PUT apihomelinkltVEHICLEIDgt Activate home link

398 Chapter 38 OVMS HTTP API

Index

AApp 367

CCar 367

SServer 367

399

  • Open-Vehicle-Monitoring-System-3 (OVMS3)
  • User Guide
  • Plugins
  • BMW i3 i3s
  • DBC Based Vehicles
  • DEMO Vehicle
  • Fiat 500e
  • Hyundai Ioniq vFL
  • Jaguar IPace
  • Kia e-Niro
  • Kia Soul EV
  • Maxus eDeliver3
  • Mercedes-Benz B250E W242
  • MG EV
  • Mitsubishi Trio
  • Nissan Leafe-NV200
  • OBDII Vehicles
  • Renault Twizy
  • Renault Zoe
  • Smart ED Gen3
  • Smart EDEQ Gen4 (453)
  • Tesla Model 3
  • Tesla Model S
  • Tesla Roadster
  • Toyota RAV4 EV
  • Tracking Vehicles
  • VW e-Up
  • VW e-Up via OBD2
  • VW e-Up via Comfort CAN (T26A)
  • Command Line Interpreter
  • CAN Bus Data Logging
  • CRTD CAN Log Format
  • Web Framework amp Plugins
  • Scripting
  • CANopen
  • OVMS Server
  • OVMS Protocol v2
  • OVMS HTTP API
  • Index
Page 2: Open Vehicles - Home | Read the Docs

User Guides

1 Open-Vehicle-Monitoring-System-3 (OVMS3) 3

2 User Guide 11

3 Plugins 89

4 BMW i3 i3s 113

5 DBC Based Vehicles 117

6 DEMO Vehicle 121

7 Fiat 500e 123

8 Hyundai Ioniq vFL 125

9 Jaguar IPace 127

10 Kia e-Niro 129

11 Kia Soul EV 131

12 Maxus eDeliver3 137

13 Mercedes-Benz B250E W242 139

14 MG EV 141

15 Mitsubishi Trio 145

16 Nissan Leafe-NV200 151

17 OBDII Vehicles 157

18 Renault Twizy 159

19 Renault Zoe 183

20 Smart ED Gen3 185

i

21 Smart EDEQ Gen4 (453) 189

22 Tesla Model 3 191

23 Tesla Model S 193

24 Tesla Roadster 195

25 Toyota RAV4 EV 201

26 Tracking Vehicles 203

27 VW e-Up 205

28 VW e-Up via OBD2 227

29 VW e-Up via Comfort CAN (T26A) 237

30 Command Line Interpreter 245

31 CAN Bus Data Logging 251

32 CRTD CAN Log Format 255

33 Web Framework amp Plugins 261

34 Scripting 341

35 CANopen 351

36 OVMS Server 361

37 OVMS Protocol v2 367

38 OVMS HTTP API 389

Index 399

ii

Open Vehicles

Note This online manual includes documentation for the stable release of the OVMS firmware (available as OTAversion tag ldquomainrdquo) and the latest nightly firmware build (available as OTA version ldquoedgerdquo) Select the manual versionmatching your setup using the menu on the bottom left

User Guides 1

Open Vehicles

2 User Guides

CHAPTER 1

Open-Vehicle-Monitoring-System-3 (OVMS3)

11 Introduction

The OVMS is an all open source vehicle remote monitoring diagnosis and control system

3

Open Vehicles

The system provides live monitoring of vehicle metrics like state of charge temperatures tyre pressures and diag-nostic fault conditions It will alert you about critical conditions and events like a charge abort battery cell failureor potential theft Depending on the vehicle integration it allows you to take control over the charge process cli-mate control tuning parameters of the engine and more OVMS developers are enthusiasts trying hard to provide asdetailed information about the internals of a vehicle as possible

While most new vehicles now include some kind of remote control system very few allow deep insight some willnot work in all regions and none will give you control over your personal data The OVMS fills that gap and alsoenables you to add all these features to existing vehicles of any kind

The OVMS can also be used for fleet monitoring It allows a fleet manager to not only track the vehicle locations butalso to monitor the vehiclersquos vitals remotely check for fault conditions offer services like automatic preheating forusers and take active control in case of abusive use As the system is open source and fully scriptable it can easilyintegrate custom access and control systems

For developers and technicians the OVMS includes a range of CAN tools including multiple logging formats aconfigurable OBD2 translator a DBC decoder a reverse engineering toolkit and a CANopen client The moduleprovides SSH access and WebSocket streaming and can stream and inject CAN frames via TCP Both the module andthe web frontend can be customized by plugins The module has three builtin CAN buses and can be extended by afourth one

The OVMS base component is a small and inexpensive hardware module that connects to the vehicle OBD2 port Thestandard kit includes a 3G modem to provide GSM connectivity and GPS and comes with a ready-to-use HologramioSIM card The US kit has been FCC certified the EU kit CE certified

The module provides a built-in Web App user interface and remote control via native cellphone Apps available forAndroid and iOS It integrates into homeprocess automation systems via MQTT and provides data logging to SDcard and to a server

12 Vehicle Support

bull Native Integration

ndash Chevrolet Volt Opel Ampera

ndash Chevrolet Bolt EV Opel Ampera-e

ndash BMW i3 i3s

ndash Fiat 500e

ndash Hyundai Ioniq vFL

ndash Jaguar Ipace

ndash Kia e-Niro Hyundai Kona

ndash Kia Soul EV

ndash Maxus eDeliver 3

ndash Mercedes-Benz B250E

ndash MG ZS EV

ndash Mitsubishi Trio (i-MiEV et al)

ndash Nissan Leaf e-NV200

ndash Renault Twizy

ndash Renault Zoe Kangoo

4 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

Open Vehicles

ndash Smart ED Gen3

ndash Smart EDEQ Gen4 (453)

ndash Tesla Model S

ndash Tesla Roadster

ndash Think City

ndash Toyota RAV4 EV

ndash VW e-Up

bull General Support

ndash DBC File Based

ndash GPS Tracking

ndash OBD-II Standard

ndash Zeva BMS

13 Links

bull User Resources

ndash User and Developer Guides (hint version selection in left menu at the bottom)

Stable release (OTA version ldquomainrdquo)

Latest nightly build (OTA version ldquoedgerdquo)

ndash User Support Forum

ndash Android App

ndash iOS App

bull Distributors

ndash FastTech (global)

ndash Medlock amp Sons (North America)

ndash OpenEnergyMonitor (UKEurope)

bull Servers

ndash Asia-Pacific

ndash GermanyEurope

bull Developers

ndash Developer Guide

ndash Developer Mailing List amp Archive

ndash Server Source

ndash Android App Source

ndash iOS App Source

13 Links 5

Open Vehicles

14 Hardware

bull Module Schematics and PCB Layouts

bull Base Module (v30-33)

ndash Black injection-moulded plastic enclosure approximately 99x73x29 mm excl plugs

ndash ESP32 WROVER processor (16MB flash 4MB SPI RAM 520KB SRAM dual core 160240MHz XtensaLX6 processor)

ndash WIFI 80211 bgn

ndash Bluetooth v42 BREDR and BLE

ndash 3x CAN buses

ndash 1x Micro USB connector (for flash download and serial console)

ndash 1x Micro SD card slot

ndash 1x Internal expansion slot

ndash 8x EGPIO 2x GPIO

ndash 1x GSM antenna connector

ndash 1x GPS antenna connector

ndash 1x DB9 vehicle connector

ndash 1x DB26 expansion connector

bull Modem Module v30-32

ndash US edition is SIM5360A (Dual-Band UMTSHSPA+ 8501900MHz Quad-Band GSMGPRSEDGE85090018001900MHz)

ndash EU edition is SIM5360J(E) (Dual-Band UMTSHSPA+ 9002100MHz Quad-Band GSMGPRSEDGE85090018001900MHz)

ndash 3G (EV-DOHSPA+) dual band modem

ndash Includes 2G (GSMGPRS) and 25G (EDGE) quad band

ndash GPSGNSS

6 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

Open Vehicles

ndash Nano (4FF) SIM slot

ndash HOLOGRAMIO nano sim included (can be exchanged if necessary)

bull Modem Module v33

ndash World edition SIM7600G (Multi-Band LTE-FDDLTE-TDDHSPA+ and GSMGPRSEDGE)

ndash 4G (LTE-FDDLTE-TDD) multi band modem

ndash Includes 3G (EV-DOHSPA+) 2G (GSMGPRS) and 25G (EDGE) quad band

ndash GPSGNSS

ndash Nano (4FF) SIM slot

ndash HOLOGRAMIO nano sim included (can be exchanged if necessary)

141 Extensions

The external DB26 DIAG connector provides access to the three CAN buses and offers some free extension ports Theinternal PCB expansion connector allows stacked additions of further modules and serves for routing GPIO ports tothe external DIAG connector See schematics for details

A very nice first extension module has been developed by Marko Juhanne OVMS-SWCAN

If you plan on developing a hardware extension or just want to do some custom adaptations have a look at ourprototyping PCB kit Itrsquos available in packs of 3 PCBs and includes headers and mounting material

If the kit isnrsquot available at the distributors please contact Mark Webb-Johnson markwebb-johnsonnet

14 Hardware 7

Open Vehicles

15 Development and Contributions

New developers are very welcome on any part of the system and we will gladly provide any help needed to getstarted

The purpose of this project is to get the community of vehicle hackers and enthusiasts to be able to expand the projectWe canrsquot do it all and there is so much to do What we are doing is providing an affordable and flexible base that thecommunity can work on and extend

Everything is open and APIs are public Other car modules can talk to the server and other Apps can show the statusand control the car This is a foundation that others hopefully will interface to and and build upon

If yoursquod like to contribute please accept our code of conduct

bull Introduce yourself on the developer mailing list

bull Be kind amp polite

bull Understand the framework concepts

bull Ask if you need help

bull Present your plans if in doubt

bull Write decent code

bull If you extend modules stick to their code style

bull Write brief but descriptive commit comments

bull Add user level descriptions to the change history

bull Provide documentation in the user guide

bull Use pull requests to submit your code for inclusion

A note on pull requests

Pull requests shall focus on one specific issue feature vehicle at a time and shall only mix vehicle specific changeswith framework changes if they depend on each other If changes are not or only loosely related split them intomultiple PRs (just as you would do with commits)

Usage hint create a branch for each pull request include only those commits in that branch (by cherry-picking ifnecessary) that shall be included in the pull request That way you can push further commits to that branch Githubwill automatically add them to an open pull request

16 Donations

The OVMS is a non-profit community project Hardware production and service can normally be financed by salesbut some things (eg prototype development and certifications) need extra money To help the project you can makea donation on the OVMS website httpswwwopenvehiclescomforum

Please also consider supporting the vehicle developers directly Check out their web sites and support addresses fortheir respective donation channels

Thank you

8 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

Open Vehicles

17 License

The project includes some third party libraries and components to which their respective licenses apply see componentsources for details

The project itself is published under the MIT license

Copyright (c) 2011-2020 Open Vehicles

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

Software which uses other licenses will be annotated appropriately

17 License 9

Open Vehicles

10 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

CHAPTER 2

User Guide

21 Warnings and Notices

211 OVMS-33-7600G FCC Statement

This equipment has been tested and found to comply with the limits for a Class B digital device pursuant to part15 of the FCC Rules These limits are designed to provide reasonable protection against harmful interference in aresidential installation This equipment generates uses and can radiate radio frequency energy and if not installedand used in accordance with the instructions may cause harmful interference to radio communications Howeverthere is no guarantee that interference will not occur in a particular installation If this equipment does cause harmfulinterference to radio or television reception which can be determined by turning the equipment off and on the user isencouraged to try to correct the interference by one or more of the following measures

bull Reorient or relocate the receiving antenna

bull Increase the separation between the equipment and receiver

bull Connect the equipment into an outlet on a circuit different from that to which the receiver is connected

bull Consult the dealer or an experienced radioTV technician for help

Caution Any changes or modications to this device not explicitly approved by manufacturer could void your authorityto operate this equipment

This device complies with part 15 of the FCC Rules Operation is subject to the following two conditions (1)This device may not cause harmful interference and (2) this device must accept any interference received includinginterference that may cause undesired operation

212 OVMS-33-7600G Specific Absorption Rate (SAR) information

This OVMS-33-7600G meets the governmentrsquos requirements for exposure to radio waves The guidelines are basedon standards that were developed by independent scientific organizations through periodic and thorough evaluationof scientific studies The standards include a substantial safety margin designed to assure the safety of all personsregardless of age or health FCC RF Exposure Information and Statement the SAR limit of USA (FCC) is 16 Wkg

11

Open Vehicles

averaged over one gram of tissue Device types OVMS-33-7600G has also been tested against this SAR limit Thisdevice was tested for typical body-worn operations with the back of the phone kept 0mm from the body To maintaincompliance with FCC RF exposure requirements use accessories that maintain an 0mm separation distance betweenthe userrsquos body and the back of the phone The use of belt clips holsters and similar accessories should not containmetallic components in its assembly The use of accessories that do not satisfy these requirements may not complywith FCC RF exposure requirements and should be avoided

213 OVMS-33-7600G CE Statement

EU importer information

OpenEnergyMonitorInTec F9Ffordd y Parc Parc MenaiBangorLL57 4FGUnited Kingdom

This product can be used across EU member states

Specification

12 Chapter 2 User Guide

Open Vehicles

Manufacturer Open Vehicles LtdHardware Version Software Version Frequency Range

bull 24G WIFI 2412MHz ~ 2472MHz(Max powerRated 1569dBm)

bull GSM 900 880MHz ~ 915MHz(Max powerRated 3266dBm)

bull DCS 1800 1710MHz ~ 1785MHz(Max powerRated 2975dBm)

bull WCDMA Band I 1920MHz ~ 1980MHz(Maxpower Rated 2340dBm)

bull WCDMA Band VIII 880MHz~915MHz(Maxpower Rated 2310dBm)

bull E-UTRA Band 1 1920MHz ~ 1980MHz(Maxpower Rated 2280dBm)

bull E-UTRA Band 3 1710MHz~1785MHz(Maxpower Rated 2240dBm)

bull E-UTRA Band 7 2500MHz ~ 2570MHz(Maxpower Rated 2297dBm)

bull E-UTRA Band 8 880MHz ~ 915MHz(Maxpower Rated 2240dBm)

bull E-UTRA Band 20 832MHz ~ 862MHz(Maxpower Rated 2295dBm)

bull E-UTRA Band 28 703MHz ~ 748MHz(Maxpower Rated 2237dBm)

bull E-UTRA Band 34 2010MHz ~ 2025MHz(Maxpower Rated 2279dBm)

bull E-UTRA Band 38 2570MHz ~ 2620MHz(Maxpower Rated 2296dBm)

bull E-UTRA Band 40 2300MHz ~ 2400MHz(Maxpower Rated 2348dBm)

Receiver category 3

Members applicability

1 Extreme temperature -20-45 Celcius

2 The device complies with RF specifications when the device used at 5mm form your body

3 RED 201453EU

Declaration of Conformity

Hereby Open Vehicles Ltd declares that this OVMS-33-7600G product is in compliance with essential requirementsand other relevant provisions of Directive 201453EU A copy of the Declaration of conformity can be found atwwwopenvehiclescom

21 Warnings and Notices 13

Open Vehicles

214 General Warnings

WarningOVMS is a hobbyist project not a commercial product It was designed by enthusiasts for enthusiasts Installationand use of this module requires some technical knowledge and if you donrsquot have that we recommend you contactother users in your area to ask for assistance

WarningThe OVMS module is continuously powered by the car even when the car is off While the OVMS module usesextremely low power it does continuously draw power from the carrsquos battery so it will contribute to lsquovampirersquo powerdrains

Do not allow your car battery to reach 0 SOC and if it does plug in and charge the car immediately Failure to dothis can result in unrecoverable failure of the carrsquos battery

The module can monitor the main and 12V battery and send alert notifications if the SOC or voltage drops below ahealthy level

215 Average Power Usage

The power used by the module depends on the component activation You can save power by disabling unusedcomponents This can be done automatically by the Power Management module to avoid deep discharging the 12Vbattery or you can use scripts to automate switching components off and on

The base components need approximately these power levels continuously while powered on

Component Avg Power 12V CurrentBase System 200 mW 17 mAWifi 330 mW 28 mAModem 170 mW 13 mAGPS 230 mW 19 mATotal 930 mW 78 mA

This adds up to

bull ~ 22 Wh or 2 Ah day

14 Chapter 2 User Guide

Open Vehicles

bull ~ 156 Wh or 13 Ah week

bull ~ 680 Wh or 57 Ah month

Note that depending on the vehicle type the module may also need to wake up the ECU periodically to retrieve thevehicle status Check the vehicle specific documentation sections for hints on the power usage for this and options toavoid or reduce this

22 Components

221 The OVMS Module

The OVMS v3 module is housed in a plastic enclosure held secure by four small screws Once open you can see themain OVMS v3 motherboard and an optional modem board

At one end of the module is the main DB9 connector you will use to connect to the vehicle as well as GSM (cellular)and GPS (positioning) antenna connections

At the other end of the module is the DA26 expansion connector the USB diagnostic connector and a Micro SD cardslot

Warning The USB port is a fragile PCB socket without reinforcement Handle it carefully do not apply forcewhen plugging or unplugging cables to not bend the plug If you need to use the port frequently two dots of hotglue at the port sides on the PCB can help to avoid breaking it off

If you open the module and take out the board take care to guide the port carefully and correctly into itrsquos case holewhen inserting the board into the casing again Insert the board USB port side first

If removinginstalling optional expansion boards (such as used for cellular connectivity) please take care to ensureyou secure screw down the expansion board using the four pillar posts provided Also please ensure that the cellularmodem connections are correct (follow the printed table on the modem board to know which antenna is which)

22 Components 15

Open Vehicles

WarningThe OVMS v3 enclosure is not waterproof and the components can be damaged by water Do not get the modulewet and do not connect it to your vehicle if it is wet

222 Cellular Modem Option and GSM Antenna

The cellular modem option allows you to control your vehicle when out of wifi coverage range The majority ofOVMS users choose this option and you will require it if you want to monitor your vehicle when away from home oroffice

OVMS modules sold in USA and Europe are provided with a Hologram SIM card pre-installed This low cost serviceallows you to get cellular connectivity simply It also allows you to roam between countries without worry Formodules purchased from China we recommend you purchase a Hologram SIM directly from the hologramio store(also available on Amazon)

Depending on settings verbosity towards the OVMS server rhythm of GPS tracking etc OVMS v3 will use between1 and 3 Megabytes per month of data (when using the v2 server protocol)

You do not have to use the Hologram service If you use another cellular provider the Sim Card format required is4FF Nano Micro Sim cards are hard to recut into the smaller format so please be careful to not damage the socketotherwise ask your operator for a swap (some do it for free)

If you are using the cellular option you should attach a suitable cellular antenna to the module using the antennaconnector labeled ldquoGSMrdquo

Modem Status LED

The blue LED on the modem board shows the current modem status

LED Status SIM5360 (3G) SIM7600 (4G)ON Searching network Searching networkFast blinking (200ms) Data Transmit Data Transmit 4G registeredSlow blinking (800ms) Registered network 2G3G registered networkOFF Power off Sleep Power off Sleep

223 GPSGNSS Antenna

Some OVMS vehicles can read the GPS signals from the car communication networks directly and do not require anyadditional hardware For others the OVMS v3 modem option also includes a GNSSGPS satellite tracking receiver

If you are using this option you should connect a suitable active GPS antenna to the connector labelled ldquoGPSrdquo

16 Chapter 2 User Guide

Open Vehicles

224 Vehicle Connection

The connection to the vehicle is by the DB9 connector labelled ldquoVEHICLErdquo This provides power to the OVMSmodule as well as connection to the vehicle communication networks

Different vehicles require different cables so you should refer to the appropriate vehicle section of this user guide todetermine which is correct for yours

225 OVMS Server v2

The OVMS Server v2 protocol is a proprietary protocol used to communicate between the vehicle and an OVMS v2server as well as from that server to the cellphone apps To provide compatibility with existing OVMS v2 cellphoneapps and servers OVMS v3 includes full support for the OVMS v2 protocol

226 OVMS Server v3

The OVMS Server v3 protocol is MQTT This is an industry standard protocol and means an OVMS v3 module cancommunicate with any standard MQTT server While this is the future of OVMS support for this is experimental atthe moment and production users should use OVMS Server v2 protocol

227 Upgrading from OVMS v1v2 to v3

The antenna and vehicle connectors for OVMS v3 are the same as for OVMS v2 and existing cablesantennas cangenerally be re-used for OVMS v3 Note however that the frequency ranges supported by individual 3G networksmay be different than 2G so may benefit from an antenna specifically designed for the 3G frequency ranges used

23 Installation

231 Pre-Installation Steps

WarningPrior to connecting the OVMS module to the vehicle or computer via USB if you have the GSM cellular option werecommend you connect a GSM antenna GSM systems are designed to always operate with an antenna andpowering on one without could damage the equipment

Prior to installation please make sure you have the following available

1 The OVMS v3 module in itrsquos enclosure

2 A micro-usb cable suitable for connecting to your computer

3 A laptop or desktop computer (if necessary)

23 Installation 17

Open Vehicles

4 A cable suitable for connecting to your vehicle

5 A GSM antenna (if you are using the cellular option)

6 A GPS antenna (if your vehicle type requires one)

You should also have ready access to this User Guide and wifi connectivity to the Internet

232 OVMS Module Installation

Powering the module

If you intend to configure the module on your desk before connecting it to the vehicle make sure your USB portdelivers power (around 500mA depending on modem and wifi activity) We recommend using a USB hub with aseparate power supply or a direct port of your laptop PC

Warning The v33 LTE Modem (SIMCOM 7600G) may not be able to connect or not power up at all whenpowered from USB even with a powered USB hub

If you cannot get the cellular connection to work on your desk try powering from your carrsquos OBD port first

Another option is adding a 12V supply on your desk eg using a standard RC 3S LiPo battery (connect 12V+ toOBD pin 16 and GND- to OBD pin 4) You can connect USB and OBD12V supply simultaneously be aware themodule will boot as soon as any power source is present

OVMS Server account

If you want to use the OVMS App andor server based telemetry services yoursquoll need an OVMS v2 server account Ifyou have not registered for an OVMS server account yet you can do so before starting the wizard to avoid needing toswitch networks in between There are currently two public v2 OVMS servers

1 Asia-Pacific httpswwwopenvehiclescom

2 Europe httpsdexters-webde

You will need to create a user account first Within your user account you then need to create a vehicle account Yoursquollneed to pick a unique vehicle ID for this eg your vehicle license plate number

Initial Connection (Wifi and Browser)

From the factory or after a factory reset your OVMS module will be running an access point with the followingcredentials

SSID OVMS Password OVMSinit

As this is insecure you should take care not to leave the module running unconfigured

Using your laptoptabletphone establish a wifi connection to the module You should see an IP address in the range1921684x allocated with a gateway at 19216841

Note Some smartphones (eg Android) require mobile data to be switched off to use a WiFi connection without ainterent connectivity

Launch your web browser and connect as follows

URL http19216841

Once connected you will be presented with a screen as follows

18 Chapter 2 User Guide

Open Vehicles

23 Installation 19

Open Vehicles

Setup wizard

The first thing to do is run the setup wizard Click Start setup now The wizard takes you through the initial setup infive simple steps telling you what it is doing and what to expect for each step

20 Chapter 2 User Guide

Open Vehicles

23 Installation 21

Open Vehicles

The wizard will need to reconfigure the module for the Wifi setup read the notes and be prepared to reconnect to themodule as necessary

Note we recommend not to use a password manager during the setup process Some browsers eg Chrome will fillin the module ID as the username which is wrong The login username needs to be admin

The wizard should be able to restore access after problems occurring in the process As a last resort if it fails to recoverat some point you can always do a factory reset and start over again

Manual configuration

After finishing the wizard or if you prefer to do a manual setup the configuration menus will provide single pages foreach module function These also contain advanced options for the features so itrsquos worth having a look

Vehicle Configuration

Go to Config Vehicle

Yoursquoll want to enter your vehicle type Vehicle ID (the same as you registered on the OVMS server) and distance unitsYou can also optionally enter your timezone (see httpswwwgnuorgsoftwarelibcmanualhtml_nodeTZ-Variablehtml for an article on GLIBC timezones for information on the format of this a list of suitable zone strings can alsobe found here httpsremotemonitoringsystemscatime-zone-abbreviationsphp)

OVMS Server v2 Configuration

Go to Config Server V2 to configure the connection to the OVMS v2 server you will be using

22 Chapter 2 User Guide

Open Vehicles

You should enter the server host (apiopenvehiclescom or ovmsdexters-webde usually) and vehicle password (akaserver password - as entered on the server when you registered your vehicle) The Vehicle ID field should already bethere and the other parameters are optional

Auto Start Configuration

OVMS has a powerful scripting language that can be used for complex configurations but to get started it is simplestto use the Auto Start system You get to this from the web interface by clicking Config Autostart

23 Installation 23

Open Vehicles

You will usually want to click to Enable auto start and Start server v2 The other fields should have been populatedcorrectly automatically for you If you are using the optional modem module you should also click Start modem toenable the modem

Once complete you can Save amp reboot to activate your new configuration

WarningDo not set the Wifi mode to AP+Client or Client before having configured your Wifi network

If you have configured this manually the Wifi network may not start automatically Log in using a USB terminal andeither do a factory reset (see Module Factory Reset) or (better) issue enable to enter secure mode then issue configset auto wifimode ap and reboot

Networking Options

OVMS v3 has a number of networking options to choose from You can either use these individually or combine themto provide failover and alternative network connectivity arrangements

1 Wifi Client OVMS can connect to a WiFi Access Point using standard WiFi (80211 bgn) protocols toconnect to a SSID (Access Point name) with associated password In simple client mode you can connect onlyto a single pre-specified SSID Alternatively you can use the scanning client mode to connect to any known

24 Chapter 2 User Guide

Open Vehicles

WiFi Access Point when within range (note however that this is not possible when you run both client andaccess point on the same OVMS device)

2 Wifi Access Point OVMS can operate as a WiFi Access Point itself using standard WiFi (80211 bgn) pro-tocols This allows users to connect to the OVMS module itself Note that OVMS v3 is not intended to be ahotspot and users cannot access the Internet via the OVMS module Wifi Access Point mode can be combinedwith simple Wifi Client mode to provide an access point for maintenance of the module as well as a client toaccess the Internet via another Access Point within range

3 Cellular Data OVMS supports optional modems to provide cellular connectivity These are configured viaConfig Modem

233 GSM SIM Activation (Hologram)

OVMS has partnered with Hologram and to provide a Hologram GSM SIM pre-installed in every OVMS kit purchasedfrom our partners in Europe and USA For modules purchased from China we recommend you purchase a HologramSIM directly from the hologramio store (also available on Amazon) In addition Hologram have provided OVMS acoupon code valid for US$5 off data usage

Hologram Coupon Code OVMS

To activate your Hologram SIM register at httpsdashboardhologramio then invoke ldquoActivate SIMrdquo in the dash-board

Note You donrsquot need to purchase a phone number for your SIM right now as there is no SMS support in V3 yet Forthe current status of SMS support see

bull Issue 62 SMS Notifications

bull Issue 63 SMS Command Gateway

When activating your Hologram SIM yoursquoll need to enter the ICCID written on the SIM itself You can also get thatelectronically (without having to open up the enclosure) from the OVMS web or terminal shell (Tools gt Shell) withthe following command

OVMS metric list mnetmdmiccid

The ICCID is also displayed during the setup process and on the modem configuration page when using the web userinterface

23 Installation 25

Open Vehicles

234 Firmware Update

The factory firmware that is provided with the module may be quite out of date You should perform a firmware updateto ensure that you have the latest firmware You can do this either over Wifi client connections or via an SD CARD

We recommend using the auto update system This will be preconfigured if you have used the setup wizard Theautomatic updates are done within a selectable hour of day and only if Wifi connectivity is available at the time

26 Chapter 2 User Guide

Open Vehicles

Flash from Web

You can typically just press the Flash now button and wait for completion

Flash from File

Using an SD CARD formatted as FAT download the firmware update and place it in a file called ovms3bin in theroot directory of the SD CARD Once the SD CARD is inserted the firmware update will start immediately

235 12V Monitoring

Note Since release 32006 the 12V calibration and alert setup can be done from the web UIrsquos vehicle configurationpage

As 12V batteries tend to die without warning and need to handle an additional unplanned constant load from theOVMS the module includes a 12V monitoring and alert system

Calibration

The 12V voltage is measured using the incoming voltage that powers the OVMS As the sensor used by the modulehas some manufacturing tolerances you should do an initial calibration Use a voltage meter to measure the actualvoltage somewhere suitable (eg at a 12V auxiliary equipment plug) calibrate the OVMS to show the same Thecalibration factor is set by

config set systemadc factor12v ltfactorgt

Calculate the ltfactorgt using oldFactor (displayedVoltage actualVoltage)

bull oldFactor is the old value set If you have not changed it yet it is 1957

bull displayedVoltage is the Voltage as displayed by the OVMS

bull actualVoltage is the Voltage as measured by hand using a voltmeter

The voltage is read once per second and smoothed over 5 samples so after changing the factor wait 5-10 seconds forthe new reading to settle

23 Installation 27

Open Vehicles

Configuration

The default 12V reference voltage (= fully charged amp calmed down voltage level) can be set by

config set vehicle 12vref ltvoltagegt

This config value initializes metric vb12vvoltageref on boot The metric will then be updated automati-cally if your vehicle supports the vecharging12v flag The measured reference voltage reflects the health of the12V battery and serves as the reference for the 12V alert if itrsquos higher than the configured default

The 12V alert threshold can be set by

config set vehicle 12valert ltvoltagediffgt

The 12V alert threshold is defined by a relative value to the 12v reference voltage If the actual 12V reading dropsbelow 12vref - 12valert the 12V alert is raised

The default reference voltage is 126V the default alert threshold 16V so the alert will be triggered if the voltagedrops below 110V This is suitable for standard lead-acid type batteries If yoursquove got another chemistry change thevalues accordingly

Related Metrics

Metric Example Value Meaningvb12vcurrent 06A Momentary current level at the 12V batteryvb12vvoltage 1328V Momentary voltage level at the 12V batteryvb12vvoltageref 1251V Reference voltage of the fully charged amp calmed down 12V batteryvb12vvoltagealert no If the 12V critical alert is active (yesno)vecharging12v yes If the 12V battery is charging or not (yesno)

Related Events

Event Data Purposevehiclealert12von 12V system voltage is below alert thresholdvehiclealert12voff 12V system voltage has recoveredvehiclecharge12vstart Vehicle 12V battery is chargingvehiclecharge12vstop Vehicle 12V battery has stopped charging

24 The OVMS Console

241 Console Connections

OVMS v3 includes a powerful command line console that can be accessed in various ways

1 Using a micro USB cable to a host computer

If the OVMS is not recognised via USB download the driver from SILABS website You will also need asuitable terminal emulator The baud rate is 115200 and you should not enable hardware flow control

2 TELNET (over wifi)

28 Chapter 2 User Guide

Open Vehicles

Note that for security reasons the telnet server component is not enabled in the default productionfirmware (but may be available in custom builds) If Telnet is available telnet to the IP address of themodule (or ltvehicleidgtlocal MDNS address)

3 SSH (over wifi)

SSH to the IP address of the module (or ltvehicleidgtlocal MDNS address) Note that when first bootedwith a network connection the module takes a minute or so to generate server side keys (which are storedin the config store)

4 Web Console SHELL tab

Use a web browser to connect to the IP address of the module (or ltvehicleidgtlocal MDNS address) ASHELL tab is available for direct command line console access

5 Remote Apps

The OVMS Android App currently includes a shell screen that can be used to issue command line consolecommands via the OVMS server v2 This functionality is not currently available in the iPhoneiPad App

6 SMS

Console commands can be issued via SMS

USB Console

Our recommendations for the USB console are as follows

1 You can use a Windows Linux Mac OSX workstation or an Android device with a USB OTG adapter cable

2 If your operating system does not have the SILABS USB driver you can download the driver from SILABSwebsite If you use Linux and your distribution includes the braille display driver ldquobrlttyrdquo you may need touninstall that as it claims any CP2102 device to be a braille device This applies eg to openSuSE 150

3 Plug in the module to your PClaptop using a micro USB cable Check to ensure a serial port appears (using theSILABS driver) For OSX and Linux this will normally appear as devttySLAB_USBtoUART or devttyUSB0(or 12 if other serial devices are connected) List your devices using ldquols devUSBrdquo

4 Once the serial port is available you will need a terminal emulator

bull For OSX the simplest is the built-in SCREEN utility You run this as screen -L devttySLAB_USBtoUART 115200 But note that the device path may be different for you - check with lsquolsdevUSBrsquo You can use lsquocontrol-a control-yrsquo or lsquocontrol-a k yrsquo (three key sequences) to exit the screenThe ldquo-Lrdquo option tells screen to capture a log of your session into the file ldquoscreenlogltngtrdquo

bull For Linux the SCREEN utility is also simple to get If it is not included with your distribution you can simplyyum install screen or apt-get install screen (depending on your distribution) From there the command is thesame as for OSX Alternatively you can use minicom (which is included with many linux distributions)

bull For Windows a simple approach is to download the free PUTTY terminal emulator This supports both directASYNC (over USB) connections as well as SSH (network) You can download putty using this link

bull For Android there are multiple USB serial Apps in the Play store A good recommendation is Serial USBTerminal by Kai Morich

5 Once you have established the connection press ENTER to see the ldquoOVMSgtrdquo prompt

SSH Console

A workstation (Mac Linux Window) on the same wifi network as the OVMS module can use the ssh protocol toconnect In Windows you can use the free PUTTY ssh client In Linux and OSX ssh is built-in

24 The OVMS Console 29

Open Vehicles

The syntax is simply

ssh userip

Where lsquouserrsquo is the username (normally lsquoovmsrsquo) and lsquoiprsquo is the IP address of the OVMS v3 module In environmentssupporting mDNS networking you should also be able to connect using the mDNS name ltvehicleidgtlocal Thepassword you enter is the module password

If you use ssh publicprivate key pairs you can store your public key on the OVMS v3 module to take advantage ofpasswordless login

OVMS config set sshkeys ltusergt ltpublic-keygt

In this case lsquouserrsquo is the username you use to ssh and the public key is your RSA public key (the long base64 blob oftext you find in id-rsapub between lsquossh-rsarsquo and your usernamecomment)

You can also use SCP to copy files to and from the OVMS v3 VFS

Note With OpenSSH version 88 (or later) the ssh-rsa algorithm has been disabled by default and needs to beenabled manually either on the command line

ssh -o HostkeyAlgorithms=+ssh-rsa -o PubkeyAcceptedAlgorithms=+ssh-rsa userip

or by adding a host entry to your ~sshconfig file

Host ovmsnamelocalHostkeyAlgorithms +ssh-rsaPubkeyAcceptedAlgorithms +ssh-rsa

242 Console Basics

Letrsquos use SSH to demonstrate this

$ ssh ovmsovmslocal

Welcome to the Open Vehicle Monitoring System (OVMS) - SSH ConsoleFirmware 31003-2-g7ea18b4-dirtyfactorymainHardware OVMS WIFI BLE BT cores=2 rev=ESP321

OVMS

When first connecting using USB the console will be in non-secure mode (as indicated by the ldquoOVMSgtrdquo prompt)Here only a limited number of commands are available (such as viewing network status modem status or systemtime) To get to secure mode enter the command lsquoenablersquo and provide the module password The prompt will thenchange to ldquoOVMSrdquo

OVMSgt enablePasswordSecure modeOVMS

You can enter the lsquodisablersquo command to get out of secure mode and lsquoexitrsquo to exit the console completely

When connecting via a pre-authenticated protocol such as SSH you will be in secure mode automatically

At any time you can use ldquordquo to show the available commands For example

30 Chapter 2 User Guide

Open Vehicles

OVMS Run a scriptboot BOOT frameworkcan CAN frameworkcharge Charging frameworkco CANopen frameworkconfig CONFIG frameworkdisable Leave secure mode (disable access to most commands)egpio EGPIO frameworkenable Enter secure mode (enable access to all commands)event EVENT frameworkexit End console sessionhelp Ask for helphomelink Activate specified homelink buttonlocation LOCATION frameworklock Lock vehiclelog LOG frameworkmetrics METRICS frameworkmodule MODULE frameworknetwork NETWORK frameworknotify NOTIFICATION frameworkobdii OBDII frameworkota OTA frameworkpower Power controlre RE frameworkscript Run a scriptsd SD CARD frameworkserver OVMS Server Connection frameworkmodem MODEM frameworkstat Show vehicle statusstore STORE frameworktest Test frameworktime TIME frameworkunlock Unlock vehicleunvalet Deactivate valet modevalet Activate valet modevehicle Vehicle frameworkvfs Virtual File System frameworkwakeup Wake up vehiclewifi WIFI framework

You can also use ldquordquo as part of a command to expand on the available options within that command root

OVMS wifi mode WIFI mode frameworkscan Perform a wifi scanstatus Show wifi status

OVMS wifi mode ap Acts as a WIFI Access Pointapclient Acts as a WIFI Access Point and Clientclient Connect to a WIFI network as a clientoff Turn off wifi networking

OVMS wifi mode client Usage wifi mode client ltssidgt ltbssidgt

Command tokens can be abbreviated so long as enough characters are entered to uniquely identify the command Op-

24 The OVMS Console 31

Open Vehicles

tionally pressing TAB at that point will auto-complete the token If the abbreviated form is not sufficient to be unique(in particular if no characters have been entered yet) then TAB will show a concise list of the possible subcommandsand retype the portion of the command line already entered so it can be completed

OVMS wifi ltTABgtmode scan statusOVMS wifi

Pressing TAB is legal at any point in the command if there is nothing more that can be completed automatically thenthere will just be no response to the TAB

25 Logging

251 Logging to the Console

Components of the OVMS system output diagnostic logs (information warnings etc) You can choose to displaythese logs on your connected console with the lsquolog monitor yesnorsquo command

OVMS log monitor Usage log monitor [no|yes]no Dont monitor logyes Monitor log

By default the USB console will have log monitoring lsquoyesrsquo SSH (and telnet if enabled) lsquonorsquo

The web shell does not use the log monitor command but has a checkbox in the upper right corner of the shellpanel instead The keyboard shortcut for the checkbox is L (Alt-L or Alt-Shift-L depending on your browser) Theweb frontend gets the continuous stream of log messages independent of the shell panel or the monitoring being activeand shows the last 100 messages received when opening the shell panel

Logs are output at various levels of verbosity and you can control what is shown both globally and on a per-componentbasis

OVMS log level none No logging (0)error Log at the ERROR level (1)warn Log at the WARN level (2)info Log at the INFO level (3)debug Log at the DEBUG level (4)verbose Log at the VERBOSE level (5)

(Note sorted here for level clarity)

The syntax of this command is log level ltlevelgt [ltcomponentgt] If the component is not specified thelevel applies to all components that donrsquot get a level set explicitly afterwards The levels increase in verbosity andsetting a particular level will also include all log output at a lower level of verbosity (so for example setting level infowill also include warn and error output)

A log line typically looks like this

I (32244049) ovms-server-v2 One or more peers have connectedLog message

Component nameTimestamp (milliseconds since boot)

Log level (I=INFO)

32 Chapter 2 User Guide

Open Vehicles

Log levels are applied on log message generation so a later change to a higher level will not reveal messages generatedpreviously

252 Logging to SD CARD

You can also choose to store logs on SD CARD This is very useful to capture debugging information for the develop-ers as the log will show what happened before a crash or misbehaviour

We recommend creating a directory to store logs ie

OVMS vfs mkdir sdlogs

To enable logging to a file issue for example

OVMS log file sdlogs20180420log

The destination file can be changed any time To disable logging to the file issue log close to restart loggingafter a close issue log open You may choose an arbitrary file name good practice is using some date andor bugidentification tag Note logging will append to the file if it already exists To remove a file use vfs rm

File logging does not persist over a reboot or crash (unless configured as shown below) you can use a script bound tothe sdmounted event to re-enable file logging automatically or configure automatic logging (see below)

You can use the webserver to view and download the files The webserver default configuration enables directorylistings and access to files located under the document root directory which is sd by default Any path not bound toan internal webserver function is served from the document root So you can get an inventory of your log files now atthe URL

http19216841logs

and access your log files from there or directly by their respective URLs Another option to retrieve the files withoutunmounting the SD card is by scp if you have configured SSH access

253 Logging Configuration

Use the web UI or config command to configure your log levels and file setup to be applied automatically on boot

OVMS config list loglog (readable writeable)

fileenable yesfilekeepdays 7filemaxsize 1024filepath sdlogslogfilesyncperiod 3level infolevelmodem infolevelv-twizy verboselevelwebserver debug

25 Logging 33

Open Vehicles

The log command can be used for temporary changes if you change the configuration it will be applied as a wholereplacing your temporary setup

If a maximum file size gt0 is configured the file will be closed and archived when the size is reached The archivename consists of the log file name with added suffix of the timestamp ie sdlogslog20180421-140356Using a logs directory will keep all your archived logs accessible at one place If filekeepdays is defined olderarchived logs will automatically be deleted on a daily base

Take care not to remove an SD card while logging to it is active (or any running file access) The log file should stillbe consistent as it is synchronized after every write but the SD file system currently cannot cope with SD removalwith open files You will need to reboot the module To avoid this always use the ldquoCloserdquo button or the log closecommand before removing the SD card

You donrsquot need to re-enable logging to an SD path after insertion the module will watch for the mount event andautomatically start logging to it

254 Performance Impact

SD card IO has an impact on the module performance So file logging should generally be switched off or runon a low level (ie ldquoinfordquo or ldquowarnrdquo) unless yoursquore hunting some bug or checking some details of operation Wealso recommend using a fast SD card for logging (check the speed with sd status check if you can raise configsdcard maxfreqkhz to 20000 kHz)

34 Chapter 2 User Guide

Open Vehicles

File logging is done by a separate task but flushing the file buffers to the SD card still may block the logging CPUcore or even both CPU cores for a short period To reduce the impact of this the log task by default only flushes thebuffer after 15 seconds of log inactivity This means you may lose the last log messages before a crash

To change the flush behaviour set config filesyncperiod to

bull 0 = never flush (ie only at log close log cycle)

bull lt 0 = flush every n log messages (ie -1 = flush after every message)

bull gt 0 = flush after n2 seconds idle

The log task counts the time spent for flushes and outputs it with the log status command

OVMS log statusLog listeners 3File logging status active

Log file path sdlogslogCurrent size 8170 kBCycle size 1024 kBCycle count 8Dropped messages 0Messages logged 70721Total fsync time 6511 s

This is an example for the default configuration of filesyncperiod 3 the logging here has on average taken6511 70721 = 9 ms per message

26 Configuration

OVMS stores all itrsquos configuration in a standardised protected configuration area accessed by the lsquoconfigrsquo commandThe configurations are organised as follows

ltparametergt ltinstancegt = ltvaluegt

For example

Parameter Instance Valuevehicle id OVMSBOXwifissid MYSSID MyPasswordauto init yes

Each parameter can be defined (by the component that owns it) as having readable andor writeable attributes andthese act as access control for the parameters

bull A lsquowriteablersquo parameter allows values to be created deleted and modified

bull A lsquoreadablersquo parameter allows values to be seen Instance names can be seen on non-readable parameters (it isjust the values themselves that are protected)

For example the lsquovehiclersquo parameter is readable and writeable

OVMS config list vehiclevehicle (readable writeable)

id MYCARtimezone HKT-8

But the lsquowifissidrsquo parameter is only writeable

26 Configuration 35

Open Vehicles

OVMS config list wifissidwifissid (protected writeable)

MYSSIDMyOtherSSIDMyNeighbour

The lsquoconfigrsquo command is used to manipulate these configurations as is fairly self-explanatory

OVMS config list Show configuration parametersinstancesrm Remove parameterinstanceset Set parameterinstance=value

You can add new instances to parameters simply by setting them

Beginning with firmware release 32009 a dedicated configuration section usr is provided for plugins Take care toprefix all instances introduced by a unique plugin name so your plugin can nicely coexist with others

27 WiFi Networking

The OVMS WiFi system is based on the ESP32 integrated WiFi transceiver It uses and provides WiFi protocols80211 bgn and WPA2 authentication The current hardware can only use 24 GHz frequency bands

The WiFi antenna is built into the ESP32 module (PCB antenna) Itrsquos possible to replace that by an external antennabut yoursquoll need electronics knowledge and SMD soldering skills amp equipment

271 Client amp Access Point Modes

The OVMS WiFi network can be configured as a client (connecting to existing WiFi networks) andor access point(providing itrsquos own private WiFi network) Both modes can be run simultaneously which is the recommended defaultThat way you can always connect to your module via WiFi

OVMS wifi statusPower onMode Access-Point + Client mode

STA SSID WLAN-214677 (-787 dBm) [scanning]MAC 30aea45fe7ecIP 19216821022552552550GW 19216821AP 7cff4d152f86

AP SSID DEX106EMAC 30aea45fe7edIP 19216841AP Stations 0

In client mode the module can connect to a fixed network or automatically scan all channels for known networks toconnect to (ldquoscanning moderdquo) Scanning mode is configured by enabling client mode without a specific client SSID

The module will normally receive an IP address gateway and DNS from the WiFi access point by DHCP See belowon how to connect with a manual static IP setup

36 Chapter 2 User Guide

Open Vehicles

In access point mode the module provides access for other WiFi devices on a private network with the IP subnet1921684024 The modulersquos IP address on this network is 19216841 The module does not provide aDNS or routing to a public WiFi or GSM network on this subnet

You can define multiple AP networks but only one can be active at a time

Use the wifi mode command to manually set the mode use the auto start configuration to configure your defaultmode and networks

Note The module cannot act as a mobile hotspot ie provide access to the internet via itrsquos modem connectionThatrsquos in part due to security considerations and in part due to hardware limitations If you need this considerinstalling a dedicated mobile hotspot and using that one via WiFi instead of the modem for the modulersquos internetaccess (you wonrsquot need the modem in this setup)

272 Scanning for Networks

To manually scan your environment for available WiFi networks do a wifi scan

OVMS wifi scanScanning for WIFI Access Points

AP SSID MAC ADDRESS CHAN RSSI AUTHENTICATION================================ ================= ==== ==== ==============WLAN-214677 7cff4d152f86 1 -83 WPA2_PSKTelekom_FON 78dd1209dcbe 11 -84 OPENWLAN-184248 78dd1209dcbc 11 -85 WPA2_PSK===========================================================================Scan complete 3 access point(s) found

This can also be done in the web UIrsquos WiFi client network configuration page by clicking on the Select button

After the module lost connection to a network a scan is performed automatically every 10 seconds until a new con-nection can be established If yoursquod like to see the background scans and results in the log enable log level verbosefor component esp32wifi

Scan Troubleshooting

If the module doesnrsquot find your access point or can only see it occasionally in the scan results you may need to raiseyour scan times This has been observed on some older Android hotspots

By default the module will scan each channel for 120 milliseconds To raise that set your scan time in millisecondsusing the config command like this eg to 200 milliseconds

OVMS config set network wifiscantmin 200

200 milliseconds have been reported to solve the Android hotspot issue In addition to the tmin configuration youmay need to allow more time looking for further access points after finding the first one Do so by setting tmax eg

OVMS config set network wifiscantmax 300

Note that every increase will increase the time a full scan takes so donrsquot set too high values Too high values mayresult in connection drops on the AP network of the module

27 WiFi Networking 37

Open Vehicles

273 WiFi Signal Quality

Note For best performance yoursquoll need a signal level of -85 dBm or higher

bull Open the web status page the Wifi signal level can be monitored in the ldquoLiverdquo box

bull Try moving turning tilting your router ndash centimeters can make a huge difference After each move step backfrom the router and watch how the signal develops

bull Try switching to another Wifi channel (router configuration)

bull Try adding a repeater half way from the router to the car

The module monitors the WiFi client signal quality and drops a WiFi connection (switches to modem if available) if itbecomes too bad The WiFi connection will be kept active and monitored and as the signal recovers the module willautomatically reconnect to the AP

The default threshold is to stop using the connection if it drops below -89 dBm A connection is assumed to be usableif the signal is above -87 dBm

Depending on your WiFi environment the WiFi connection may still be usable at lower signal levels but it normallywill need stable levels above -87 dBm

To tweak the thresholds use the web UI WiFi configuration or change the following configuration variables

OVMS config set network wifisqgood -870OVMS config set network wifisqbad -890

274 WiFi Mesh Configuration

In normal operation the module will try to stick to an established connection as long as possible If signal qualitydrops it will switch to the modem connection but monitor the WiFi signal and reassociate to the current AP if possible

If using a mesh network you may want to force scanning for a better mesh AP as soon as the signal drops below theldquobadrdquo threshold To do so set the network configuration wifibadreconnect to true either using the web UIor by doing

OVMS config set network wifibadreconnect yes

With this the module will perform a full WiFi reconnect cycle as soon as the signal becomes bad

This is meant for the car moving between cells of your mesh network eg if the first cell is checked in at your gatebut a much better cell becomes available in your garage car port It should not be enabled if your Wifi signal isgenerally poor as that will cause many disconnects amp reconnects

275 Static IP SSID Configuration

To connect with a static client address instead of using DHCP use the wifi ip static command

OVMS wifi ip static [ltipgt ltsubnetgt ltgatewaygt]

The gateway will also be used as the DNS

To configure persistent static details for a known SSID set these using the following configuration syntax

38 Chapter 2 User Guide

Open Vehicles

OVMS config set wifissid ltssidgtovmsstaticip ltipgtltsubnetgtltgatewaygt

You can also force connection to a specific AP by itrsquos MAC address ldquoBSSIDrdquo in WiFi terms To do so you need tosupply the MAC address as a second argument to the wifi mode client or as the third argument to the wifimode apclient command

OVMS wifi mode client ltssidgt ltbssidgt

OVMS wifi mode apclient ltapssidgt ltssidgt ltbssidgt

This currently needs manual activation by command Hint use a script for example bound to a location

276 AP Bandwidth Configuration

In normal operation the default AP bandwidth is set to 20Mhz to reduce interference and improve the signal quality Ifa wider 40Mhz bandwidth is preferred eg for high throughput logging set the network configuration wifiapbwwith the command

OVMS config set network wifiapbw 40

Once the parameter is set the module will require rebooting to take effect The default bandwidth can be restored byeither removing the parameter or setting it to 20

28 Virtual File System (VFS)

OVMS includes a Virtual File System (VFS) used to unify all storage in the system The primary configuration andscripting storage is mounted as lsquostorersquo and the SD card as lsquosdrsquo A lsquovfsrsquo set of commands is provided for basicmanipulation of these stores

OVMS vfs append VFS Append a line to a filecat VFS Display a filecp VFS Copy a fileedit VFS Edit a filels VFS Directory Listingmkdir VFS Create a directorymv VFS Rename a filerm VFS Delete a filermdir VFS Delete a directorystat VFS Status of a filetail VFS Output tail of a file

Please take care This is a very small microcontroller based system with limited storage The store area should onlybe used for storage of configurations and small scripts The sd SD CARD area is more flexibly and can be used forstoring of configuration logs firmware images etc

281 Network Access

Network access to the VFS is available via SCP or through the web server

SCP can access the whole file system and is readwrite

28 Virtual File System (VFS) 39

Open Vehicles

copy a new firmware to the sd card on an OVMS named leaf in my ssh configscp buildovms3bin leafsddev_ovms3bin

copy a config backup from OVMS named leaf to my local directoryscp leafsdbackupcfg-2019-12-05zip

In the upload example the firmware can then be loaded with the OTA flash vfs command

The web server offers read access rooted at the sd card An example retrieving that same config file from the SCPexample would look like

httpleaf-abrlocalbackupcfg-2019-12-05zip

29 Metrics

Metrics are at the heart of the OVMS v3 system They are strongly typed named parameters with values in specificunits (and able to be automatically converted to other units) For example a metric to record the motor temperaturemay be an integer in Celsius units and may be convertible to Fahrenheit

The full list of metrics available can be shown

OVMS metrics listmfreeram 4232852mhardware OVMS WIFI BLE BT cores=2 rev=ESP321mmonotonic 3568Secvplatitude 222809vplongitude 114161vpodometer 100000Kmvpsatcount 12vpspeed 0Kphvptrip 0Kmvtalert 0001vthealth 95939674vtpressure 2068432164832757917579kPavttemp 33333438degCvtype DEMO

You can filter the metrics list output for names matching a given substring for example metrics listvolt will show all voltage related metrics

A base OVMS v3 system has more than 100 metrics available (see below) and vehicle modules can add more for theirown uses (see vehicle sections)

In general vehicle modules (and some other system components) are responsible for updating the metrics and serverconnections read those metrics reformat them and send them on to servers and Apps (for eventual display to the user)Status commands (such as STAT) also read these metrics and display them in user-friendly forms

OVMS statNot chargingSOC 500Ideal range 200KmEst range 160KmODO 1000000KmCAC 1600AhSOH 100

40 Chapter 2 User Guide

Open Vehicles

For developer use there are also some other metric commands used to manually modify a metricrsquos value (for testingand simulation purposes) and trace changes

OVMS metrics list Show all metricspersist Show persistent metrics infoset Set the value of a metrictrace METRIC trace framework

Some metrics are presistent across warm reboots This prevents values such as SOC from being lost when firmware isupdated (or in the event of a crash) You can display these with metrics list -p and view general informationabout presistent metrics with metrics persist

291 Standard Metrics

Metric name Example value Descriptionmfreeram 3275588 Total amount of free RAM in bytesmhardware OVMS WIFI BLE BT Base module hardware infommonotonic 49607Sec Uptime in secondsmnetmdmiccid 89490240001766080167 SIM ICCIDmnetmdmmodel 35316B09SIM5360E Modem module hardware infomnetmdmnetwork congstar Current GSM network providermnetmdmsq -101dBm and signal qualitymnetprovider WLAN-214677 Current primary network providermnetsq -79dBm signal qualitymnettype wifi and type (nonemodemwifi)mnetwifinetwork WLAN-214677 Current Wifi network SSIDmnetwifisq -791dBm and signal qualitymserial Reserved for module serial nomtasks 20 Task count (use module tasks to list)mtimeutc 1572590910Sec UTC time in secondsmversion 32005-155-g3133466f Firmware versionmegpioinput 012345679 EGPIO input port state (ports 0 9 present=high)megpiomonitor 89 EGPIO input monitoring portsmegpiooutput 45679 EGPIO output port statesv2connected yes yes = V2 (MP) server connectedsv2peers 1 V2 clients connectedsv3connected yes = V3 (MQTT) server connectedsv3peers V3 clients connectedvb12vcurrent 0A Auxiliary 12V battery momentary currentvb12vvoltage 1229V Auxiliary 12V battery momentary voltagevb12vvoltagealert yes = auxiliary battery under voltage alertvb12vvoltageref 123V Auxiliary 12V battery reference voltagevbctemp 1313 13degC Cell temperaturesvbctempalert 00 0 Cell temperature deviation alert level [0=normal 1=warning 2=alert]vbctempdevmax 143086 -129degC Cell maximum temperature deviation observedvbctempmax 1918 17degC Cell maximum temperaturesvbctempmin 1312 12degC Cell minimum temperaturesvbcvoltage 41054095 4105V Cell voltagesvbcvoltagealert 00 0 Cell voltage deviation alert level [0=normal 1=warning 2=alert]vbcvoltagedevmax 00096-00104 00125V Cell maximum voltage deviation observed

Continued on next page

29 Metrics 41

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvbcvoltagemax 41354125 414V Cell maximum voltagesvbcvoltagemin 38753865 388V Cell minimum voltagesvbcac 907796Ah Calculated battery pack capacityvbconsumption 0Whkm Main battery momentary consumptionvbcoulombrecd 475386Ah Main battery coulomb recovered on tripchargevbcoulombrecdtotal 9475386Ah Main battery coulomb recovered total (life time)vbcoulombused 0406013Ah Main battery coulomb used on tripvbcoulombusedtotal 835406013Ah Main battery coulomb used total (life time)vbcurrent 0A Main battery momentary current (output=positive)vbenergyrecd 269691kWh Main battery energy recovered on tripchargevbenergyrecdtotal 321269691kWh Main battery energy recovered total (life time)vbenergyused 00209496kWh Main battery energy used on tripvbenergyusedtotal 31770209496kWh Main battery energy used total (life time)vbhealth General textual description of battery healthvbplevelavg 95897 Cell level - pack averagevbplevelmax 9641 Cell level - strongest cell in packvbplevelmin 94871 Cell level - weakest cell in packvbplevelstddev 0548 Cell level - pack standard deviationvbptempavg 13degC Cell temperature - pack averagevbptempmax 13degC Cell temperature - warmest cell in packvbptempmin 13degC Cell temperature - coldest cell in packvbptempstddev 0degC Cell temperature - current standard deviationvbptempstddevmax 073degC Cell temperature - maximum standard deviation observedvbpvoltageavg 41V Cell voltage - pack averagevbpvoltagegrad 00032V Cell voltage - gradient of current seriesvbpvoltagemax 4105V Cell voltage - strongest cell in packvbpvoltagemin 409V Cell voltage - weakest cell in packvbpvoltagestddev 000535V Cell voltage - current standard deviationvbpvoltagestddevmax 000783V Cell voltage - maximum standard deviation observedvbpower 0kW Main battery momentary power (output=positive)vbrangeest 99km Estimated rangevbrangefull 508km Ideal range at 100 SOC amp current conditionsvbrangeideal 48km Ideal rangevbrangespeed 216kmh Momentary ideal range gainloss (chargedischarge) speedvbsoc 963 State of chargevbsoh 85 State of healthvbtemp 13degC Main battery momentary temperaturevbvoltage 574V Main battery momentary voltagevc12vcurrent 78A Output current of DCDC-convertervc12vpower 123W Output power of DCDC-convertervc12vtemp 345degC Temperature of DCDC-convertervc12vvoltage 123V Output voltage of DCDC-convertervccharging no yes = currently chargingvcclimit 0A Maximum charger output currentvccurrent 125A Momentary charger output currentvcdurationfull 25Min Estimated time remaing for full chargevcdurationrange -1Min for sufficient rangevcdurationsoc 0Min for sufficient SOCvcefficiency 876 Momentary charger efficiency

Continued on next page

42 Chapter 2 User Guide

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvckwh 26969kWh Energy sum for running chargevckwhgrid 36969kWh Energy drawn from grid during running sessionvckwhgridtotal 25669kWh Energy drawn from grid total (life time)vclimitrange 0km Sufficient range limit for current chargevclimitsoc 80 Sufficient SOC limit for current chargevcmode standard standard range performance storagevcpilot no Pilot signal presentvcpower 125kW Momentary charger input powervcstate done charging topoff done prepare timerwait heating stoppedvcsubstate scheduledstop scheduledstart onrequest timerwait powerwait stopped interruptedvctemp 16degC Charger temperaturevctime 0Sec Duration of running chargevctimermode yes = timer enabledvctimerstart Time timer is due to start seconds since midnight UTCvctype undefined type1 type2 chademo roadster teslaus supercharger ccsvcvoltage 0V Momentary charger supply voltagevdcp yes yes = Charge port openvdfl yes = Front left door openvdfr yes = Front right door openvdhood yes = Hoodfrunk openvdrl yes = Rear left door openvdrr yes = Rear right door openvdtrunk yes = Trunk openvealarm yes = Alarm currently soundingveaux12v yes = 12V auxiliary system is on (base system awake)veawake no yes = Vehicle is fully awake (switched on by the user)vecconfig yes = ECUcontroller in configuration stateveclogin yes = Module logged in at ECUcontrollervecabintemp 20degC Cabin temperaturevecabinfan 100 Cabin fanvecabinsetpoint 24degC Cabin set pointvecabinintake fresh Cabin intake type (fresh recirc etc)vecabinvent feetface Cabin vent type (comma-separated list of feet face screen etc)vecharging12v no yes = 12V battery is chargingvecooling yes = Coolingvedrivemode 33882626 Active drive profile code (vehicle specific)vedrivetime 0Sec Seconds driving (turned on)vefootbrake 0 Brake pedal state []vegear Geardirection negative=reverse 0=neutralvehandbrake yes = Handbrake engagedveheadlights yes = Headlights onveheating yes = Heatingvehvac yes = HVAC activevelocked yes = Vehicle lockedveon no yes = Vehicle is in ldquoignitionrdquo state (drivable)veparktime 49608Sec Seconds parking (turned off)veregenbrake yes = Regenerative braking activeveservrange 12345km Distance to next scheduled maintenanceservice [km]veservtime 1572590910Sec Time of next scheduled maintenanceservice [Seconds]

Continued on next page

29 Metrics 43

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvetemp Ambient temperaturevethrottle 0 Drive pedal state []vevalet yes = Valet mode engagedvggenerating no True = currently delivering powervgclimit 0A Maximum generator input current (from battery)vgcurrent 125A Momentary generator input current (from battery)vgdurationempty 25Min Estimated time remaining for full dischargevgdurationrange -1Min for range limitvgdurationsoc 0Min for SOC limitvgefficiency 876 Momentary generator efficiencyvgkwh 26969kWh Energy sum generated in the running sessionvgkwhgrid 36969kWh Energy sent to grid during running sessionvgkwhgridtotal 25669kWh Energy sent to grid totalvglimitrange 0km Minimum range limit for generator modevglimitsoc 80 Minimum SOC limit for generator modevgmode standard Generator mode (TBD)vgpilot no Pilot signal presentvgpower 125kW Momentary generator output powervgstate done Generator state (TBD)vgsubstate Generator substate (TBD)vgtemp 16degC Generator temperaturevgtime 0Sec Duration of generator runningvgtimermode false True if generator timer enabledvgtimerstart Time generator is due to startvgtype Connection type (chademo ccs )vgvoltage 0V Momentary generator output voltagevitemp Inverter temperaturevipower 427kW Momentary inverter motor power (output=positive)viefficiency 982 Momentary inverter efficiencyvmrpm Motor speed (RPM)vmtemp 0degC Motor temperaturevpacceleration 0ms2 Vehicle accelerationvpaltitude 3278m GPS altitudevpdirection 312deg GPS directionvpgpshdop 13 GPS horizontal dilution of precision (smaller=better)vpgpslock no yes = has GPS satellite lockvpgpsmode AA ltGPSgtltGLONASSgt NADE (NoneAutonomousDifferentialEstimated)vpgpsspeed 0kmh GPS speed over groundvplatitude 513023 GPS latitudevplocation Home Name of current location if definedvplongitude 739006 GPS longitudevpodometer 579131km Vehicle odometervpsatcount 8 GPS satellite count in viewvpspeed 0kmh Vehicle speedvptrip 0km Trip odometervtalert 0001 TPMS tyre alert levels [0=normal 1=warning 2=alert]vthealth 95939674 TPMS tyre health statesvtpressure 20682164 kPa TPMS tyre pressuresvttemp 33333438degC TPMS tyre temperatures

Continued on next page

44 Chapter 2 User Guide

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvtype RT Vehicle type codevvin VF1ACVYB012345678 Vehicle identification number

210 Over The Air (OTA) Updates

OVMS v3 includes 16MB flash storage This is partition as

4MB for factory application image (factory)4MB for the first OTA application image (ota_0)4MB for a second OTA application image (ota_1)1MB for store configuration and scripting storageThe remainder for bootloader generic non-volatile storage and other data

In general the factory application firmware is stored in flash at the factory during module production That firmwareis never changed on production modules and is always kept as a failover backup

That leaves two firmwares for Over The Air (OTA) updates If the currently running firmware is the factory one anOTA updated firmware can be written to either of the OTA partitions If the current running firmware is ota_0 thenany new OTA updates will be written to ota_1 (and similarly if ota_1 is currently running then new OTA updates willbe written to ota_0) In this way the currently running firmware is never modified and is always available as a failoverbackup

You can check the status of OTA with the lsquoota statusrsquo command

OVMS ota statusFirmware 31003-2-g7ea18b4-dirtyfactorymain (build idf v31-dev-453-rarr˓g0f978bcb Apr 7 2018 162657)Server Available 31003Running partition factoryBoot partition factory

That is showing the currently running firmware as a custom image v31003-2-g7ea18b4-dirty running in factorypartition The running currently running partition is factory and the next time the system is booted it will run fromfactory as well

As a convenience if there is currently active wifi connectivity a network lookup will be performed and the currentlyavailable firmware version on the server will be shown In this case that is the standard 31003 release (as shown inthe lsquoServer Availablersquo line)

If we wanted to boot from ota_1 we can do this with lsquoota boot ota_1rsquo

OVMS ota boot ota_1Boot from ota_1 at 0x00810000 (size 0x00400000)

OVMS ota statusFirmware 31003-2-g7ea18b4-dirtyfactorymain (build idf v31-dev-453-rarr˓g0f978bcb Apr 7 2018 162657)Server Available 31003Running partition factoryBoot partition ota_1

If the bootloader fails to boot from the specified OTA firmware it will failover and boot from factory

We can flash firmware to OTA either from a file on VFS (normally sd) or over the Internet (via http) Letrsquos try asimple OTA update over HTTP

210 Over The Air (OTA) Updates 45

Open Vehicles

OVMS ota flash httpCurrent running partition is factoryTarget partition is ota_0Download firmware from apiopenvehiclescomfirmwareotav31mainovms3bin to ota_0Expected file size is 2100352Preparing flash partitionDownloading (100361 bytes so far)Downloading (200369 bytes so far)Downloading (300577 bytes so far)Downloading (1903977 bytes so far)Downloading (2004185 bytes so far)Download complete (at 2100352 bytes)Setting boot partitionOTA flash was successful

Flashed 2100352 bytes from apiopenvehiclescomfirmwareotav31mainovms3binNext boot will be from ota_0

OVMS ota statusFirmware 31003-2-g7ea18b4-dirtyfactorymain (build idf v31-dev-453-rarr˓g0f978bcb Apr 7 2018 162657)Server Available 31003Running partition factoryBoot partition ota_0

Rebooting now (with lsquomodule resetrsquo) would boot from the new ota_0 partition firmware

OVMS ota statusFirmware 31003ota_0main (build idf v31-dev-453-g0f978bcb Apr 7 2018rarr˓131119)Server Available 31003Running partition ota_0Boot partition ota_0

211 Boot Status

OVMS maintains a record of the reason for each boot in RAM that survives a reboot It can show you how long themodule has been running for and the reason for the last reboot

OVMS boot statusLast boot was 2244 second(s) ago

This is reset 9 since last power cycleDetected boot reason SoftResetCrash counters 0 total 0 earlyCPU0 boot reason was 12CPU1 boot reason was 12

If an unexpected (not lsquomodule resetrsquo) reboot occurs within the first 10 seconds of startup (usually during the boot-timeauto-loading of modules scripts etc) the crash counters are incremented If those crash counters reach 5 (without aclean reset in between) then the auto-loading of modules is disabled for the 6th boot

In case of a crash the output will also contain additional debug information ie

Last crash abort() was called on core 1Backtrace

(continues on next page)

46 Chapter 2 User Guide

Open Vehicles

(continued from previous page)

0x40092ccc 0x40092ec7 0x400dbf1b 0x40176ca9 0x40176c6d 0x400eebd9 0x4013aed90x4013b538 0x40139c15 0x40139df9 0x4013a701 0x4013a731

If the module can access the V2 server after the crash reboot it will also store this information along with the crashcounters in the server table ldquo-OVM-DebugCrashrdquo which will be kept on the server for 30 days

Please include this info when sending a bug report along with the output of ldquoota statusrdquo and ndash if available ndash any logfiles capturing the crash event (see Logging to SD CARD) If you can repeat the crash please try to capture a log atldquolog level verboserdquo

212 Events

Internally OVMS raises events whenever significant events occur An event is a lightweight message of a name plusoptionally associated internal binary data Event names are top-down structured (so can be filtered by prefix) andsufficient to identify the source and type of the event Individual vehicle types may also issue their own events andcustom user events are also possible

To bind a script to an event save the script in directory storeeventslteventnamegt (hint directories canbe created using the web UI editor) Whenever events are triggered all the scripts in the corresponding storeeventslteventnamegt directory are executed Event scripts are executed in alphanumerical order of their namesGood practice is to prefix script names with 2-3 digit numbers in steps of 10 or 100 (ie first script named 50-)so new scripts can easily be integrated at a specific place If the event script is written in Javascript be sure to add thesuffix js to the name Other names will be executed using the standard command interpreter

If you want to introduce a custom event (eg for a plugin) prefix the event name by usrltpluginnamegtfollowed by the event purpose Example Foglight

Be aware events are processed in series from a queue so depending on the system load and the list of registeredevent listeners there may be some delay from event generation to eg a script execution

2121 Commands

bull event list [ltkeygt] ndash Show registered listeners for all or events matching a key (part of the name)

bull event trace lton|offgt ndash Enabledisable logging of events at the ldquoinfordquo level Without tracing events arealso logged but at the ldquodebugrdquo level Ticker events are never logged

bull event raise [-dltdelay_msgt] lteventgt ndash Manually raise an event optionally with a delay You canraise any event you like but you shouldnrsquot raise system events without good knowledge of their effects

2122 Standard Events

Event Data Purposeappconnected One or more remote Apps have connectedappdisconnected No remote Apps are currently connectedcanopennodeemcy lteventgt CANopen node emergency receivedcanopennodestate lteventgt CANopen node state change receivedcanopenworkerstart ltworkergt CANopen bus worker task startedcanopenworkerstop ltworkergt CANopen bus worker task stoppingclockHHMM Per-minute local time hour HH minute MM

Continued on next page

212 Events 47

Open Vehicles

Table 2 ndash continued from previous pageEvent Data PurposeclockdayN Per-day local time day N (0=Sun 6=Sat)configchanged Configuration has changedconfigmounted Configuration is mounted and availableconfigunmounted Configuration is unmounted and unavailableegpioinputltportgtltstategt EGPIO input port change (port=0 9 state=highlow)egpiooutputltportgtltstategt EGPIO output port change (port=0 9 state=highlow)gpslockacquired GPS lock has been acquiredgpslocklost GPS lock has been losthousekeepinginit Housekeeping has initialisedlocationalertflatbedmoved GPS movement of parked vehicle detectedlocationenterltnamegt ltnamegt The specified geolocation has been enteredlocationleaveltnamegt ltnamegt The specified geolcation has been leftnetworkdown All networks are downnetworkinterfacechange Network interface change detectednetworkinterfaceup Network connection is establishednetworkmgrinit Network manager has initialisednetworkmgrstop Network managed has been stoppednetworkmodemdown Modem network is downnetworkmodemup Modem network is upnetworkreconfigured Networking has been reconfigurednetworkup One or more networks are upnetworkwifidown WIFI network is downnetworkwifistabad WIFI client has bad signal levelnetworkwifistagood WIFI client has good signal levelnetworkwifiup WIFI network is upnotifylttypegtltsubtypegt An info alert error notification is sentretoolsclearedall RE frame log has been clearedretoolsclearedchanged RE frame change flags clearedretoolscleareddiscovered RE frame discovery flags clearedretoolsmodeanalyse RE switched to analysis moderetoolsmodediscover RE switched to discovery moderetoolsstarted RE (reverse engineering) toolkit startedretoolsstopped RE toolkit stoppedretoolspidscanstart RE OBD2 PID scan startedretoolspidscanstop RE OBD2 PID scan stoppedretoolspidscandone RE OBD2 PID scan completedsdinsert The SD card has just been insertedsdmounted The SD card is mounted and ready to usesdremove The SD card has just been removedsdunmounted The SD card has completed unmountingsdunmounting The SD card is currently unmountingserverv2authenticating V2 server connection is authenticatingserverv2connected V2 server connection established onlineserverv2connecting V2 server connection in progressserverv2connectwait V2 server is pausing before connectionserverv2disconnected V2 server connection has been lostserverv2stopped V2 server has been stoppedserverv2waitnetwork V2 server connection is waiting for networkserverv2waitreconnect V2 server is pausing before re-connection

Continued on next page

48 Chapter 2 User Guide

Open Vehicles

Table 2 ndash continued from previous pageEvent Data Purposeserverv3authenticating V3 server connection is authenticatingserverv3connected V3 server connection established onlineserverv3connecting V3 server connection in progressserverv3connectwait V3 server is pausing before connectionserverv3disconnected V3 server connection has been lostserverv3stopped V3 server has been stoppedserverv3waitnetwork V3 server connection is waiting for networkserverv3waitreconnect V3 server is pausing before re-connectionserverwebsocketclosed ltcntgt Web server lost a websocket clientserverwebsocketopened ltcntgt Web server has a new websocket clientsystemmodemdown Modem has been disconnectedsystemmodemgotgps Modem GPS has obtained locksystemmodemgotip Modem received IP address from DATAsystemmodeminstalled Modem type has been identified driver installedsystemmodemlostgps Modem GPS has lost locksystemmodemmuxstart Modem MUX has startedsystemmodemnetdeepsleep Modem is deep sleeping DATA networksystemmodemnethold Modem is pausing DATA networksystemmodemnetloss Modem has lost DATA networksystemmodemnetsleep Modem is sleeping DATA networksystemmodemnetstart Modem is starting DATA networksystemmodemnetwait Modem is pausing before starting DATAsystemmodempoweredon Modem is powered onsystemmodempoweringon Modem is powering onsystemmodemreceivedussd ltussdgt A USSD message has been receivedsystemmodemstop Modem has been shut downsystemshutdown System has been shut downsystemshuttingdown System is shutting downsystemstart System is startingsystemvfsfilechanged ltpathgt VFS file updated (note only sent on some file changes)systemwifiapstaconnected WiFi access point got a new client connectionsystemwifiapstadisconnected WiFi access point lost a client connectionsystemwifiapstaipassigned WiFi access point assigned an IP address to a clientsystemwifiapstart WiFi access point mode startingsystemwifiapstop WiFi access point mode stoppingsystemwifidown WiFi is shutting downsystemwifiscandone WiFi scan has been finishedsystemwifistaconnected WiFi client is connected to a stationsystemwifistadisconnected WiFi client has disconnected from a stationsystemwifistagotip WiFi client got an IP addresssystemwifistalostip WiFi client lost itrsquos IP addresssystemwifistastart WiFi client mode startingticker1 One second has passed since last tickerticker10 Ten seconds have passedticker300 Five minutes have passedticker3600 One hour has passedticker60 One minute has passedticker600 Ten minutes have passedvehiclealarmoff Vehicle alarm has been disarmed

Continued on next page

212 Events 49

Open Vehicles

Table 2 ndash continued from previous pageEvent Data Purposevehiclealarmon Vehicle alarm has been armedvehiclealert12voff 12V system voltage has recoveredvehiclealert12von 12V system voltage is below alert thresholdvehiclealertbms BMS cellpack voltstemps exceeded thresholdsvehicleasleep Vehicle systems are asleepvehicleawake Vehicle systems are awakevehicleaux12von Vehicle 12V auxiliary system is on (base system awake)vehicleaux12voff Vehicle 12V auxiliary system is offvehiclecharge12vstart Vehicle 12V battery is chargingvehiclecharge12vstop Vehicle 12V battery has stopped chargingvehiclechargefinished Vehicle charge has completed normallyvehiclechargemode ltmodegt Vehicle charge mode has been setvehiclechargepilotoff Vehicle charge pilot signal is offvehiclechargepiloton Vehicle charge pilot signal is onvehiclechargeprepare Vehicle is preparing to chargevehiclechargestart Vehicle has started to chargevehiclechargestate ltstategt Vehicle charge state has changedvehiclechargestop Vehicle has stopped chargingvehiclechargetimermodeoff Vehicle charge timer mode has been switched offvehiclechargetimermodeon Vehicle charge timer mode has been switched onvehicledrivemodeltngt Vehicle drivemode has been set to profile ltngt (vehicle specific)vehiclegearforward Vehicle has been put in forward gearvehiclegearneutral Vehicle has been put in neutral gearvehiclegearreverse Vehicle has been put in reverse gearvehicleheadlightsoff Vehicle headlights are offvehicleheadlightson Vehicle headlights are onvehiclelocked Vehicle has been lockedvehicleoff Vehicle has been switched offvehicleon Vehicle has been switched onvehiclerequiregps A vehicle has indicated it requires GPSvehiclerequiregpstime A vehicle has indicated it requires GPS timevehicletypecleared Vehicle module has been unloadedvehicletypeset lttypegt Vehicle module has been loadedvehicleunlocked Vehicle has been unlockedvehiclevaletoff Vehicle valet mode deactivatedvehiclevaleton Vehicle valet mode activated

213 Geofenced Locations

This section of the manual is still under development

214 Notifications

Notifications can be simple text messages or transport structured data To distinguish by their purpose and originnotifications have a type and a subtype

Notifications are sent by the module via the available communication channels (clientserver connections) If a channelis temporarily down (eg due to a connection loss) the notifications for that channel will be kept in memory until thechannel is available again (Note this message queue does not survive a crash or reboot of the module)

50 Chapter 2 User Guide

Open Vehicles

Channels process notifications differently depending on the way they work For example a v2 server will forward textnotifications as push messages to connected smart phones and email readers a v3 server will publish them under anMQTT topic and the webserver will display the message as a modal dialog See the respective manual sections fordetails

Notification types currently defined

bull info ndash informational text messages

bull alert ndash alert text messages

bull error ndash error code messages

bull data ndash historical data records usually CSV formatted

bull stream ndash live data streaming (high bandwidth) usually JSON formatted

The standard subtypes used are listed below these can be used to filter messages Vehicles may introduce customnotifications and replace standard notifications see the respective user guide section for details

Subtypes by convention are given in lower case with dots lsquorsquordquo as structural separators

Notification channels currently defined

bull ovmsv2 ndash server v2 connection

bull ovmsv3 ndash server v3 connection

bull ovmsweb ndash websocket connections

bull pushover ndash pushover text messaging service

Channels may have multiple active instances (ldquoreadersrdquo) for example you can open multiple websocket connectionsChannels may exclude notification types Currently stream records are only supported on a websocket connectionall other types are supported on all channels

Use notify status to see the currently registered channels (ldquoreadersrdquo) Example

OVMS notify statusNotification system has 3 readers registered

pushover(1) verbosity=1024ovmsv2(2) verbosity=1024ovmsweb(3) verbosity=65535

Notify typesalert 0 entriesdata 0 entrieserror 0 entriesinfo 0 entriesstream 0 entries

The channelrsquos ldquoverbosityrdquo defines the supported maximum length of a textual notification message on that channelNotification senders should honor this but not all may do so If messages exceed this limit they may be truncated

2141 Sending notifications

You can send custom notifications from the shell or command scripts by using the notify raise command Thecommand can send the output of another command an error code (implies type error) or any text you enter Forexample to send a custom text message do

OVMS notify raise text info usrantonwelcome Hello wonderful person

214 Notifications 51

Open Vehicles

In this case the type would be info and the subtype usrantonwelcome The type must match one of thedefined types the subtype can be chosen arbitrarily Please use a unique usr prefix for custom notifications to avoidcollisions

To send a battery status command result do

OVMS notify raise command info batterystatus stat

To send notifications from Duktape scripts use the API call OvmsNotifyRaise()

When a text (infoalert) or error notification is sent (ie has at least one listening channel eg pushover) anevent is raised once when the notification is queued The event will be named notifylttypegtltsubtypegt Forexample the second example above would come with an event notifyinfobatterystatus

2142 Suppress notifications

You can filter the channels to be used for notifications by their subtypes By default no subtypes are filtered on anychannel so all notifications are sent to all clients

To disable (suppress) notifications create a config entry based on the respective subtype that lists the channels toinclude or exclude

OVMS config set notify ltsubtypegt ltchannelsgt

ltchannelsgt options are

a) explicit inclusion eg ovmsv2pushover (only enable these)

b) explicit exclusion eg -ovmsv3-ovmsweb (only disable these)

c) - (dash) to disable all

d) empty to enable all

Example to disable the OTA update notifications on all channels do

OVMS config set notify otaupdate -

52 Chapter 2 User Guide

Open Vehicles

2143 Standard notifications

Type Subtype Purpose Contentalert alarmsounding Vehicle alarm is soundingalert alarmstopped Vehicle alarm has stoppedalert batt12valert 12V Battery criticalalert batt12vrecovered 12V Battery restoredalert battbmsalert Battery packcell alert (critical voltagetemperature deviation)alert battsocalert Battery SOC criticalinfo chargedone stat on charge finishedinfo chargestarted stat on start of chargeinfo chargetoppingoff stat on start of topping off chargephaseinfo chargestopped stat on planned charge stopalert chargestopped stat on unplanned charge stopdata debugcrash Transmit crash backtraces (rarr -OVM-DebugCrash)data debugtasks Transmit task statistics (rarr -OVM-DebugTasks)info drivetripreport Trip driving statistics (see Trip report)alert flatbedmoved Vehicle is being transported while parked - possible theftflatbedinfo heatingstarted stat on start of heating (battery)data loggrid Grid (chargegenerator) history log (see below) (rarr -LOG-Grid)data logtrip Trip history log (see below) (rarr -LOG-Trip)alert modemno_pincode No PIN code for SIM card configuredalert modemwrongpincode Wrong pin codeinfo otaupdate New firmware availabledownloadedinstalledinfo pushover Connection failure message delivery responsestream retoolslistupdate RE toolkit CAN frame list updatestream retoolsstatus RE toolkit general status updateinfo valetdisabled Valet mode disabledinfo valetenabled Valet mode enabledalert valethood Vehicle hood opened while in valet modealert valettrunk Vehicle trunk opened while in valet modealert vehicleidle Vehicle is idling stopped turned on

2144 Grid history log

The grid history log can be used as a source for long term statistics on your charges and typical energy usages and tocalculate your vehicle energy costs

Log entries are created on each change of the charge or generator state (vcstate vgstate)

You need to enable this log explicitly by configuring a storage time via config param notify loggridstoretime (in days) or via the web configuration page Set to 0empty to disable the log Already stored logentries will be kept on the server until expiry or manual deletion

Note the stability of the total energy counters included in this log depends on their source and persistence on thevehicle andor module If they are kept on the module they may lose their values on a power outage

bull Notification subtype loggrid

bull History record type -LOG-Grid

bull Format CSV

bull Archive time config notify loggridstoretime (days)

214 Notifications 53

Open Vehicles

bull Fieldscolumns

ndash pos_gpslock

ndash pos_latitude

ndash pos_longitude

ndash pos_altitude

ndash pos_location

ndash charge_type

ndash charge_state

ndash charge_substate

ndash charge_mode

ndash charge_climit

ndash charge_limit_range

ndash charge_limit_soc

ndash gen_type

ndash gen_state

ndash gen_substate

ndash gen_mode

ndash gen_climit

ndash gen_limit_range

ndash gen_limit_soc

ndash charge_time

ndash charge_kwh

ndash charge_kwh_grid

ndash charge_kwh_grid_total

ndash gen_time

ndash gen_kwh

ndash gen_kwh_grid

ndash gen_kwh_grid_total

ndash bat_soc

ndash bat_range_est

ndash bat_range_ideal

ndash bat_range_full

ndash bat_voltage

ndash bat_temp

ndash charge_temp

ndash charge_12v_temp

54 Chapter 2 User Guide

Open Vehicles

ndash env_temp

ndash env_cabintemp

ndash bat_soh

ndash bat_health

ndash bat_cac

ndash bat_energy_used_total

ndash bat_energy_recd_total

ndash bat_coulomb_used_total

ndash bat_coulomb_recd_total

2145 Trip history log

The trip history log can be used as a source for long term statistics on your trips and typical trip power usages as wellas your battery performance in different environmental conditions and degradation over time

Entries are created at the beginning and end of each ldquoignitionrdquo cycle (veon change) Configure a minimum triplength for logging by the config variable notify logtripminlength or via the web UI If your vehicle doesnot support the vptrip metric set the minimum trip length to 0

The log entry at the beginning of a trip is created to track non-driving SOC changes vampire drains and BMS SOCcorrections that occurred in between If yoursquore just interested in the actual drive results filter the records eg bypos_trip gt 01 or env_drivetime gt 10 (by default log entries will be created 3 seconds after the veonstate change)

You need to enable this log explicitly by configuring a storage time via config param notify logtripstoretime (in days) or via the web configuration page Set to 0empty to disable the log Already stored logentries will be kept on the server until expiry or manual deletion

bull Notification subtype logtrip

bull History record type -LOG-Trip

bull Format CSV

bull Archive time config notify logtripstoretime (days)

bull Fieldscolumns

ndash pos_gpslock

ndash pos_latitude

ndash pos_longitude

ndash pos_altitude

ndash pos_location

ndash pos_odometer

ndash pos_trip

ndash env_drivetime

ndash env_drivemode

ndash bat_soc

ndash bat_range_est

214 Notifications 55

Open Vehicles

ndash bat_range_ideal

ndash bat_range_full

ndash bat_energy_used

ndash bat_energy_recd

ndash bat_coulomb_used

ndash bat_coulomb_recd

ndash bat_soh

ndash bat_health

ndash bat_cac

ndash bat_energy_used_total

ndash bat_energy_recd_total

ndash bat_coulomb_used_total

ndash bat_coulomb_recd_total

ndash env_temp

ndash env_cabintemp

ndash bat_temp

ndash inv_temp

ndash mot_temp

ndash charge_12v_temp

ndash tpms_temp_min

ndash tpms_temp_max

ndash tpms_pressure_min

ndash tpms_pressure_max

ndash tpms_health_min

ndash tpms_health_max

2146 Trip report

The trip report outputs some core statistics of the current or most recent trip (drive cycle) It can be queried any timeusing the stat trip command or be configured to be sent automatically on turning the vehicle off

Use the web UI (Config rarr Notifications) or set config variable notify reporttripenable to yes andoptionally a minimum trip length in notify logtripminlength (defaults to 02 km) If your vehicle doesnot support the vptrip metric set the minimum trip length to 0

The statistics available depend on your vehicle type (ie metrics support of that vehicle adaption) Vehicles also mayoverride the report to provide custom statistics By default a full trip report will contain

bull Trip length

bull Average driving speed

bull Overall altitude difference (start to end point)

56 Chapter 2 User Guide

Open Vehicles

bull Energy consumption in Wh per kmMi

bull Recuperation percentage (in relation to energy used)

bull SOC difference amp new SOC

bull Estimated range difference amp new range

bull Average acceleration amp deceleration

The average driving speed is calculated only from speeds above 5 kph (3 mph) (to exclude slow speed rolling) andthe acceleration amp deceleration averages exclude values below 25 kphs (16 mphs) (constant speed cruising)

215 Time

This section of the manual is still under development

216 SSLTLS

Warning Letrsquos Encrypt root certificate expiration on September 30 2021

To prevent losing TLS connectivity with an LE secured server (like dexters-webde) with module firmwareversions 32016 or earlier you need to install the new root certificate manually Sorry for the inconvenience

See below Letrsquos Encrypt Root Certificate Update

2161 SSLTLS Trusted Certificate Authorities

A default minimal list of trusted certificate authorities (CA) is provided with the firmware you can see the currentloaded list with the tls trust list command

OVMS tls trust listAddTrust External CA Root length 15211521 byte certificate AddTrust External CA Root

cert version 3serial number 01issuer name C=SE O=AddTrust AB OU=AddTrust External TTP Network

rarr˓CN=AddTrust External CA Rootsubject name C=SE O=AddTrust AB OU=AddTrust External TTP Network

rarr˓CN=AddTrust External CA Rootissued on 2000-05-30 104838expires on 2020-05-30 104838signed using RSA with SHA1RSA key size 2048 bitsbasic constraints CA=truekey usage Key Cert Sign CRL Sign

If you want to add to this list you can place the PEM formatted root CA certificate in the storetrustedcadirectory on your config partition using the text editor Then reload the list with

OVMS tls trust reloadReloading SSLTLS trusted CA listSSLTLS has 4 trusted CAs using 5511 bytes of memory

215 Time 57

Open Vehicles

On boot the trusted Certificate Authorities provided in firmware and put in your storetrustedca directorywill be automatically loaded and made available

These trusted certificate authorities are used by the various module in the OVMS system when establishing SSLTLSconnections (in order to verify the certificate of the server being connected to)

2162 How to get the CA PEM for a Server

Download from CA

If you know the CA check their download section

Using a Browser

This only works for https servers

1 Open the website you want to access

2 Open the encryption info (eg Chrome lock icon at URL rarr show certificate)

3 Display the certificate chain (eg Chrome tab ldquoDetailsrdquo first element)

4 Select the last entry before the actual server certificate

5 Export the certificate in PEM format (usually the default)

6 Install the file contents as shown above

Using OpenSSL or GNU TLS CLI

This works for all servers and ports

openssl s_client -connect HOSTNAMEPORT -servername HOSTNAME -showcerts ltdevnull | sed -ne -BEGIN CERTIFICATE--END CERTIFICATE-p

or

gnutls-cli --print-cert --port PORT HOSTNAME ltdevnull | sed -ne -BEGIN CERTIFICATE--END CERTIFICATE-p

Substitute HOSTNAME and PORT accordingly eg https = port 443 The sed just strips the other info from theoutput and can be omitted to check for errors or details

There should be two certificates in the output look for BEGIN and END markers The first one is the server certificatethe second one the CA certificate Copy that second certificate into the editor take care to include the BEGIN andEND lines

2163 Letrsquos Encrypt Root Certificate Update

If running firmware version 32016 or earlier you need to install the new Letrsquos Encrypt root certificate (ldquoISRGRoot X1rdquo) manually to enable encrypted connections to servers secured by a Letrsquos Encrypt certificate

1 Save the certificate text shown below to file storetrustedcaisrgx1

2 Issue command tls trust reload or reboot the module

Certificate text

58 Chapter 2 User Guide

Open Vehicles

-----BEGIN CERTIFICATE-----MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2VhcmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygch77ct984kIxuPOZXoHj3dcKivVqbvYATyjb3miGbESTtrFjRQSa78f0uoxmyF+0TM8ukj13Xnfs7jEvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6UA5TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sWT8KOEUt+zwvo7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hmELNKjD+Jo2FR3qyHB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UCB5iPNgiV5+I3lg02dZ77DnKxHZu8AlJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUvKBds0pjBqAlkd25HN7rOrFleaJ1ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWnOlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTnjh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbwqHyGO0aoSCqI3Haadr8faqU9GYrOPNk3sgrDQoofb4hVC1CLQJ13hef4Y53CIrU7m2Ys6xt0nUW7vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEBwQEAwIBBjAPBgNVHRMBAf8EBTADAQHMB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkqhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaSV9lZLubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ3BebYhtF8GaV0nxvwuo77xPy9auJGpsMiuX1+mvoiBOv2XqkSsisRcOjKKNFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7UrTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l++sKAIuvtd7u+Nxe5AW0wdeRlN8NwdCjNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVcoyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui01lvh+wjChP4kqKOJ2qxq4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9Ut7y0Ff9yi0GE44Za4rF2LN9d11TPAmRGunUHBcnWEvgJBQl9nJEiU0ZsnvgcubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57demyPxgcYxneR44KJ4EBs+lVDR3veyJm+kXQ99b21+jh5Xos1AnX5iItreGCc=-----END CERTIFICATE-----

217 Scripting

2171 Command Scripts

Lists of commands can be entered into a script file and stored in the VFS for execution (in the storescriptsdirectory) These are called lsquocommand scriptsrsquo and are simple sequential lists of OVMS commands A commandscript can be executed with

OVMS ltscriptgtOVMS script run ltscriptgt

Command scripts can also be stored in the storeeventslteventnamegt directory structure Whenever eventsare triggered all the scripts in the corresponding storeeventslteventnamegt directory are executed Eventscripts are executed in alphanumerical order of their names Good practice is to prefix script names with 2-3 digitnumbers in steps of 10 or 100 (ie first script named 50-) so new scripts can easily be integrated at a specificplace

Output of background scripts without console association (eg event scripts) will be sent to the log with tag scriptat ldquoinfordquo level

Note that the developer building firmware can optionally set the OVMS_DEV_SDCARDSCRIPTS build flag If thatis set then the system will also check sdscripts and sdevents for scripts This should not be used forproduction builds as you could hack the system just by plugging in an SD card

217 Scripting 59

Open Vehicles

In addition to command scripts more sophisticated scripting capabilities may be enabled if the JavaScript environmentis enabled in the build This is discussed in the next section of this guide

2172 JavaScripting

OVMS v3 includes a powerful JavaScript engine In addition to the standard relatively fixed firmware flashed tothe module JavaScripting can be used to dynamically load script code to run alongside the standard firmware Thisjavascript code can respond to system events and perform background monitoring and other such tasks

The simplest way of running javascript is to place a piece of javascript code in the storescripts directory withthe file extension js Then the standard mechanism of running scripts can be employed

OVMS ltscriptjsgtOVMS script run ltscriptjsgt

Short javascript snippets can also be directly evaluated with

OVMS script eval ltcodegt

Such javascript code can also be placed in the storeeventslteventnamegt directories to be automaticallyexecuted when the specified event is triggered The script file name suffix must be js to run the Javascript interpreter

Note The scripting engine used is Duktape Duktape supports ECMAScript E5E51 with some additions from laterECMAScript standards Duktape does not emulate a browser environment so you donrsquot have window or documentobjects etc just core Javascript plus the OVMS API and plugins

Duktape builtin objects and functions httpsduktapeorgguidehtmlduktapebuiltins

2173 Persistent JavaScript

When a javascript script is executed it is evaluated in the global javascript context Care should be taken that localvariables may pollute that context so it is in general recommended that all JavaScript scripts are wrapped

(function() user code

)()

It is also possible to deliberately load functions and other code into the global context persistently and have thatcode permanently available and running When the JavaScript engine initialises it automatically runs a special startupscript

storescriptsovmsmainjs

That script can in turn include other code If you make a change to such persistent code and want to reload it you canwith

OVMS script reload

2174 JavaScript Modules

The OVMS JavaScript engine supports the concept of modules (using the nodejs style of exports) Such modules canbe written like this

60 Chapter 2 User Guide

Open Vehicles

exportsprint = function(obj ind) var type = typeof objif (type == object ampamp ArrayisArray(obj)) type = arrayif (ind) ind =

switch (type) case string

print( + objreplace(g ) + )break

case arrayprint([n)for (var i = 0 i lt objlength i++) print(ind + )exportsprint(obj[i] ind + )if (i = objlength-1) print()print(n)

print(ind + ])break

case objectprint(n)var keys = Objectkeys(obj)for (var i = 0 i lt keyslength i++) print(ind + + keys[i] + )exportsprint(obj[keys[i]] ind + )if (i = keyslength-1) print()print(n)

print(ind + )break

defaultprint(obj)

if (ind == ) print(n)

By convention modules such as this are placed in the storescriptslib directory as ltmodulenamegtjsThese modules can be loaded with

JSON = require(libJSON)

And used as

JSONprint(this)

To automatically load a custom module on startup add the MyPlugin = require(libMyPlugin) lineto ovmsmainjs

There are a number of internal modules already provided with the firmware and by convention these are providedunder the intltmodulenamegt namespace The above JSON module is for example provided as intJSON andautomatically loaded into the global context These internal modules can be directly used (so JSONprint(this)works directly)

217 Scripting 61

Open Vehicles

2175 Testing JavaScript Modules

Use the editor (see Tools menu) to test or evaluate arbitrary Javascript code This can be done on the fly ie withoutsaving the code to a file first Think of it as a server side Javascript shell

Testing modules normally involves reloading the engine as the require() call caches all loaded modules untilrestart To avoid this during module development use the following template code This mimics the require() callwithout caching and allows to do tests within the same evaluation run

Load modulemymodule = (function()exports =

insert module code here

return exports)()

Module API testsmymodulemyfunction1()JSONprint(mymodulemyfunction2())

As the module is actually loaded into the global context this way just like using require() anything else using themodule API (eg a web plugin) will also work after evaluation

2176 Heap Memory

Due to limitations of the general esp-idf system memory management Duktape will normally use the custom memorymanager umm_malloc by Ralph Hempel

umm_malloc needs a dedicated chunk of the system memory to work with The default for Duktape is 512 KB(taken from SPIRAM) which is normally sufficient even for extended scripting If you need more RAM the sizecan be changed by config set module duktapeheapsize ltsize_in_KBgt Maximum allowed size is1024 KB The heap size needs to be configured at Duktape startup and cannot be changed while Duktape is runningTo reconfigure the heap size set the new configuration and do a script reload

Call meminfo() to query the current heap memory usage status The function returns an object containing somestandard and some memory library internal info The shell command script meminfo outputs the object in JSONformat Example

OVMS script meminfo

totalBytes 524224usedBytes 273344freeBytes 250880largestFreeBytes 180608memlib ummummTotalEntries 2723ummUsedEntries 2615ummFreeEntries 108ummTotalBlocks 16382ummUsedBlocks 8542ummFreeBlocks 7840ummMaxFreeContiguousBlocks 5644ummUsageMetric 108ummFragmentationMetric 27

62 Chapter 2 User Guide

Open Vehicles

ldquolargestFreeBytesrdquo is the largest block of contiguous memory available Note these values will change by someamount between the garbage collection runs done every 60 seconds the maximum usage will be just before thegarbage collection and the base line just after

ldquomemlibrdquo tells about the memory manager in use the following fields are the internal state variables and statistics ofthat manager (having the memlib name as a name prefix) These can be useful to monitor the memory managementload and performance

If running a firmware configured to use the default system memory manager the output will look like this

OVMS script meminfo

totalBytes 4072176usedBytes 415996freeBytes 3656180largestFreeBytes 3635864memlib syssysMinimumFreeBytes 3653072sysAllocatedBlocks 6013sysFreeBlocks 454sysTotalBlocks 6467

2177 Internal Objects and FunctionsMethods

A number of OVMS objects have been exposed to the JavaScript engine and are available for use by custom scriptsvia the global context

The global context is the analog to the window object in a browser context it can be referenced explicitly as thison the JavaScript toplevel or as globalThis from any context

You can see the global context objects methods functions and modules with the JSONprint(this) method

OVMS script eval JSONprint(this)

performance now function now() [native code]

assert function () [native code] print function () [native code] write function () [native code] meminfo function () [native code] OvmsCommand Exec function Exec() [native code]

OvmsConfig Delete function Delete() [native code] Get function Get() [native code] Instances function Instances() [native code] Params function Params() [native code] Set function Set() [native code]

OvmsEvents Raise function Raise() [native code]

OvmsLocation Status function Status() [native code]

(continues on next page)

217 Scripting 63

Open Vehicles

(continued from previous page)

OvmsMetrics AsFloat function AsFloat() [native code] AsJSON function AsJSON() [native code] Value function Value() [native code]

OvmsNotify Raise function Raise() [native code]

OvmsVehicle ClimateControl function ClimateControl() [native code] Homelink function Homelink() [native code] Lock function Lock() [native code] SetChargeCurrent function SetChargeCurrent() [native code] SetChargeMode function SetChargeMode() [native code] SetChargeTimer function SetChargeTimer() [native code] StartCharge function StartCharge() [native code] StartCooldown function StartCooldown() [native code] StopCharge function StopCharge() [native code] StopCooldown function StopCooldown() [native code] Type function Type() [native code] Unlock function Unlock() [native code] Unvalet function Unvalet() [native code] Valet function Valet() [native code] Wakeup function Wakeup() [native code]

JSON format function () [ecmascript code] print function () [ecmascript code]

PubSub publish function () [ecmascript code] subscribe function () [ecmascript code] clearAllSubscriptions function () [ecmascript code] clearSubscriptions function () [ecmascript code] unsubscribe function () [ecmascript code]

Global Context

bull assert(conditionmessage) Assert that the given condition is true If not raise a JavaScript exceptionerror with the given message

bull print(string) Print the given string on the current terminal If no terminal (for example a backgroundscript) then print to the system console as an informational message

bull write(stringUint8Array) Write the given string or Uint8Array to the current output channel (ieterminalHTTP connection) Use this to transfer binary data to a reader

bull meminfo() Returns an object containing the current heap memory status (see Heap Memory)

bull performancenow() Returns monotonic time since boot in milliseconds with microsecond resolution

64 Chapter 2 User Guide

Open Vehicles

JSON

The JSON module extends the native builtin JSONstringify and JSONparse methods by a format and aprint method to format andor print out a given javascript object in JSON format Both by default insert spacingand indentation for readability and accept an optional false as a second parameter to produce a compact version fortransmission

bull JSONprint(data) Output data (any Javascript data) as JSON readable

bull JSONprint(data false) compact (without spacingindentation)

bull str = JSONformat(data) Format data as JSON string readable

bull str = JSONformat(data false) compact (without spacingindentation)

bull JSONstringify(value[ replacer[ space]]) see MDN JSONstringify

bull JSONparse(text[ reviver]) see MDN JSONparse

Note The JSON module is provided for compatibility with standard Javascript object dumps and for readability Ifperformance is an issue consider using the Duktape native builtins JSONstringify() Duktapeenc() andJSONparse() Duktapedec() (see Duktape builtins and Duktape JSON for explanations of these)

For example Duktapeenc(JC data) is equivalent to JSONformat(data false) except for therepresentation of functions Using the JX encoding will omit unnecessary quotings

Warning All Duktape JSON encoders and decoders have a very high performance penalty and should beavoided for large objects or frequent encodingdecoding with large being any object larger than a handful ofconfiguration or state variables

For general data storage and exchange with the web UI use the CBOR serialization instead

CBOR

CBOR is a binary serialization format and especially with Duktape the better alternative over JSON for storage anddata transmission if human readability isnrsquot required

ldquoCBORrdquo stands for ldquoConcise Binary Object Representationrdquo See httpscborio for details on the specification andavailable implementations CBOR isnrsquot necessarily more compact in storage space but can be encoded and decodedmuch faster and with much less memory overhead as JSON

Duktape implements CBOR support by the builtin CBORencode() and CBORdecode() methods

bull enc = CBORencode(data) Encode data (any Javascript data) to CBOR format (result is an ArrayBuffer)

bull data = CBORdecode(enc) Decode CBOR format (ArrayBufferUint8Array) to Javascript data

CBOR support in Duktape is still considered experimental but the underlying implementation is mature

CBOR also isnrsquot part of the standard browser builtin Javascript APIs yet so the OVMS web framework includes thecbor-js library by Patrick Gansterer (same API as on the Duktape side)

The webserver command API supports binary output from commands amp Javascript API methods and the output canbe passed to CBORdecode() directly

Example

The following scheme shows how to transmit a javascript data object from the module backend into the web frontend

217 Scripting 65

Open Vehicles

Module backendbackendgetdata = function ()

var mydata = pi 3141 fib [ 011235813 ] write(CBORencode(mydata))

Web frontendloadjs( command backendgetdata() output binary )done((stream) =gt

var mydata = CBORdecode(stream))

For full examples see the ldquoAuxBatMonrdquo and ldquoPwrMonrdquo plugins

Note When loading CBOR data via VFSLoad() you need to set the binary option to true so the loader willreturn a Uint8Array instead of a standard string

HTTP

The HTTP API provides asynchronous GET amp POST requests for HTTP and HTTPS Requests can return text andbinary data and follow 301302 redirects automatically Basic authentication is supported (add username amp passwordto the URL) digest authentication is not yet implemented

The handler automatically excludes the request objects from garbage collection until finished (successfailure) so youdonrsquot need to store a global reference to the request

bull req = HTTPRequest(cfg) Perform asynchronous HTTPHTTPS GET or POST request

Pass the request parameters using the cfg object

ndash url standard URLURI syntax optionally including user auth and query string

ndash post optional POST data set to an empty string to force a POST request Note you needto provide this in encoded form If no Content-Type header is given it will default tox-www-form-urlencoded

ndash headers optional array of objects containing key-value pairs of request headers NoteUser-Agent will be set to the standard OVMS user agent if not present here

ndash timeout optional timeout in milliseconds default 120 seconds

ndash binary optional flag true = perform a binary request (see response object)

ndash done optional success callback function called with the response object as argument with thispointing to the request object

ndash fail optional error callback function called with the error string as argument with this point-ing to the request object

ndash always optional final callback function no arguments this = request object

The cfg object is extended and returned by the API (req) It will remain stable at least until the requesthas finished and callbacks have been executed On completion the req object may contain an updatedurl and a redirectCount if redirects have been followed Member error (also passed to the failcallback) will be set to the error description if an error occurred The always callback if present is calledin any case after a done or fail callback has been executed Check thiserror in the alwayscallback to know if an error occurred

On success member object response will be present and contain

66 Chapter 2 User Guide

Open Vehicles

ndash statusCode the numerical HTTP Status response code

ndash statusText the HTTP Status response text

ndash headers array of response headers each represented by an object ltnamegt ltvaluegt

ndash body only for text requests response body as a standard string

ndash data only for binary requests response body as a Uint8Array

Notes any HTTP response from the server is considered success check responsestatusCode forserver specific errors Callbacks are executed without an output channel so all print outputs will bewritten to the system log Hint use JSONprint(this false) in the callback to get a debug logdump of the request

Examples

simple POST ignore all resultsHTTPRequest( url httpsmartpluglocalswitch post state=onampwhen=nowrarr˓ )

fetch and inspect a JSON objectHTTPRequest(

url httpsolarcontrollerlocalstatusfmt=jsondone function(resp)

if (respstatusCode == 200) var status = JSONparse(respbody)if (status[power] gt 5000)OvmsVehicleStartCharge()

else if (status[power] lt 3000)OvmsVehicleStopCharge()

)

override user agent log completed request objectHTTPRequest(

url httpsdexters-webdeftestjsonheaders [ User-Agent Mr What Zit Tooya ]always function() JSONprint(this false)

)

bull HTTPrequest() Legacy alias for HTTPRequest() please do not use

Note SSL requests (https) can take up to 12 seconds on an idle module SSL errors also may not reflect the actualerror for example an empty server response with code 400 may be reported as a general ldquoSSL errorrdquo If you get ldquoSSLerrorrdquo on a valid request you may need to install a custom root CA certificate see SSLTLS

VFS

The VFS API provides asynchronous loading and saving of files on store and sd Text and binary data issupported Currently only complete files can be loaded the saver supports an append mode In any case the data tosaveload needs to fit into RAM twice as the buffer needs to be converted tofrom Javascript

The handler automatically excludes the request objects from garbage collection until finished (successfailure) so youdonrsquot need to store a global reference to the request

217 Scripting 67

Open Vehicles

Loading or saving protected paths (storeovms_config) is not allowed Saving to a path automaticallycreates missing directories

See AuxBatMon 12V History Chart for a complete application usage example

bull req = VFSLoad(cfg) Perform asynchronous file load

Pass the request parameters using the cfg object

ndash path full file path eg sdmydatatelemetryjson

ndash binary optional flag true = perform a binary request returned data will be an Uint8Array)

ndash done optional success callback function called with the data content read as the single argumentthis pointing to the request object

ndash fail optional error callback function called with the error string as argument with this point-ing to the request object

ndash always optional final callback function no arguments this = request object

The cfg object is extended and returned by the API (req) It will remain stable at least until the requesthas finished and callbacks have been executed On success the req object contains a data property (alsopassed to the done callback) which is either a string (text mode) or a Uint8Array (binary mode)

Member error (also passed to the fail callback) will be set to the error description if an error occurredThe always callback if present is called in any case after a done or fail callback has been executedCheck thiserror in the always callback to know if an error occurred

Example

Load a custom telemetry object from a JSON file on SD cardvar telemetryVFSLoad(path sdmydatatelemetryjsondone function(data) telemetry = Duktapedec(jx data) process telemetry

fail function(error) print(Error loading telemetry + error)

)

bull req = VFSSave(cfg) Perform asynchronous file save

Pass the request parameters using the cfg object

ndash data the string or Uint8Array to save

ndash path full file path (missing directories will automatically be created)

ndash append optional flag true = append to the end of the file (also creating the file as necessary)

ndash done optional success callback function called with no arguments this pointing to the requestobject

ndash fail optional error callback function called with the error string as argument with this point-ing to the request object

ndash always optional final callback function no arguments this = request object

The cfg object is extended and returned by the API (req) It will remain stable at least until the requesthas finished and callbacks have been executed

68 Chapter 2 User Guide

Open Vehicles

Member error (also passed to the fail callback) will be set to the error description if an error occurredThe always callback if present is called in any case after a done or fail callback has been executedCheck thiserror in the always callback to know if an error occurred

Example

Save the above telemetry object in JSON format on SD cardVFSSave(

path sdmydatatelemetryjsondata Duktapeenc(jx telemetry)fail function(error)

print(Error saving telemetry + error)

)

Warning File IO especially saving can cause short freezes of the module

Minimize save frequency and if possible avoid saving while the vehicle is in operation (driving charging) byusing a check like

Saving to VFS may cause short blockings so only allow when vehicle is offfunction allowSave()

return OvmsMetricsValue(veon) ampamp OvmsMetricsValue(vccharging)

Note Saving to and loading from SD card

When storing plugin data on an SD card the plugin needs to take care of the SD card being mounted later in the bootprocess than the scripts are loaded Plugins additionally may need to take into account that the user may replace theSD card any time

When trying to save or load from an unmounted SD error will be set to volume not mounted If this happensduring plugin initialization the plugin should subscribe to the SD mount event to retry the loadsave as soon as the SDcard becomes available

Code scheme

var storeFile = sdusrhistorycborvar listen_sdmount = nullvar history =

function loadStoreFile() VFSLoad(path storeFilebinary truedone function(data)

print(storeFile + loadedn)history = CBORdecode(data)startRecording()

fail function(error)

print(storeFile + + thiserror + n)if (listen_sdmount ampamp thiserror == volume not mounted)

retry once after SD mountlisten_sdmount = PubSubsubscribe(sdmounted loadStoreFile)

else

(continues on next page)

217 Scripting 69

Open Vehicles

(continued from previous page)

startRecording()

)

function startRecording() if (listen_sdmount) PubSubunsubscribe(listen_sdmount)listen_sdmount = null

PubSubsubscribe(tickerEvent ticker) for example

if (storeFile) loadStoreFile()

else startRecording()

PubSub

The PubSub module provides access to a Publish-Subscribe framework In particular this framework is used to deliverevents to the persistent JavaScript framework in a high performance flexible manner An example script to print outthe ticker10 event is

var myTicker=function(msgdata) print(Event +msg+n)

PubSubsubscribe(ticker10myTicker)

The above example created a function myTicker in global context to print out the provided event name Then thePubSubsubscribe module method is used to subscribe to the ticker10 event and have it call myTickerevery ten seconds The result is ldquoEvent ticker10rdquo printed once every ten seconds

PubSub interprets events similar to MQTT as hierarchical topics with dots separating the levels It delivers the eventsin multiple passes with each new pass removing the last dotted part of the topic (ie bottom-up) so the most specificsubscriptions will be called first The handler is always called with the original eventtopic name So to eg catchall events vehiclecharge you can simply subscribe to vehiclecharge and inspect the actual eventname in your handler

PubSubsubscribe(vehiclecharge function (event) print(Got charging related event + event)

)

bull id = PubSubsubscribe(topic handler) Subscribe the function handler to messages of thegiven topic Note that types are not limited to OVMS events The method returns an id to be used tounsubscribe the handler

bull PubSubpublish(topic [data]) Publish a message of the given topic All subscribed handlers willbe called with the topic and data as arguments data can be any Javascript data

bull PubSubunsubscribe(id | handler | topic) Cancel a specific subscription all subscriptions ofa specific handler or all subscriptions to a topic

70 Chapter 2 User Guide

Open Vehicles

OvmsCommand

bull str = OvmsCommandExec(command) The OvmsCommand object exposes one method ldquoExecrdquo Thismethod is passed a single parameter as the command to be executed runs that command and then returnsthe textual output of the command as a string For example

print(OvmsCommandExec(boot status))Last boot was 14 second(s) ago

This is reset 0 since last power cycleDetected boot reason PowerOn (114)Crash counters 0 total 0 early

OvmsConfig

bull array = OvmsConfigParams() Returns the list of available configuration parameters

bull array = OvmsConfigInstances(param) Returns the list of instances for a specific parameter

bull string = OvmsConfigGet(paraminstancedefault) Returns the specified parame-terinstance value

bull object = OvmsConfigGetValues(param [prefix]) Gets all param instances matching theoptional prefix with their associated values If a prefix is given the returned property names will havethe prefix removed Note all values are returned as strings you need to convert them as needed

bull OvmsConfigSet(paraminstancevalue) Sets the specified parameterinstance value

bull OvmsConfigSetValues(param prefix object) Sets all properties of the given object asparam instances after adding the prefix Note non-string property values will be converted to their stringrepresentation

bull OvmsConfigDelete(paraminstance) Deletes the specified parameter instance

Beginning with firmware release 32009 a dedicated configuration parameter usr is provided for plugins Youcan add new config instances simply by setting them for example by OvmsConfigSet(usr mypluginlevel 123) or by the config set command

Read plugin configuration example

Set default configurationvar cfg = level 100 enabled no

Read user configurationObjectassign(cfg OvmsConfigGetValues(usr myplugin))

if (cfg[enabled] == yes) print(Im enabled at level + Number(cfg[level]))

Keep in mind to prefix all newly introduced instances by a unique plugin name so your plugin can nicely coexist withothers

OvmsEvents

This provides access to the OVMS event system While you may raise system events the primary use is to raisecustom events Sending custom events is a lightweight method to inform the web UI (or other plugins) about simplestate changes Use the prefix usr on custom event names to prevent conflicts with later framework additions

217 Scripting 71

Open Vehicles

Another use is the emulation of the setTimeout() and setInterval() browser methods by subscribing to adelayed event Pattern

function myTimeoutHandler() raise the timeout event again here to emulate setInterval()

PubSubsubscribe(usrmyplugintimeout myTimeoutHandler)

start timeoutOvmsEventsRaise(usrmyplugintimeout 1500)

bull OvmsEventsRaise(event [delay_ms]) Signal the event optionally with a delay (millisecondsmust be given as a number) Delays are handled by the event system the method call returns immediately

OvmsLocation

bull isatlocation = OvmsLocationStatus(location) Check if the vehicle is currently in a loca-tionrsquos geofence (pass the location name as defined) Returns true or false or undefined if thelocation name passed is not valid

Note to get the actual GPS coordinates simply read metrics vplatitude vplongitude and vpaltitude

OvmsMetrics

bull str = OvmsMetricsValue(metricname [decode]) Returns the typed value (default) or stringrepresentation (with decode = false) of the metric value

bull num = OvmsMetricsAsFloat(metricname) Returns the float representation of the metric value

bull str = OvmsMetricsAsJSON(metricname) Returns the JSON representation of the metric value

bull obj = OvmsMetricsGetValues([filter] [decode]) Returns an object of all metrics match-ing the optional name filtertemplate (see below) by default decoded into Javascript types (ie numericalvalues will be JS numbers arrays will be JS arrays etc) The object returned is a snapshot the valueswonrsquot be updated

The filter argument may be a string (for substring matching as with metrics list) an array of fullmetric names or an object of which the property names are used as the metric names to get The objectwonrsquot be changed by the call see Objectassign() for a simple way to merge objects Passing anobject is especially convenient if you already have an object to collect metrics data

The decode argument defaults to true pass false to retrieve the metrics string representations insteadof typed values

With the introduction of the OvmsMetricsGetValues() call you can get multiple metrics at once and let thesystem decode them for you Using this you can for example do

Get all metrics matching substring vbc (vehicle battery cell)var metrics = OvmsMetricsGetValues(vbc)print(Temperature of cell 3 + metrics[vbctemp][2] + degCn)print(Voltage of cell 7 + metrics[vbcvoltage][6] + Vn)

Get some specific metricsvar ovmsinfo = OvmsMetricsGetValues([mversion mhardware])JSONprint(ovmsinfo)

72 Chapter 2 User Guide

Open Vehicles

This obsoletes the old pattern of parsing a metricrsquos JSON representation using eval() JSONparse() orDuktapedec() you may still find in some plugins Example

var celltemps = eval(OvmsMetricsAsJSON(vbctemp))print(Temperature of cell 3 + celltemps[2] + degCn)

Warning Never use eval() on unsafe data eg user input eval() executes arbitrary Javascript so canbe exploited for code injection attacks

OvmsNotify

bull id = OvmsNotifyRaise(type subtype message) Send a notification of the given type andsubtype with message as contents Returns the message id allocated or 0 in case of failure Examples

send an info notification to the userOvmsNotifyRaise(info usrmypluginstatus Alive and kicking)

send a JSON stream to a web pluginOvmsNotifyRaise(stream usrmypluginupdate JSONformat(streamdatararr˓false))

send a CSV data record to a serverOvmsNotifyRaise(data usrmypluginrecord -MyStatus086400Alive)

OvmsVehicle

The OvmsVehicle object is the most comprehensive and exposes several methods to access the current vehicle Theseinclude

bull str = OvmsVehicleType() Return the type of the currently loaded vehicle module

bull success = OvmsVehicleWakeup() Wakeup the vehicle (return TRUE if successful)

bull success = OvmsVehicleHomelink(buttondurationms) Fire the given homelink button

bull success = OvmsVehicleClimateControl(onoff) Turn onoff climate control

bull success = OvmsVehicleLock(pin) Lock the vehicle

bull success = OvmsVehicleUnlock(pin) Unlock the vehicle

bull success = OvmsVehicleValet(pin) Activate valet mode

bull success = OvmsVehicleUnvalet(pin) Deactivate valet mode

bull success = OvmsVehicleSetChargeMode(mode) Set the charge mode (ldquostandardrdquo ldquostoragerdquo ldquorangerdquo ldquoperformancerdquo)

bull success = OvmsVehicleSetChargeCurrent(limit) Set the charge current limit (in amps)

bull success = OvmsVehicleSetChargeTimer(onoff start) Set the charge timer

bull success = OvmsVehicleStartCharge() Start the charge

bull success = OvmsVehicleStopCharge() Stop the charge

bull success = OvmsVehicleStartCooldown() Start a cooldown charge

bull success = OvmsVehicleStopCooldown() Stop the cooldown charge

217 Scripting 73

Open Vehicles

bull result = OvmsVehicleObdRequest(arguments) Perform OBDUDS request (synchronous)

Pass the request parameters using the arguments object

ndash txid the CAN ID to send the request to (or 0x7df for broadcast)

ndash rxid the CAN ID to expect the response at (or 0 for broadcast)

ndash request the request to send either a hex encoded string or an Uint8Array

ndash bus optional CAN bus device name default ldquocan1rdquo

ndash timeout optional timeout in milliseconds default 3000

ndash protocol optional protocol to use default 0 = ISOTP_STD ndash see vehicleh for other protocols

The result object will have these properties

ndash error 0 = no error else the error code with negative ranges being system errors positive codes areOBDUDS response error codes (NRCs)

ndash errordesc a human readable error description

ndash response only on success the binary response (Uint8Array)

ndash response_hex only on success hex encoded response (string)

Example

Establish diagnostic session with an ECUvar res = OvmsVehicleObdRequest( txid 0x765 rxid 0x7cf request 1003 rarr˓)if (reserror)print(reserrortext)

elseprint(resresponse_hex)

2178 Test Utilities

You can use the web UI editor and shell to edit upload and test script files If you need many test cycles a convenientalternative is to use shell scripts to automate the process

If yoursquove configured ssh public key authentication you can simply use scp to upload scripts and ssh to executecommands

binbash Upload amp execute a script file

FILE=testjsPATH=storescripts

OVMS_HOST=yourovmslocal

SCP=usrbinscp -qSSH=usrbinssh

Upload$SCP $FILE $OVMS_HOST$PATH$FILE

Execute$SSH $OVMS_HOST script run $FILE

74 Chapter 2 User Guide

Open Vehicles

Customize to your needs If you want to test a plugin simply replace the script run command by scriptreload followed by some script eval calls to your plugin API

Note this may be slow as the ssh session needs to be negotiated for every command

A faster option is using the OVMS HTTP REST API The following script uses curl to upload and execute a script

binbash Upload amp execute a script file

FILE=testjsPATH=storescripts

OVMS_HOST=httpyourovmslocalOVMS_USER=adminOVMS_PASS=yourpassword

CURL=usrbincurl -c auth -b authSED=usrbinsedDATE=usrbindate

Loginif [[ -e auth ]] then

AUTHAGE=$(($($DATE +s) - $($DATE +s -r auth)))else

AUTHAGE=3600fiif [[ $AUTHAGE -ge 3600 ]] thenRES=$($CURL $OVMS_HOSTlogin --data-urlencode username=$OVMS_USER --data-

rarr˓urlencode password=$OVMS_PASS 2gtdevnull)if [[ $RES =~ Error ]] thenecho -n LOGIN ERROR echo $RES | $SED -e sltligt([^lt])1grm authexit 1

fifi

UploadRES=$($CURL $OVMS_HOSTedit --data-urlencode path=$PATH$FILE --data-rarr˓urlencode content$FILE 2gtdevnull)if [[ $RES =~ Error ]] thenecho -n UPLOAD ERROR echo $RES | $SED -e sltligt([^lt])1grm authexit 1

fi

Execute$CURL $OVMS_HOSTapiexecute --data-urlencode command=script run $FILE

217 Scripting 75

Open Vehicles

218 Factory Reset

2181 Module Configuration

A standard factory reset erases the configuration store After a factory reset you will be able to access the USBconsole with an empty module password and the ldquoOVMSrdquo wifi access point with the initial password ldquoOVMSinitrdquo Werecommend using the setup wizard to configure the module or restoring a configuration backup as soon as possible1as the module is accessible by anyone knowing the initial password

The standard factory reset does not revert OTA firmware installs See below for methods to switch back to andoptionally replace the factory firmware

Method 1 Command

If you have console command access a factory reset can be accomplished with this command

OVMS module factory resetReset configuration store to factory defaults and lose all configuration data (yn)rarr˓yStore partition is at 00c10000 size 00100000Unmounting configuration storeErasing 1048576 bytes of flashFactory reset of configuration store complete and reboot now

That command will erase all configuration store and reboot to an empty configuration

Note to issue this command from the web shell or a remote shell (App Server ) you need to skip the confirmationstep by adding the option -noconfirm ie

OVMS module factory reset -noconfirm

Method 2 SD card

If you donrsquot have console access you can perform a factory reset by placing an empty file named factoryresettxt in the root directory of an SD card and insert that SD into the (running) module The file will be deleted and themodule will reboot within about 30 seconds

Method 3 Switch S2

You can also open the module case remove any SD card (important) power on the module wait 10 seconds thenpush and hold switch ldquoS2rdquo for 10 seconds ldquoS2rdquo is located here

1 Wait for the SSH key generation to finish after reboot before attempting to restore the backup Trying to run both processes concurrently maycrash the module Key generation takes about 2 minutes look for log message ldquoSSH server key installedrdquo

76 Chapter 2 User Guide

Open Vehicles

Method 4 USB

If you donrsquot have console access and donrsquot have an SD card you can perform a factory reset from a PC via USB usingthe esptoolpy tool from the Espressif ESP-IDF toolkit (see below for installation)

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 erase_region 0xC10000 0x100000

Note the port needs to be changed to the one assigned by your system ie devttyUSB0 on a Linux system orCOMx on Windows After using esptoolpy to manually erase the config region you should go into the console and dothe module factory reset step to properly factory reset

Note Methods 1 2 and 3 need a running system ie will not work if your module cannot boot normally In this casefirst try method 4 If that doesnrsquot help also switch back to the factory firmware as shown below

2182 Module Factory Firmware

You can switch back to factory firmware with this command

OVMS ota boot factoryBoot from factory at 0x00010000 (size 0x00400000)

Or without console access (lost module password) using the esptoolpy from the Espressif ESP-IDF toolkit

218 Factory Reset 77

Open Vehicles

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 erase_region 0xd000 0x2000

Note the device needs to be changed to the one assigned by your system ie devttyUSB0 on a Linux system orCOMx on Windows

2183 Flash Factory Firmware via USB

esptoolpy can also be used to flash a new factory firmware Download the firmware file ovms3bin you wantto flash then issue

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 --before default_reset --after hard_reset write_flash --compress --flash_mode dio --flash_freq 40m --flash_size detect 0x10000 ovms3bin

Note if you were running an OTA partition before you also need to switch back to the factory partition as shownabove

2184 Full Reflash via USB

If you accidentally did an erase_flash or erased the wrong region you will need to do a full reflash of your module(including the boot loader and partitioning scheme)

The need for a full reflash will typically show by the USB output of the module boot being just something like

rst0x10 (RTCWDT_RTC_RESET)boot0x3f (SPI_FAST_FLASH_BOOT)flash read err 1000ets_mainc 371ets Jun 8 2016 002257

To do a full reflash download the three bin files from the release you want to flash eg from

httpsovmsdexters-webdefirmwareotav32edge

Then issue

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 --before default_reset --after hard_reset write_flash --compress --flash_mode dio --flash_freq 40m --flash_size detect 0x1000 bootloaderbin 0x10000 ovms3bin 0x8000 partitionsbin

replacing the port and file paths accordingly for your system

If this fails open a support ticket on httpswwwopenvehiclescom and attach a log of the boot process or install thedeveloper environment and do a make flash

2185 Installing esptoolpy

The esptoolpy package and installation instructions can be found here

httpsgithubcomespressifesptool

78 Chapter 2 User Guide

Open Vehicles

The package normally can be installed without manual download using the python package manager ldquopiprdquo ie onUnixLinux

sudo pip install esptool

Warning You can brick your module using the esptool Only use the commands shown above

219 OBDII ECU

2191 Purpose

The OBDII interface is a connector electrical specification and protocol used for viewing the operation and statusof a car It is mandated in all light duty vehicles sold in North America beginning in 1996 and while the focus ofthe information it provides is for monitoring the emissions of Internal Combustion Engines it has proven to be ahandy port for connecting a variety of aftermarket displays and monitors to a car Electric Vehicles have no need foremissions monitoring so often omit the port from the car thus making the these aftermarket devices incompatibleThe OBDII ECU capability of the OVMS v3 is used to create a simulated OBDII port which can be used to attachmany of these aftermarket devices to the car

2192 Cabling

The cable and OBDII connector are not provided with the OVMSv3 module and can be built using the diagram belowAlternatively you can purchase the OVMS V3 HUD OBD II-F Cable from FastTech

DA26 OBDII Female Signal name6 14 CAN3-L16 6 CAN3-H8 4 amp 5 Chassis amp Signal Ground18 16 +12v switched output to HUDdongle

NB Also place a 120 ohm resistor between OBDII pins 14 amp 6 for bus termination

2193 Setup

From the Web Interface check the ldquoStart OBD2ECUrdquo box and select CAN3 from the dropdown menu (if using thewiring diagram above) This will enable the OBDII ECU Task to run the next time the OVMSv3 module is poweredon or reset Also check the ldquoPower on external 12Vrdquo box in order to feed 12v power through to the device Click onSave at the bottom of the page

From the command line the following commands are available

obdii ecu start can3 Starts the OBDII ECU taskobdii ecu stop Stops the OBDII ECU taskobdii ecu list Displays the parameters being served and their current valueobdii ecu reload Reloads the map of parameters after a config change

power ext12v on Turns on power feed to the devicepower ext12v off Turns off power feed to the device

219 OBDII ECU 79

Open Vehicles

2194 Operation

During operation an OBDII device for example a Head-Up Display (HUD) or OBDII Diagnostic module will makeperiodic requests usually a few times per second for a set of parameters The OVMSv3 module will reply to thoseparameters with the metric if configured to do so on an individual basis These parameters can be common itemssuch as vehicle speed engine RPM and engine coolant temperature but because of the differences between ICE andEV vehicles many of the parameters do not have equivalent values in an EV Speed and engine (motor) RPM can bedirectly mapped but there is typically no ldquoengine coolantrdquo That parameter (in fact most parameters) can be mappedto some other value of interest For example the Engine Coolant display on the HUD can be configured to displaymotor or battery temperature instead Engine Load (PID 4 a percentage value) is mapped by default to battery Stateof Charge (also a percentage) However note that not all vehicle metrics may be supported by all vehicles

Parameters requested by the OBDII device are referred to by ldquoPID valuerdquo Note that each PID has a specific range ofallowed values and that it is not possible to directly represent values outside that range For example PID 5 (Enginecoolant temperature) has a range of -40 to +215 it would not be possible to map the full range of motor RPMs to thisparameter Values outside the allowed range are limited to the range boundary value The complete table of possibleparameters are described here httpsenwikipediaorgwikiOBD-II_PIDsMode_01

Vehicle metrics are referred to by name See the table in Appendix 1 for a list of available metrics which vehiclesreport them and which of those are of a format that can be mapped by the OBDII ECU task

2195 Defaults and customization

By default the following mapping of PID value to OVMSv3 metric is used

PID (Dec) PID (Hex) Requested Parameter Mapped Metric Value Metric Name4 0x04 Engine Load Battery SOC vbsoc5 0x05 Coolant Temp Motor Temp vmtemp12 0x0c Motor RPM Motor RPM vmrpm13 0x0d Vehicle Speed Vehicle Speed vpspeed16 0x10 MAF Air Flow 12v Battery vb12vvoltage

The OBDII ECU task supports the remapping and reporting of PIDs 4-18 31 33 47 and 51 (all decimal) PIDs 0and 32 are used by the OBDII protocol for management and not available for assignment Other PIDs return zero

PIDs requested for which no mapping has been established are ignored by the OBDII ECU task As an aid for discov-ering which PIDs are being requested the configuration parameter lsquoautocreatersquo may be used to populate entries intothe obdii ecu list display (lsquoconfig set obd2ecu autocreate yesrsquo) Such autocreated entries are marked as ldquoUnimple-mentedrdquo and return zero to the device They are not added to the configured (saved) obd2ecumap and get cleared ateach boot or reset They may be mapped to a supported metric if desired using

config set obd2ecumap ltPIDgt ltmetric namegt

Example

OVMS config set obd2ecumap 5 vbtemp(map battery temp to engine coolant temp)

OVMS vfs edit storeobd2ecu10(script for fuel pressure PID see below)

OVMS obdii ecu reloadOBDII ECU pid map reloaded

(continues on next page)

80 Chapter 2 User Guide

Open Vehicles

(continued from previous page)

OVMS obdii ecu list

PID Type Value Metric0 (0x00) internal 00000004 (0x04) internal 95000000 vbsoc5 (0x05) metric 16000000 vbtemp10 (0x0a) script 000000011 (0x0b) unimplemented 000000012 (0x0c) internal 0000000 vmrpm13 (0x0d) internal 0000000 vpspeed16 (0x10) internal 13708791 vb12vvoltage32 (0x20) internal 0000000

Types ldquointernalrdquo means default internal handling of the PID ldquometricrdquo means a user-set mapping of PID to thenamed metric ldquounimplementedrdquo are PIDs requested by the device but for which no map has been set ldquoscriptrdquomeans the user has configured a script to handle the PID

2196 Special handling

Several PIDs are handled specially by the OBDII ECU task

bull PIDs 0 and 32 are bit masks that indicate what other PIDs are being reported by the OBDII ECU task These aremaintained internally based on the default mapped and scripted PID table Note that some OBDII devices usePID 0 as a test for ECU presence and operating mode (standard or extended) and ignore the returned valuesThe OBDII ECU task supports both modes

bull PID 12 Engine RPM is often monitored by the OBDII device to detect when the car is turned off Since anEVrsquos motor is not rotating when the car is stopped a HUD may decide to power down when it sees the RPMdrop below a particular value or if there is no variation (jitter) in its value To prevent this the OBDII ECU taskwill source a fake value of 500 rpm plus a small periodic variation if the car is not moving (vehicle speed isless than 1) To actually let the device turn off see ldquoExternal Power Controlrdquo below

bull PID 16 MAF Air Flow is commonly used by OBDII devices to display fuel flow by measuring the amount ofair entering the engine in support of combustion Since this is irrelevant to an EV the OBDII ECU task mapsthis metric to a simple integer Most HUDs displays limit this to a range of 0-199 literhr which is acceptable todisplay the +12v battery voltage Since the conversion factors are complicated this value is at best approximatein spite of its implied precision

bull Mode 9 PID 2 VIN is used to report the carrsquos DMV VIN to the attached OBDII device Since the rest ofthe parameters reported by the OBDII ECU task are simulated and some OBDII devices may use the VIN fortracking purposes the reporting of the VIN may be turned off by setting the privacy flag to ldquoyesrdquo The commandis lsquoconfig set obd2ecu privacy yesrsquo Setting it to lsquonorsquo which is the default allows the reporting of the VIN

bull Mode 9 PID 10 ECU Name is statically mapped to report the OVMSv3rsquos Vehicle ID field (vehicle name notVIN) This string may be customized to any printable string of up to 20 characters if not used with the OVMSv2 or v3 mobile phone applications (lsquoconfig set vehicle id car_namersquo)

2197 Metric Scripts

Should one desire to return a value not directly available by a single named metric it is possible to map a PID to a shortscript where combinations of metrics constants etc may be used to create a custom value Note that the restrictionson PID value ranges still applies Also note that the special handling for PID 12 (engine RPM) is not applied in theOBDII ECU task so it must be included in the script if driving a HUD

219 OBDII ECU 81

Open Vehicles

Scripts should be placed in the directory storeobd2ecuPID where PID is the decimal value of the PID to be pro-cessed Example for creating a ldquokw per kmrdquo sort of metric

ret1=OvmsMetricsAsFloat(vpspeed)ret2=OvmsMetricsAsFloat(vbpower)out=00if (ret1 gt 0) out=ret2ret1 out

Put this text in a file storeobd2ecu4 to map it to the ldquoEngine Loadrdquo PID See ldquoSimple Editorrdquo chapter for file editingor use lsquovfs appendrsquo commands (tedious) Note however that Vehicle Power (vbpower) is not supported on all cars(which is why this is not the default mapping for this PID)

Warning The error handling of the scripting engine is very rough at this writing and will typically cause a full modulereboot if anything goes wrong in a script

2198 External Power Control

Since the OVMSv3 module remains powered at all times and the normal means for deducing that a car has beenturned off donrsquot work on an EV (see PID 12 above) an external OBDII device needs to be explicitly turned on andoff This is currently done with short event scripts The following commands configure the OVMSv3 to make theexternal 12v feed follow the vehicle onoff state or use the vfs edit command to create or modify the files

vfs mkdir storeeventsvfs mkdir storeeventsvehicleonvfs mkdir storeeventsvehicleoff

vfs append power ext12v on storeeventsvehicleonext12vvfs append power ext12v off storeeventsvehicleoffext12v

220 EGPIO

2201 Hardware

The OVMS has 10 general purpose IO ports provided by a MAX7317 IO expander

The MAX7317 ports can be individually configured as either an open-drain output or an overvoltage-protected Schmittinput Being open-drain you need to add pull-up resistors for input and output switch uses to get a defined high level(eg 10K to 33V) See the datasheet for details on maximum current amp voltage ratings

Depending on your hardware configuration up to 4 ports may be used by the module 6 are generally free to use

Port Signal(s) ExpPin Default usage0 MDM_EN 15 Modem enable1 SW_CTL ndash Ext12V control (SW_12V)2 CAN1_EN + EIO_1 17 CAN1 transceiver enable3 MDM_DTR + EIO_2 19 Modem sleep control4 EIO_3 21 -free-5 EIO_4 20 -free-6 EIO_5 18 -free-7 EIO_6 16 -free-8 EIO_7 14 -free-9 EIO_8 12 -free-

82 Chapter 2 User Guide

Open Vehicles

SW_CTL (port 1) controls a BTS452R power switch which could deliver a nominal output of 25W or 18A and up to40W or 29A short term at the SW_12V pin but the main fuse of the module (located at the corner near the DB9 plug)limits the 12V current total sum of the board plus any external hardware to continuous 075A on a revision 31 boardand 10A on a revision 32 board The unswitched EXT_12V pin is also behind the fuse

The module including modem needs a 12V current share of ~80mA in full operation Calculate with 100mA to beon the safe side That leaves continuous 065A on a revision 31 board and 09A on a revision 32 board for externaldevices and addons powered by the module The fuse has a little headroom but donrsquot rely on that

SW_12V is meant to power auxiliary devices from the OVMS for example head-up displays Of course you can aswell power a standard 12V automotive relay or fan directly from this without additional hardware

The EGPIO (EIO) ports are not connected directly to the DA26 connector but are available atthe internal expansion port To route an EGPIO port to the DA26 connector connect it to oneof the GEP_17 lines at the expansion port either directly or via some additional driver

Fig 1 Expansion Port (Prototype PCB)Fig 2 DA26 Connector

Example to route EIO_8 (port 9) to GEP_7 (pin 21 on the DA26) seta jumper on pins 10+12 on the expansion port

2202 Commands

EGPIO control is provided by the egpio command set

bull egpio output ltportgt ltlevelgt [ltportgt ltlevelgt] ndash set output level(s)

bull egpio input ltportgt [ltportgt ] ndash query inputlevel(s)

bull egpio status ndash show output input amp monitor status

bull egpio monitor lton|offgt [ports] ndash enabledisablemonitoring

bull egpio monitor status ndash show current monitoring status

220 EGPIO 83

Open Vehicles

To configure a port for input it needs to be switched to output levelhigh (1) That is done automatically by the input and monitor com-mands

If you set multiple outputs the ports will be set one at a time so outputlevels will change with a slight delay You can use this behaviour to setdata lines before a clock line eg when sending bits serially into a shiftregister

Note The MAX7317 needs active polling to detect input state changes Monitoring is disabled by default it can beenabled manually or configured to start automatically on module init Without monitoring only manual input querieswill update the input state trigger input events and input metric updates

2203 Configuration

Parameter Instance Descriptionauto egpio yes = Start monitoring on boot (default no)egpio monitorports List of ports to monitor by default (space separated)egpio monitorinterval Polling interval in milliseconds (min 10 default 50)

The default interval of 50 ms (= 20 Hz) means an input signal needs to be at least 50 ms long to be detected Thispolling frequency produces a CPU load of ~05 on core 1 and is normally sufficient to detect even very short buttonpushes

2204 Metrics

Metric name Example value Descriptionmegpioinput 012345679 EGPIO input port state (ports 0 9 present=high)megpiomonitor 89 EGPIO input monitoring portsmegpiooutput 45679 EGPIO output port state

Hint to process these metrics from Javascript read them into an array using eval() and test for the presence of aport number using eg the includes() method in a browser plugin Duktape does not support includes() youcan test indexOf(port) instead

Example

var input = eval(OvmsMetricsAsJSON(megpioinput))if (inputindexOf(9) lt 0)

print(Input port 9 (EIO8) is currently lown)

2205 Events

Event Data Purposeegpioinputltportgtltstategt ndash EGPIO input port change (port=0 9 state=highlow)egpiooutputltportgtltstategt ndash EGPIO output port change (port=0 9 state=highlow)

84 Chapter 2 User Guide

Open Vehicles

Hint to listen to events from Javascript bind to msgevent on a receiver object from browser context or usePubSub from module context

Example

PubSubsubscribe(egpioinput9low function()print(Input port 9 (EIO8) is now lown)

)

221 TPMS

OVMS v3 includes a capability to read and write sets of TPMS wheel sensors IDs from the vehicle TPMS ECU andstore in your configuration Support for this is vehicle-specific and may require optional hardware boards so pleasefollow your individual vehicle guides for further information

The command to read the current TPMS wheel sensor IDs from the car is

OVMS tpms read SET

(replace SET with your own identifier for this set of wheels such as lsquosummerrsquo lsquowinterrsquo etc)

You can check the stored wheel sensor ID sets with

OVMS tpms list

If you change wheels you can write the new wheel IDs to the TPMS ECU in the car with

OVMS tpms write SET

(replace SET with your own identifier for this set of wheels such as lsquosummerrsquo lsquowinterrsquo etc)

Note that in most cases the car must be switched on for the above commands to work Please refer to your vehiclespecific user guide for more information on this

Note also that OVMS doesnrsquot have any radio capable of receiving TPMS signals and cannot read the IDs from thewheel sensors themselves OVMS can only read the IDs from the TPMS ECU in the car itself You can howeverdrop by pretty much any garage (or use any of a large number of TPMS tools) to trigger and read these IDs from thewheels Once your garage gives you the sensor IDs (each expressed as an 8 character hexadecimal ID) you can enterthem into OVMS as

OVMS tpms set SET ID1 ID2 ID3 ID4 (replace SET with your own identifier for this set of wheelsand ID1 with the hexadecimal sensor ID)

222 Optional K-Line Expansion Board

The optional K-Line Expansion Board is available to extend the capabilities of the OVMS system It can be used totalk to vehicle ECUs using K-Line communication standards

221 TPMS 85

Open Vehicles

There are two installation options

1 If you are using a modem module you install the K-Line Expansion Board on top of the modem Unscrew thefour black screws holding the modem in place In your K-Line expansion board kit you will find four brassstand offs with holes at one end and small bolts at the other Use these to screw down the modem Now orientthe K-line Expansion Board so the top left corner (marked with a white triangle) matches the white triangle onthe modem board Carefully push the K-Line Expansion Board into place (making sure that the pins align andare not bent) Once done the four black screws can be used to secure it in place

2 If you are not using a modem module you install the K-Line Expansion Board directly onto the main OVMSboard Screw the provided standoffs into the main board and Carefully attach the provided pin headers intothe main OVMS board Now orient the K-line Expansion Board so the top left corner (marked with a whitetriangle) matches the white triangle on the main OVMS board Carefully push the K-Line Expansion Board intoplace (making sure that the pins align and are not bent) Once done the four black screws can be used to secureit in place

86 Chapter 2 User Guide

Open Vehicles

Next the K-Line expansion board will need to be configured to match your vehiclersquos K-Line bus and ECU hardwarerequirements Refer to your vehicle specific guide for information on what your vehicle requires

bull S1 is used to turn onoff the extra lsquomasterrsquo mode components For most vehicles this should be OFF

bull SW1 is used to select the power source for the K-Line bus It can be 0 (no power connected) 1 (5v powerfrom USB bus) 2 (5v power converted from vehiclersquos 12v power) or 3 (12v power direct from the vehicle)For most vehicles either 2 or 3 is used

The K-Line bus from the vehicle is connected via a vehicle specific cable This connection is usually to pin 1 on theDB9 connector On OVMS modules v32 and later (as well as v31 boards labelled on board as July 2018 or later)this is internally connected to GEP7 (General Expansion Pin 7) This is necessary to bring the K-Line bus up to theinternal expansion pins (for the K-Line Expansion Board to be able to reach it)

If you have an earlier board there is a relatively simply wiring modification that can be made to upgrade to this

1 You will need a soldering iron solder and a small length of insulated wire

2 Pin 1 on the DB9 connector is the K-Line pin from the vehicle

3 Pin 21 on the DA26 connector is GEP 7 (which is also connected to a pin on internal expansion connector)

4 On the underside of the board you can solder a jumper wire between DB9 pin 1 and DA26 pin 21 to makethis connection

Please refer to the vehicle specific guides for further information on this

222 Optional K-Line Expansion Board 87

Open Vehicles

88 Chapter 2 User Guide

CHAPTER 3

Plugins

The OVMS can easily be extended by plugins Plugins may consist of any combination of module scripts (Javascript)and web UI extensions (HTML)

Installation currently needs to be done manually but is simple See below and the plugin documentation on specificsteps and on how to use the plugin functions A plugin store with simplified download and optional automatic updatingwill be provided in the future

This page is intended as an overview of all plugins currently available in the OVMS repository If yoursquore a plugindeveloper and want to add your plugin here please submit a pull request containing your plugin directory Organizeyour files and include a READMErst as shown here

31 ABRP abetterrouteplannercom

Send live data to abetterrouteplannercom

Overview

abetterrouteplanner is probably the best website to plan a route with an EV and optimize the number of stops neededand where to charge your vehicle

Moreover it has a wonderful functionality to update your plan taking into account your live data to adjust withthe real consumption of the vehicle by connecting an obd device and soft like EVNotify or Torque Pro

This plugin sends your live data from the OVMS box

Author David S Arnold

New in version 12 Your own parameters (car model abrp token but also api-url) are now stored as config param-eters you can consult them using the shell with config list usr or modify with config set command

89

Open Vehicles

Contents

bull ABRP abetterrouteplannercom

ndash Installation

ndash Script code

ndash Usage

311 Installation

You can use the embedded website toolsshell and toolseditor of the OVMS box to create the directory and file Thiseditor will allow you to paste the plugin code from the documentation

Files to be created in storescripts

bull ovmsmainjs if not already exists

bull sendlivedata2abrpjs by copying the file below

Next configure your car model API URL amp token

Note ABRP only supports live data feeds for some car models You can request a notification when support has beenadded for your car Do not feed live data using other car models Also ABRP has not yet added this OVMS pluginas a general data source so you need to disguise as ldquoTorquerdquo

If using the ABRP 4 UI

bull Login to abetterrouteplanner

bull Open ldquoSettingsrdquo enable detailed setup

bull Add your car (if ABRP has no live support for your car model it will display ldquoLive data not availablerdquo)

bull Click ldquoLink Torquerdquo click ldquoNextrdquo 3 times

bull Set the ldquoWebserver URLrdquo by config set usr abrpurl Note according to Iterniothe URL httpapiiterniocom1tlmsend should generally be used here instead of theTorque specific one displayed

bull Set the ldquoUser Email Addressrdquo (API token) by config set usr abrpuser_token

If using ABRP classic UI

bull Login to abetterrouteplanner in classic view

bull In Settingsmore Settings therersquos an item lsquoLive Car Connectionrsquo with 2 buttons lsquoSetuprsquo and lsquoView livedatarsquo

bull Click on Setup (if there is no Setup button live data support isnrsquot available for your car model)

bull Click on Torque

bull Set the ldquoWebserver URLrdquo by config set usr abrpurl

bull Set the ldquoUser Email Addressrdquo (API token) by config set usr abrpuser_token

Determine your car model code

bull Open API car models list

90 Chapter 3 Plugins

Open Vehicles

bull To improve readability optionally paste the page into JSONlintcom

bull Search for your car brand and model the code is the field following the car specification for examplerenaultzoe2052r110

bull Set the code by config set usr abrpcar_model

Finally reboot your OVMS module This was a one-time configuration

Yoursquore now ready Test it with the shell page in the embedded web server using the command script eval abrpinfo() and then with the command script eval abrponetime() You can also do it with the mobile app

312 Script code

This is a javascript code to extract in the file sendlivedata2abrpjs

Warning note the minimum firmware version 32008-147

1 2 storescriptssendlivedata2abrpjs3 4 Module plugin5 Send live data to a better route planner6 This version uses the embedded GSM of OVMS so theres an impact on data

rarr˓consumption7 requires OVMS firmware version 32008-147 minimum (for HTTP call)8 9 Version 13 2020 inf0mike (forum httpswwwopenvehiclescom)

10 11 Enable12 - install at above path13 - add to storescriptsovmsmainjs14 abrp = require(sendlivedata2abrp)15 - script reload16 17 Usage18 - script eval abrpinfo() =gt to display vehicle data to be sent to abrp19 - script eval abrponetime() =gt to launch one time the request to abrp server20 - script eval abrpsend(1) =gt toggle send data to abrp21 - (0) =gt stop sending data22 - script eval abrpresetConfig() =gt reset configuration to defaults23 24 Version 13 updates25 - Fix for rounding of fractional SOC causing abrp to report SOC off by 126 - Fix for altitude never being sent27 - New convenience method to reset config to defaults28 29 Version 12 updates30 - based now on OVMS configuration to store user token car model and url31 - review messages sent during charge32 - send a message when vehicle is on before moving to update abrp33 34 Version 11 fix and update35 - fixed the utc refreshing issue36 - send notifications37 - send live data only if necessary

(continues on next page)

31 ABRP abetterrouteplannercom 91

Open Vehicles

(continued from previous page)

38 39

40

41

42 43 Declarations44 CAR_MODEL find your car model here httpsapiiterniocom1tlmget_carmodels_

rarr˓listapi_key=32b2162f-9599-4647-8139-66e9f952837045 OVMS_API_KEY API_KEY to access to ABRP API given by the developer46 MY_TOKEN Your token (corresponding to your abrp profile)47 TIMER_INTERVAL to subscribe to a ticker event48 URL url to send telemetry to abrp following httpsiterniocomindexphp

rarr˓iternio-telemetry-api49 CR Carriage Return for console prints50 51 objTLM JSON object containing data read52 objTimer timer object53 54

55 const CAR_MODEL = 56 const OVMS_API_KEY = 32b2162f-9599-4647-8139-66e9f952837057 const MY_TOKEN = ----58 const TIMER_INTERVAL = ticker60 every minute59 const EVENT_MOTORS_ON = vehicleon60 const URL = httpapiiterniocom1tlmsend61

62 const DEFAULT_CFG = 63 url URL64 user_token MY_TOKEN65 car_model CAR_MODEL66 67

68 const CR = n69

70 var objTLM71 var objTimer objEvent72 var sHasChanged = 73 var bMotorsOn = false74

75 initialise from default76 var abrp_cfg = JSONparse(JSONstringify(DEFAULT_CFG))77

78 check if json object is empty79 function isJsonEmpty(obj) 80 for(var key in obj) 81 if(objhasOwnProperty(key))82 return false83 84 return true85 86

87 Read amp process config88 function readConfig() 89 check if config exist90 var read_cfg = OvmsConfigGetValues(usr abrp)91 print(JSONstringify(read_cfg) + CR)92 if (isJsonEmpty(read_cfg) == true)

(continues on next page)

92 Chapter 3 Plugins

Open Vehicles

(continued from previous page)

93 no config yet set the default values94 OvmsConfigSetValues(usrabrpabrp_cfg)95 else 96 config existing97 abrp_cfgurl = read_cfgurl98 abrp_cfguser_token = read_cfguser_token99 abrp_cfgcar_model = read_cfgcar_model

100 101 102

103 Make json telemetry object104 function InitTelemetryObj() 105 return 106 utc 0107 soc 0108 soh 0109 speed 0110 car_model abrp_cfgcar_model111 lat 0112 lon 0113 alt 0114 ext_temp 0115 is_charging 0116 batt_temp 0117 voltage 0118 current 0119 power 0120 121 122

123 Fill json telemetry object124 function UpdateTelemetryObj(myJSON) 125 if(myJSON)126 if the data object is undefined or null then return early127 return false128 129 var read_num = 0130 var read_str = 131 var read_bool = false132

133 sHasChanged = 134

135 if (bMotorsOn) 136 sHasChanged = _MOTORS-ON137 bMotorsOn = false138 139

140 using Mathfloor avoids rounding up of 5 values to next whole number141 as some vehicles report fractional values Abrp seems to only support integer

rarr˓values142 read_num = Mathfloor(Number(OvmsMetricsValue(vbsoc)))143 if (myJSONsoc = read_num) 144 myJSONsoc = read_num145 sHasChanged += _SOC + myJSONsoc + 146 147

148 read_num = Number(OvmsMetricsValue(vbsoh))(continues on next page)

31 ABRP abetterrouteplannercom 93

Open Vehicles

(continued from previous page)

149 if (myJSONsoh = read_num) 150 myJSONsoh = read_num151 sHasChanged += _SOH + myJSONsoh + 152 153

154 if ( (myJSONsoh + myJSONsoc) == 0 ) 155 Sometimes the canbus is not readable and abrp doesnt like 0 values156 print(canbus not readable reset module and then put motors on + CR)157 return false158 159

160 myJSONlat = OvmsMetricsAsFloat(vplatitude)toFixed(3)161 above code line works except when value is undefined after reboot162

163 read_num = OvmsMetricsAsFloat(vplatitude)164 read_num = read_numtoFixed(3)165 if (myJSONlat = read_num) 166 myJSONlat = read_num167 sHasChanged += _LAT + myJSONlat + deg168 169

170 read_num = Number(OvmsMetricsAsFloat(vplongitude))171 read_num = read_numtoFixed(3)172 if (myJSONlon = read_num) 173 myJSONlon = read_num174 sHasChanged += _LON + myJSONlon + deg175 176

177 read_num = Number(OvmsMetricsAsFloat(vpaltitude))178 read_num = read_numtoFixed(1)179 if (read_num lt= (myJSONalt - 2) || read_num gt= (myJSONalt + 2)) 180 myJSONalt = read_num181 sHasChanged += _ALT + myJSONalt + m182 183

184 read_num = Number(OvmsMetricsValue(vbpower))185 myJSONpower = read_numtoFixed(1)186

187 myJSONspeed=Number(OvmsMetricsValue(vpspeed))188 myJSONbatt_temp=Number(OvmsMetricsValue(vbtemp))189 myJSONext_temp=Number(OvmsMetricsValue(vetemp))190 myJSONvoltage=Number(OvmsMetricsValue(vbvoltage))191 myJSONcurrent=Number(OvmsMetricsValue(vbcurrent))192

193 myJSONutc = Mathtrunc(Datenow()1000)194 myJSONutc = OvmsMetricsValue(mtimeutc)195

196 read_bool = Boolean(OvmsMetricsValue(vccharging))197 vccharging is also on when regen =gt not wanted here198 read_str = OvmsMetricsValue(vcstate)199 if ( (read_str == charging) || (read_str == topoff) ) 200 myJSONis_charging = 1201 read_str = OvmsMetricsValue(vcmode)202 if (sHasChanged = ) 203 sHasChanged += _CHRG + read_str + ( + OvmsMetricsValue(vccharging)

rarr˓+ )204 print(Charging in mode + read_str + CR)

(continues on next page)

94 Chapter 3 Plugins

Open Vehicles

(continued from previous page)

205 206 else 207 myJSONis_charging = 0208 209

210 myJSONcar_model = abrp_cfgcar_model211

212 return (sHasChanged == )213 214

215 Show available vehicle data216 function DisplayLiveData(myJSON) 217 var newcontent = 218 newcontent += altitude = + myJSONalt + m + CR GPS altitude219 newcontent += latitude = + myJSONlat + deg + CR GPS latitude220 newcontent += longitude= + myJSONlon + deg + CR GPS longitude221 newcontent += ext temp = + myJSONext_temp + degC + CR Ambient

rarr˓temperature222 newcontent += charge = + myJSONsoc + + CR State of charge223 newcontent += health = + myJSONsoh + + CR State of health224 newcontent += bat temp = + myJSONbatt_temp + degC + CR Main battery

rarr˓momentary temperature225 newcontent += voltage = + myJSONvoltage + V + CR Main battery

rarr˓momentary voltage226 newcontent += current = + myJSONcurrent + A + CR Main battery

rarr˓momentary current227 newcontent += power = + myJSONpower + kW + CR Main battery

rarr˓momentary power228 newcontent += charging = + myJSONis_charging + CR yes = currently

rarr˓charging229 print(newcontent)230 231

232 function InitTelemetry() 233 objTLM = InitTelemetryObj()234 sHasChanged = 235 236

237 function UpdateTelemetry() 238 var bChanged = UpdateTelemetryObj(objTLM)239 if (bChanged) DisplayLiveData(objTLM) 240 return bChanged241 242

243 function CloseTelemetry() 244 objTLM = null245 sHasChanged = 246 247

248 http request callback if successful249 function OnRequestDone(resp) 250 print(response=+JSONstringify(resp)+CR)251 OvmsNotifyRaise(info usrabrpstatus ABRP + sHasChanged)252 253

254 http request callback if failed255 function OnRequestFail(error)

(continues on next page)

31 ABRP abetterrouteplannercom 95

Open Vehicles

(continued from previous page)

256 print(error=+JSONstringify(error)+CR)257 OvmsNotifyRaise(info usrabrpstatus ABRP + JSONstringify(error))258 259

260 Return full url with JSON telemetry object261 function GetUrlABRP() 262 var urljson = abrp_cfgurl263 urljson += 264 urljson += api_key= + OVMS_API_KEY265 urljson += amp266 urljson += token= + abrp_cfguser_token267 urljson += amp268 urljson += tlm= + encodeURIComponent(JSONstringify(objTLM))269 print(urljson + CR)270 return urljson271 272

273 Return config object for HTTP request274 function GetURLcfg() 275 var cfg = 276 url GetUrlABRP()277 done function(resp) OnRequestDone(resp)278 fail function(err) OnRequestFail(err)279 280 return cfg281 282

283 function SendLiveData() 284 if (UpdateTelemetry()) 285 HTTPRequest( GetURLcfg() )286 287 288

289 function Reactivate_MotorsOn() 290 bMotorsOn = true291 SendLiveData()292 293

294 function InitTimer() 295 objTimer = PubSubsubscribe(TIMER_INTERVAL SendLiveData)296 objEvent = PubSubsubscribe(EVENT_MOTORS_ON SendLiveData)297 298

299 function CloseTimer() 300 PubSubunsubscribe(objEvent)301 PubSubunsubscribe(objTimer)302 objEvent = null303 objTimer = null304 305

306 API method abrponetime()307 Read and send data but only once no timer launched308 exportsonetime = function() 309 readConfig()310 InitTelemetry()311 SendLiveData()312 CloseTelemetry()

(continues on next page)

96 Chapter 3 Plugins

Open Vehicles

(continued from previous page)

313 314

315 API method abrpinfo()316 Do not send any data just read vehicle data and writes in the console317 exportsinfo = function() 318 readConfig()319 InitTelemetry()320 UpdateTelemetry()321 CloseTelemetry()322 323

324 API method abrpresetConfig()325 Resets stored config to default326 exportsresetConfig = function() 327 OvmsConfigSetValues(usrabrp DEFAULT_CFG)328 print(JSONstringify(abrp_cfg))329 OvmsNotifyRaise(info usrabrpstatus ABRPconfig changed)330 331

332 API method abrpsend()333 Checks every minut if important data has changed and send it334 exportssend = function(onoff) 335 if (onoff) 336 readConfig()337 if (objTimer = null) 338 print(Already running + CR)339 return340 341 print(Start sending data + CR)342 InitTelemetry()343 SendLiveData()344 InitTimer()345 OvmsNotifyRaise(info usrabrpstatus ABRPstarted)346 else 347 if (objTimer == null) 348 print(Already stopped + CR)349 return350 351 print(Stop sending data + CR)352 CloseTimer()353 CloseTelemetry()354 OvmsNotifyRaise(info usrabrpstatus ABRPstopped)355 356

313 Usage

How to make it run

bull install as described in lsquoInstallationrsquo

bull add to storescriptsovmsmainjs abrp = require(sendlivedata2abrp)

bull script reload

With command lines in the OVMS android or iOS app in the messages part

31 ABRP abetterrouteplannercom 97

Open Vehicles

bull script eval abrpinfo() =gt to display vehicle data to be sent to abrp

bull script eval abrponetime() =gt to launch one time the request to abrp server

bull script eval abrpsend(1) =gt toggle send data to abrp

bull script eval abrpsend(0) =gt stop sending data

bull script eval abrpresetConfig() =gt reset configuration to defaults

Also in the messages part configuration can be updated with

bull config set usr abrpcar_model ltvaluegt

bull config set usr abrpurl ltvaluegt

bull config set usr abrpuser_token ltvaluegt

32 AuxBatMon 12V History Chart

Web chart showing last 24 hours of 12V battery metrics (similar to Android App)

Version 23 by Michael Balzer ltdexterdexters-webdegt

The module plugin records the relevant 12V battery metrics (voltage reference voltage current charger and environ-ment temperatures) once per minute for up to 24 hours by default

The web plugin renders these recordings into a time series chart and continues feeding live updates into the chart Thechart is zoomable and can be panned along the X axis

Since version 20 metrics history data is stored in a file and restored automatically on rebootreload This needsOVMS firmware gt= 32008-235 to work (will fallback to no saving on earlier versions)

98 Chapter 3 Plugins

Open Vehicles

Version 23 changes the file and transfer encoding from JSON to CBOR Upgrading is strongly recommended asthis has a substantial performance gain for both the module (scripting engine) and the web user interface (loading thechart)

321 Installation

1 Save auxbatmonjs as storescriptslibauxbatmonjs

2 Add line to storescriptsovmsmainjs

bull auxbatmon = require(libauxbatmon)

3 Issue script reload or evaluate the require line

4 Install auxbatmonhtm web plugin recommended setup

bull Type Page

bull Page usrauxbatmon

bull Label 12V History

bull Menu Tools

bull Auth Cookie

322 Configuration

No live config currently You can customize the sample interval (default 60 seconds) and the history size (default24 hours) by changing the constants in the code Take care to match a customization in both the module and the webplugin

The persistent history storage file is storeusrauxbatmoncbor by default It needs ~30 kB with the defaultconfiguration If space is tight on your store partition you can change the file location to sd in the sourcecode

323 Plugin API

auxbatmondump(CBOR) -- dump recorded history data in CBOR format (binary)auxbatmondump() -- dump recorded history data in JSON formatauxbatmondump() -- get a copy of the history data object

33 ChgInd Charge State Indicator

Control three LEDs to indicate charging amp SOC level

Version 10 by Michael Balzer ltdexterdexters-webdegt

Following an idea by ldquogreen_foxrdquo on the german Twizy forum (not limited to the Twizy) to implement an externallyvisible charge indicator

Use a red a green and a blue LED to signal charge state

bull OFF = not charging

bull RED = charging SOC below 20

33 ChgInd Charge State Indicator 99

Open Vehicles

bull YELLOW (RED+GREEN) = charging SOC 20 80

bull GREEN = charging SOC above 80

bull BLUE = fully charged (held for 15 minutes)

This plugin uses three EGPIO lines to control the three LEDs (KISS) By using a shift register this could be reducedto two lines by using a serial protocol to one line The latter would need protocol support in the EGPIO (todo)

331 Installation

1 Save chgindjs as storescriptslibchgindjs

2 Add line to storescriptsovmsmainjs

bull chgind = require(libchgind)

3 Issue script reload or evaluate the require line

332 Configuration

EGPIO ports to useconst LED_red = 4 EIO_3const LED_green = 5 EIO_4const LED_blue = 6 EIO_5

Time to hold BLUE state after charge stopconst holdTimeMinutes = 15

333 Plugin API

chgindset(state) -- set LED state (offredyellowgreenblue)

34 Edimax Smart Plug Control

Smart Plug control for Edimax models SP-1101W SP-2101W et al

Version 20 by Michael Balzer ltdexterdexters-webdegt

Note may need HTTPrequest() digest auth support to work with newer Edimax firmware (untested)

The smart plug can be bound to a defined location Automatic periodic recharging or charge stop can be configuredvia main battery SOC level andor 12V battery voltage level The plugin can also switch off power at the charge stopevent of the main andor 12V battery

341 Installation

1 Save edimaxjs as storescriptslibedimaxjs

2 Add line to storescriptsovmsmainjs

bull edimax = require(libedimax)

3 Issue script reload

100 Chapter 3 Plugins

Open Vehicles

4 Install edimaxhtm web plugin recommended setup

bull Type Page

bull Page usredimax

bull Label Edimax Smart Plug

bull Menu Config

bull Auth Cookie

5 Install edimax-statushtm web plugin recommended setup

bull Type Hook

bull Page status

bull Hook bodypost

The edimax-statushtm plugin adds power control to the Status pagersquos vehicle panel

342 Configuration

Use the web frontend for simple configuration

Param Instance Descriptionusr edimaxip Edimax IP addressusr edimaxuser username admin by defaultusr edimaxpass password 1234 by defaultusr edimaxlocation optional restrict auto switch to this locationusr edimaxsoc_on optional switch on if SOC atbelowusr edimaxsoc_off optional switch off if SOC ataboveusr edimaxchg_stop_off optional yes = switch off on vehiclechargestopusr edimaxaux_volt_on optional switch on if 12V level atbelowusr edimaxaux_volt_off optional switch off if 12V level ataboveusr edimaxaux_stop_off optional yes = switch off on vehiclecharge12vstop

343 Usage

script eval edimaxget()script eval edimaxset(on | off)script eval edimaxinfo()

Note get() amp set() do an async update (if the location matches) the result is logged Use info() to show thecurrent state

344 Events

usredimaxonusredimaxoffusredimaxerror

34 Edimax Smart Plug Control 101

Open Vehicles

35 Foglight Speed Adaptive Foglight

Automatic speed adaptive fog light using OVMS GPIO port

bull foglightjs ndash module script

bull foglighthtm ndash web dashboard extension

Details httpsdocsopenvehiclescomenlatestcomponentsovms_scriptdocsfoglighthtml

36 PwrMon Trip Power Chart

Web chart showing average speed power amp energy use on the road

Version 12 by Michael Balzer ltdexterdexters-webdegt

The plugin calculates average speed (kph) power (kW) amp energy use (Wpk = Whkm) from the odometer altitudeand energy counters (metrics vbenergyused amp vbenergyrecd) so the vehicle needs to provide thesewith reasonable precision amp resolution

The optional module plugin continuously records and stores the metrics history so the chart can load the last 20 km(by default) when opened The chart will then continue to add live metrics data Without the module plugin the chartwill only display live data

The chart is zoomable and can be panned along the X axis The four data series can be selected and shownhidden asusual by clicking on the series names in the legend click into the chart to highlight a specific data point

The live data may be more accurate than the data stored by the module plugin as it will react directly to the odometerchange while the module plugin can only check the odometer once per second

Version 12 changes the file and transfer encoding from JSON to CBOR Upgrading is strongly recommended asthis has a substantial performance gain for both the module (scripting engine) and the web user interface (loading thechart)

102 Chapter 3 Plugins

Open Vehicles

361 Installation

1 Install pwrmonhtm web plugin recommended setup

bull Type Page

bull Page usrpwrmon

bull Label Trip Power Chart

bull Menu Tools

bull Auth Cookie

2 Optionally

bull Save pwrmonjs as storescriptslibpwrmonjs

bull Add line to storescriptsovmsmainjs

ndash pwrmon = require(libpwrmon)

bull Issue script reload or evaluate the require line

362 Configuration

No live config currently You can customize the sample interval (default 03 km) and the history size (default 20 km)by changing the constants in the code The storage file and interval (1 km) can also be changed

On the web plugin you can customize the live sample interval (default 03 km doesnrsquot need to match the moduleplugin) and the initial zoom (default 8 km)

The persistent history storage file is storeusrpwrmoncbor by default It needs ~10 kB with the defaultconfiguration If space is tight on your store partition you can change the file location to sd in the sourcecode or disable the file by setting an empty string as the filename

363 Plugin API

pwrmondump(CBOR) -- dump recorded history data in CBOR format (binary)pwrmondump() -- dump (print) recorded history data in JSON formatpwrmondata() -- get a copy of the history data object

37 RegenMon Regen Brake Monitor

Live monitoring for regenerative brakelight amp acceleration level

bull regenmonhtm

Details httpsdocsopenvehiclescomenlatestcomponentsovms_webserverdocsregenmonhtml

38 REPIDScan OBD2 PID Scanner UI

Web UI for the OVMS3 RE toolkitrsquos OBD2 PID scanner

Version 21 by Michael Balzer ltdexterdexters-webdegt

37 RegenMon Regen Brake Monitor 103

Open Vehicles

bull 10 Initial release

bull 20 Highlight differences between scan results

bull 21 PID step support

This is a web frontend for the re obdii scan commands

Some basic usage notes are included but you really should have some knowlegde of how accessing ECU and otheronboard devices via OBD-IIUDS works Some pointers to get started

bull httpsenwikipediaorgwikiOBD-II_PIDs

bull httpsenwikipediaorgwikiUnified_Diagnostic_Services

You will need OVMS firmware release 32015-324 or higher to be able to use all features

The UI allows to easily define and keep multiple scans along with notes Scan results of two successive runs can becompared directly The UI checks if vehicle NONE is loaded and shows a button to switch to that otherwise The CANbuses can be started from the UI as well

Scan results are shown in plain text form as delivered by the underlying commands

Feel free to improve and extend (and submit your results)

381 Installation

1 Install repidscanhtm web plugin recommended setup

104 Chapter 3 Plugins

Open Vehicles

bull Type Page

bull Page usrrepidscan

bull Label RE PID Scanner

bull Menu Tools

bull Auth Cookie

382 Usage

Warning The scanner allows to use any poll type Requests will be sent with PIDs only though but somedevices may fail to validate the request length so be careful not to use any write or control poll types

The OBD2 PID scanner performs a series of OBDUDS requests for a range of PIDs and displays the results OnlyPIDs with positive results (responses) will be shown in the results

Enter all values hexadecimal (case irrelevant) Default RXID is TXID+8 try RXID range 500-7FF if you donrsquot knowthe responding ID To send broadcast requests set TXID to 7DF and RXID to 7E8-7EF The PID range must matchthe poll type PID constraints (816 bit)

Click ldquoStartrdquo to run a scan Only one scan can be active at a time but you donrsquot need to stop a scan to start anotherrun

Scan results will be shown automatically when the scan has been completed Scanning a large range of PIDs may takesome time to get intermediate results click ldquoStatusrdquo You can also start the scan do something else and return to thetool later

Differences between two scans are highlighted in both result tabs with added PIDs being marked green (yellow innight mode) and byte value changes being marked red No highlighting is applied if the scans donrsquot share any PIDs

On the next scanner start the previous results (if any) will be copied to the ldquoPreviousrdquo tab You can switch tabs by themouse or keyboard to compare them and look for differences eg after having changed some control on the car

All inputs and outputs can be saved to and loaded from files on the module or SD card Use this to define your areasof interest so you can easily re-run a previously defined scan the next day File format is plain readable JSON so youcan continue analysis or prepare scans offline

Notes to avoid clashing of scan polls with vehicle polls use the scanner only with the vehicle module NONE TheCAN bus to use needs to have been started in active mode The scanner does not send session or tester presencemessages if you need these use the re obdii tester tool or the obdii canX request command

39 Renault Twizy

391 Dashboard-Tuneslider

Add recuperation control to the dashboard

bull dashboard-tunesliderhtm

Details httpsdocsopenvehiclescomenlatestcomponentsovms_webserverdocsplugin-twizydashboard-tunesliderhtml

39 Renault Twizy 105

Open Vehicles

392 eDriver BMS Monitor

Status monitor for the Twizy custom eDriver BMS by Pascal Ripp

Version 20 by Michael Balzer ltdexterdexters-webdegt

This is a simple web page plugin to display the standard battery cell info along with the additional custom data providedby the eDriver BMS on one page

Additional custom data

bull Main state

bull Error state

bull BMS internal temperature

bull AUX relay state

bull Cell balancing states

Note these are read from their respective custom metrics xrtbms see Custom Metrics

Overall SOC voltage current and coulombenergy counters are also shown to simplify battery capacity and currentsensor calibration

Check out the eDriver BMS Manual for details or contact Pascal in case of questions

Installation

1 Install edrvmonhtm web plugin recommended setup

bull Type Page

bull Page usredrvmon

bull Label eDriver BMS Monitor

bull Menu Vehicle

bull Auth Cookie

106 Chapter 3 Plugins

Open Vehicles

History

bull V20 ndash Added cell balancing time totals + SOC amp voltage usecharge range

bull V10 ndash Initial release

393 Page-Command

only command options as UI

Version 02 Matthias Greiling ltmatthiasgreilingdegt

Details

This view only presents commands to OVMS While driving you can choose between different drive modes Thecoloured area indicates the active drive mode Activate an other mode by touching or clicking the grey bordered areaTo change again simply click or touch again the same or another ares Furthermore you can limit the speed online topredefined values The speed limit signs are common in germany and display kmh Just activate the sign you want tobe limited to - another touch will deactivates the limit of the chosen one

Installation

1 Install page-commandhtml web plugin recommended setup

bull Type Page

bull Page usrcommand

bull Label

bull Menu Main

bull Auth Cookie

39 Renault Twizy 107

Open Vehicles

History

bull V02 ndash Simplfy backgrounds icons of command row

bull V01 ndash Initial release

394 WifiConsole

Backend for WifiConsole hardware extension

bull WifiConsolejs

Details httpsgithubcomdexterbgWifiConsole

310 VW e-Up Mii Citigo

3101 ECUToolkit VW e-Up ECU Access

Library and web UI for diagnostics and configuration of the e-Up Mii Citigo ECUs

bull Library version 05 by Michael Balzer ltdexterdexters-webdegt

bull Web UI version 01 by Michael Balzer ltdexterdexters-webdegt

108 Chapter 3 Plugins

Open Vehicles

You will need OVMS firmware release 32016-226 or higher to be able to use this

The library is meant as a general tool to access the VW ECUs It provides means to simplify sending OBDUDScommands to ECUs by ID and to automate diagnostic session loginlogout It provides methods to set the workshopcode (WSC) do security authorization do scans and codings

The web UI allows to open multiple tools for different ECUs and saveload the current setup including the tool states

Feel free to improve and extend (and submit your results)

Warning

Warning Use at your own risk This ECU toolkit is based on reverse engineering I havenrsquot had access to anyofficial documentation Itrsquos only been used and tested on few vehicles chances are there will be issues with othervehicle configurations

Note If yoursquore interested in a fully featured VW ECU tool consider buying the excellent third party tools VCDS(httpswwwross-techcomvag-com) or OBDeleven (httpsobdelevencom) which fully support all VW vehiclesincluding of course the e-Up These tools also can decode most DTCs and provide detailed information on faultconditions

310 VW e-Up Mii Citigo 109

Open Vehicles

Installation

1 Save xvu-ecujs as storescriptslibxvu-ecujs

bull Add to storescriptsovmsmainjs

ndash xvu = ecu require(libxvu-ecu)

ndash or in case you already have the xvu namespace object just add the ecu part

bull Issue script reload or evaluate the require line

2 Install xvu-ecu-toolhtm web plugin recommended setup

bull Type Page

bull Page xvuecutoolkit

bull Label ECU Toolkit

bull Menu Vehicle

bull Auth Cookie

Usage

You can use the toolkit without ignition on if you just want to review some stored backup or dry run some coding tests

The web UI shows the list of known ECUs on the left side (or upper side on mobile devices) The list can be filteredto only show ECUs installed in the car by clicking the ldquordquo button this will need ignition on so the library can accessthe CAN gateway

Open a tool by selecting the ECU to investigate then clicking the tool button below the list To switch between toolsclick on the tool tab title To close a tool click the cross mark on the tool tabrsquos title

You can save the toolkit state (ie all open tools including their data) to a file on the OVMS SD card or store partitionLoading replaces the current toolkit state by the one loaded so discards any unsaved content

Click the menu box title to collapse or expand the box Loading will automatically collapse the menu box on mobiledevices

Enable the debug log messages to see which OBDUDS commands are performed The log will be shown in the panelfooter The read only mode inhibits OBDUDS commands doing PID changes DTC clearing or security accessesThey will still be logged so you can see what would be done

If you encounter issues send me a debug log

Scan tool

The Scan tool is considered to be safe as no write operations are involved

Scan results include the current hardware amp software versions the codings and DTCs so are useful as a backup forlater reference

To do a scan turn the ignition on select the ECU to scan and click the Scan button A new tab will open and thescan will start immediately Scans take from 5 - 15 seconds depending on the number of subsystems and other systemactivity The results will be shown in the tab

110 Chapter 3 Plugins

Open Vehicles

Coding tool

The Coding tool allows to change the ECU configuration ECUs may accept invalid codings that possibly can causehardware damage so be cautious ECUs will record all your write operations Even though the toolkit reuses the lastworkshop code found in the ECU by default there still will be a log entry carrying the date of the change

Use the full coding input field to copy amp paste codings for backups amp restores eg from a former scan result Afterpasting click outside the field to validate the coding and update the bits

Subsystem codings are included in the ECU coding other than in the scan result where they are shown at the respectivesubsystem You can paste amp write only the main coding the subsystem will then not be changed

Select a byte position to view and change the individual bits of that byte Only labels for bits known to work onthe VW e-Up models have been added up to now source of this is the german GoingElectric forum amp wiki (httpswwwgoingelectricde)

To submit a changed coding to the ECU click ldquoWriterdquo Most codings donrsquot need a security code so leave the fieldempty unless ldquoWriterdquo aborts with a security clearance error Security codes can be found in the forums and officialrepair manuals

Library API

Documentation on the API methods is in preparation

As this is currently an alpha release the API is work in progress and likely to change

If yoursquore interested in using whatrsquos considered stable now or possibly even contribute please read the source andcontact me

311 Installing Module Plugins

A module plugin normally consists of a single Javascript file that needs to be placed in the storescriptslibdirectory The plugin is then loaded by a require() call which can be done manually as needed or automaticallyon boot by adding it to the storescriptsovmsmainjs file

1 Menu Tools rarr Editor

2 Cancel the open dialog

3 Paste the plugin source into the editor

4 Save as rarr storescriptslib using the name as shown in the plugin documentation

5 Open rarr (one level up) rarr ovmsmainjs

6 Add the require() call as shown in the plugin documentation

7 Save

8 Reload JS Engine

The plugin is now installed and activated

Hint you can now try out the commands provided by the plugin directly from the editor Clear the editor fill in thecommand or Javascript snippet click Evaluate JS The output will be shown below the input field

To deactivate a plugin comment out the require() call by prefixing the line with and do another JS enginereload To remove a plugin remove the require() call and delete the file using vfs rm storescriptslib

311 Installing Module Plugins 111

Open Vehicles

312 Installing Web Plugins

A web plugin normally consists of a single HTML file Web plugins can be meant to render new pages or to hook intoan existing page They need an initial registration to work

1 Menu Config rarr Web Plugins

2 (add)

3 Set type and name as suggested in the plugin documentation

4 Save

5 Edit

6 Set attributes as suggested in the plugin documentation

7 Paste the plugin source into the content area

8 Save

The plugin is now installed and activated

Hint you can use the text editor (tools menu) to change or update an already installed web plugin Simply edit theplugin file in folder storeplugin directly the system will reload the plugin as soon as you save it

To deactivate a web plugin set the state to ldquooffrdquo To remove a plugin click rarr Save

112 Chapter 3 Plugins

CHAPTER 4

BMW i3 i3s

Vehicle Type BMWI3

This vehicle type supports the BMW i3 and i3s models All model years should be supported

The OVMS support was developed Jan 2021

It was developed against the authorrsquos 2018 120Ah i3s BEV I would welcome engagement from the owner of a REXtype to further develop metrics related to the REX engine Testing by drivers of LHD models as well as those withthe smaller batteries will also be helpful

As of this release this vehicle support is read-only and cannot send commands to the car

41 Support Overview

ldquotbardquo item are still on the to-do list and are not currently supported

113

Open Vehicles

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable OBD-II cable left-handed cable worked best in my RHD carGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (or any compatible antenna)SOC Display YesRange Display YesCabin Pre-heatcool Control tbaGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display tbaCharge Status Display YesCharge Interruption Alerts YesCharge Control tbaLockUnlock Vehicle tbaValet Mode Control NoOthers 12v battery voltagecurrent battery true SOC etc

42 WARNINGS

421 Alarm behaviour

As standard the i3 will sound the alarm if anything is left connected to the OBD-II port when the car is locked

A tool like Bimmercode will allow you to disable this Alternatively you will need to disconnect the OVMS unit beforelocking the car

A future version may add a command to allow you to disable this alarm directly from your OVMS shell

422 12V Battery drain

The i3 has a small 20Ah AGM 12v battery Whilst care has been taken to minimize OVMSrsquo power usage OVMScould eventually drain this battery if the car is left unplugged and locked OVMS will also send an alert if 12V dropsunder 12V alert threshold (See 12V Calibration section)

HOWEVER If you are going to leave the car for a fews days it is recommended to unplug OVMS

43 Car status

The car is accessible over the OBD-II port when it is running (ignition on) and for a short time (40 seconds or so) afterit is turned off or the car is ldquotweakedrdquo (lock button pushed connected-drive command received etc)

Unfortunately this means that when your car is standing or charging OVMS only has intermittent access to data fromthe car

By observation whilst the car is charging it wakes up now and then (seems to be every 30 minutes) So at those timeswe can update our SOC etc

114 Chapter 4 BMW i3 i3s

Open Vehicles

Metrics ldquoveawakerdquo tells you if the car is awake or not Metric ldquoxi3sagerdquo will tell you how many minutes have passedsince we last received data from the car

You may also refer to metric xi3spollermode as follows

Mode Meaning0 Car is asleep - no OBD-II data traffic1 Car OBD-II is awake - we are seeing data traffic2 Car is ready to drive or driving3 Car is charging

44 Custom metrics

Metric name Example value Descriptionxi3sage 5Min How long since we last got data from the carxi3spollermode 0 OBD-II polling mode as explained abovexi3vbpocvavg 40646V Main battery pack - average open-circuit voltagexi3vbpocvmax 4067V Main battery pack - highest open-circuit voltagexi3vbpocvmin 4063V Main battery pack - lowest open-circuit voltagexi3vbrangebc 245km Available range per trip computer (based on current driving mode and style)xi3vbrangecomfort 217km Available range if you use Comfort modexi3vbrangeecopro 245km Available range if you use EcoPro modexi3vbrangeecoproplus 247km Available range if you use EcoPro+ modexi3vbsocactual 85 Actual physical state-of-charge of the main battery packxi3vbsocactualhighlimit 937 Highest physical charge level permitted (shown as 100 SOC)xi3vbsocactuallowlimit 105 Minimum physical charge level permitted (shown as 0 SOC)xi3vcchargecablecapacity 0A Maximum power capacity of connected charge cable per the charging interfacexi3vcchargeledstate 0 Colour of the ldquoring lightrdquo on the charging interfacexi3vcchargeplugstatus Not connected Charging cable connectedxi3vccurrentdc 0A Power flowing on the DC side of the AC chargerxi3vccurrentdclimit 0100003A Limitxi3vccurrentdcmaxlimit 16A Maximum limitxi3vccurrentphase1 0A Power being drawn on AC phase 1xi3vccurrentphase2 0A Power being drawn on AC phase 2xi3vccurrentphase3 0A Power being drawn on AC phase 3xi3vcdcchargevoltage 0V Voltage seen on the DC charger inputxi3vcdccontactorstatus open DC contactor state (closed implies we are DC charging)xi3vcdccontrolsignals 0 DC charger control signals (always see 0)xi3vcdcinprogress no DC charging in progressxi3vcdcplugconnected no Is DC charger plug connected (doesnrsquot seem to work)xi3vcderatingreasons 0 Reasons why charging rate is deratedxi3vcerror 0 Charging error codesxi3vcfailsafetriggers 0 Failsafe trigger reasonsxi3vcinterruptionreasons 0 Charging interruption reasonsxi3vcpilotsignal 0A Charge rate pilot signal being received from EVSExi3vcreadytocharge no Are we ready to chargexi3vctempgatedriver 40degC Charger gatedrive mosfet temperaturexi3vcvoltagedc 84V Charger output DC voltage being seen (for AC charging not DC)xi3vcvoltagedclimit 420V Maximum permitted DC voltge

Continued on next page

44 Custom metrics 115

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxi3vcvoltagephase1 0V Voltage seen on AC charger input phase 1xi3vcvoltagephase2 0V Voltage seen on AC charger input phase 2xi3vcvoltagephase3 0V Voltage seen on AC charger input phase 3xi3vdchargeportdc no Is the charger port DC cover open (doesnrsquot seem to work)xi3veautorecirc no Ventilation is in ldquoauto-recirculaterdquo modexi3veobdtraffic no Are we seeing OBD-II frames from the carxi3vptripconsumption 127Whkm Average consumption for the current or most recent tripxi3vpwheel1_speed 0kmh Wheel 1 speedxi3vpwheel2_speed 0kmh Wheel 2 speedxi3vpwheel3_speed 0kmh Wheel 3 speedxi3vpwheel4_speed 0kmh Wheel 4 speedxi3vpwheel_speed 0kmh Average wheel speed

45 To be researched

Can we startstop charging

Can we pre-heat

Can we lockunlock the car

Can we disable the OBD-II alarm

Still looking for the trip regen kWh

Can we get the voltage state of each individual cells rather than just the battery min max average

116 Chapter 4 BMW i3 i3s

CHAPTER 5

DBC Based Vehicles

Vehicle Type DBC

The DBC based vehicle reads a specified DBC file describing CAN bus messages and produces vehicle metrics fromthat It is under development experimental and not generally available

51 Support Overview

Function Support StatusHardware This is vehicle specific The DBC vehicle module can be configured to use any or all of

the 3 CAN busesVehicle Cable Vehicle specificGSM Antenna Standard GSM antennaGPS Antenna Vehicle specific Standard OVMS GPS supportedSOC Display Yes if DBC maps itRange Display Yes if DBC maps itGPS Location Yes if DBC maps it otherwise OVMS GPSSpeed Display Yes if DBC maps itTemperature Display Yes if DBC maps itBMS v+t Display Not currently supportedTPMS Display Yes if DBC maps itCharge Status Display Yes if DBC maps itCharge InterruptionAlerts

Yes if DBC maps it

Charge Control Not supported by DBC format maybe by extensionCabin Pre-heatcoolControl

Not supported by DBC format maybe by extension

LockUnlock Vehicle Not supported by DBC format maybe by extensionValet Mode Control Not supported by DBC format maybe by extensionOthers None

117

Open Vehicles

52 Contents

521 DBC Introduction

DBC is a CAN data description file format introduced by Vector Informatik GmbH DBC files are text files so can becreated and edited using a simple text editor like the one built into the OVMS web UI

DBC files can be used to support vehicles that donrsquot have a dedicated native adaption yet This is done using thegeneric DBC vehicle type which can use DBC files to translate CAN data into metrics

This section tries to show you how to create and use a DBC specification on the OVMS Of course yoursquoll need to knowhow to decode your vehiclersquos CAN frames first You can use the OVMS RE (reverse engineering) toolkit to identifywhich messages are on the bus and which changes correlate to actions and status on the car

Therersquos also a very good general introduction to DBC from CSS Electronics including an explanatory video httpswwwcsselectronicscomscreenpagecan-dbc-file-database-introlanguageen

DBC files only specify the passive (reading) part they donrsquot provide a means to define transmissions If you need tosend frames to request certain information you can still use the OVMS DBC engine to decode the results (instead ofdoing the decoding in C++ code) So a DBC file can be used as a base for a real vehicle module To request OBD2data during development you can use the re obdii commands

Basic Example

Warning The DBC support is usable but considered to be an alpha release The way it works may change in thefuture

This example is taken from the Twizy which sends some primary BMS status data at CAN ID 0x155 (341) Note theTwizy module actually does not use DBC this is just an example how you would decode this message if using DBC

Message example 05 96 E7 54 6D 58 00 6F

bull Byte 0 charge current limit [A] scaled by 5 no offset 05rarr 25A

bull Bytes 1+2 momentary battery current [A] big endian lower 12 bits scaled by -025 offset +500 _6 E7 rarr5825A

bull Bytes 4+5 SOC [] big endian scaled by 00025 no offset 6D 58rarr 6998

These can be translated to metrics directly

bull Charge current limit vcclimit

bull Momentary battery current vbcurrent

bull Battery SOC vbsoc

Create DBC File

Copy amp paste the following into a new editor window

VERSION DBC Example 10

BS_ 500000 00

BO_ 341 BMS_1 8 Vector__XXX

(continues on next page)

118 Chapter 5 DBC Based Vehicles

Open Vehicles

(continued from previous page)

SG_ v_c_climit 7|80+ (50) [0|35] A Vector__XXXSG_ v_b_current 11|120+ (-025500) [-500|1000] A Vector__XXXSG_ v_b_soc 39|160+ (000250) [0|100] Vector__XXX

What does this mean

bull BS_ defines the bus speed (500 kbit in this example) and bit timings (unused)

bull BO_ defines the data object a CAN frame of length 8 with ID 341 (0x155) (ldquoBMS_1rdquo is just an arbitrary name)

bull SG_ lines define the signals (values) embedded in the object (see below)

bull Vector__XXX is just a placeholder for any senderreceiver (currently unused by the OVMS)

Signals are defined by their

bull Name (= metric name with replaced by _)

bull Start position (bit position) and bit length (7|8)

bull Endianness 0 = big endian (most significant byte first) 1 = little endian (least significant byte first) (Note theDBC format documentation is wrong on this)

bull Signedness + = unsigned - = signed

bull Scaling and offset (-025500) =gt real value = raw value -025 + 500

bull Minimummaximum [-500|1000] = valid real values are in the range -500 to 1000

bull Unit eg A (ignoredirrelevant defined by the metric)

The metric to set can be given as the name of the signal You may use the metric name directly on the OVMS but toconform to the DBC standard replace the dots by _

Bit positions are counted from byte 0 upwards by their significance regardless of the endianness The first messagebyte has bits 0 7 with bit 7 being the most significant bit of the byte The second byte has bits 8 15 with bit 15being the MSB and so on

[ 7 6 5 4 3 2 1 0 ] [ 15 14 13 12 11 10 9 8 ] [ 23 22 21 20 `----- Byte 0 ----acute `------- Byte 1 --------acute `----- Byte 2

For big endian values signal start bit positions are given for the most significant bit For little endian values the startposition is that of the least significant bit

Note On endianness ldquobig endianrdquo means a byte sequence of 0x12 0x34 decodes into 0x1234 (most significantbyte first) ldquolittle endianrdquo means the same byte sequence decodes into 0x3412 (least significant byte first) ldquoBigendianrdquo is the natural way of writing numbers ie with their most significant digit coming first ldquolittle endianrdquo isvice versa Endianness only applies to values of multiple bytes single byte values are always written naturally ldquobigendianrdquo

Use DBC File

Save the DBC example as storedbctwizy1dbc (the directory will be created by the editor)

Open the shell To see debug logs issue log level debug dbc-parser and log level debug v-dbc

Note the DBC parser currently isnrsquot graceful on errors a wrong DBC file may crash the module So you shouldonly enable automatic loading of DBC files on boot when yoursquore done developing and testing it

52 Contents 119

Open Vehicles

So letrsquos first try if the DBC engine can parse our file The dbc autoload command loads all DBC files from thestoredbc directory

OVMS dbc autoloadAuto-loading DBC filesD (238062) dbc-parser VERSION parsed as DBC Example 10D (238062) dbc-parser BU_ parsed 1 nodesD (238062) dbc-parser BO_ parsed message 341D (238072) dbc-parser SG_ parsed signal v_c_climitD (238072) dbc-parser SG_ parsed signal v_b_currentD (238082) dbc-parser SG_ parsed signal v_b_soc

Looks good dbc list can tell us some statistics

OVMS dbc listtwizy1 DBC Example 10 1 message(s) 3 signal(s) 56 coverage 1 lock(s)

The coverage tells us how much of our CAN data bits are covered by signal definitions

Now letrsquos load the file into the DBC vehicle

OVMS config set vehicle dbccan1 twizy1Parameter has been set

OVMS vehicle module NONEI (1459922) v-none Generic NONE vehicle module

OVMS vehicle module DBCI (249022) v-dbc Pure DBC vehicle moduleI (249022) v-dbc Registering can bus 1 as DBC twizy1

Nice Letrsquos simulate receiving our test frame and check the decoded metrics

OVMS can can1 rx standard 155 05 96 E7 54 6D 58 00 6FOVMS me li vbsocvbsoc 6998OVMS me li vbcurrentvbcurrent 5825AOVMS me li vcclimitvcclimit 25A

So the decoding apparently works

To configure DBC mode for autostart we now just need to set the DBC vehicle mode to be loaded on vehicle startupand to enable autoloading of the DBC files from storedbc You can do so either by using the user interface pageConfig rarr Autostart (check ldquoAutoload DBC filesrdquo and set the vehicle type to ldquoDBCrdquo) or from the shell by

OVMS config set auto dbc yesOVMS config set auto vehicletype DBC

Try a reboot to see if everything works

You can now add more objects and signals to your DBC file

Note During development of a DBC file yoursquoll need to reload the file frequently The DBC engine locks the currentlyused vehicle so yoursquoll need to unload the DBC vehicle (vehicle module NONE) then reload the DBC file (dbcautoload) then reactivate the DBC vehicle (vehicle module DBC)

120 Chapter 5 DBC Based Vehicles

CHAPTER 6

DEMO Vehicle

Vehicle Type DEMO

The demonstration vehicle can be used to verify module functionality but is mostly used for development purposesThe vehicle itself updates system metrics with simulated data It can respond to charge and other similar commands

61 Support Overview

Function Support StatusHardware Demonstration data only no vehicle connectionVehicle Cable None not required (other than power)GSM Antenna Standard GSM antennaGPS Antenna None not requiredSOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display YesBMS v+t Display Not currently supportedTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control YesCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle YesValet Mode Control YesOthers None

121

Open Vehicles

122 Chapter 6 DEMO Vehicle

CHAPTER 7

Fiat 500e

Vehicle Type FT5E

The Fiat 500e vehicle support will be documented here

71 Support Overview

Function Support StatusHardware tbaVehicle Cable tbaGSM Antenna tbaGPS Antenna tbaSOC Display tbaRange Display tbaGPS Location tbaSpeed Display tbaTemperature Display tbaBMS v+t Display tbaTPMS Display tbaCharge Status Display tbaCharge Interruption Alerts tbaCharge Control tbaCabin Pre-heatcool Control tbaLockUnlock Vehicle tbaValet Mode Control tbaOthers tba

123

Open Vehicles

124 Chapter 7 Fiat 500e

CHAPTER 8

Hyundai Ioniq vFL

Hyundai Ioniq Electric (28 kWh)

bull Vehicle Type HIONVFL

bull Log tag v-hyundaivfl

bull Namespace xhi

bull Maintainers Michael Balzer

bull Sponsors Henri Bachmann

bull Credits EVNotify

125

Open Vehicles

81 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display NoGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display PartialBMS v+t Display YesSOH Display YesTPMS Display NoCharge Status Display YesCharge Interruption Alerts YesCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

82 Custom Metrics

Metric name Example value Descriptionxhibsocbms 785 Internal BMS SOCxhicstate 128 Charge state flags

83 Debug Logs

To see all PID poll results in your log set log level verbose for component v-hyundaivfl

126 Chapter 8 Hyundai Ioniq vFL

CHAPTER 9

Jaguar IPace

Vehicle Type IPace

Support for Jaguar IPace is provided by this module (c) 2021 by Didier Ernotte

91 Support Overview

Function Support StatusHardwareVehicle CableGSM AntennaGPS AntennaSOC Display YesRange DisplayGPS Location (not yet)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display (not yet)Charge Interruption AlertsCharge ControlCabin Pre-heatcool ControlLockUnlock Vehicle NoValet Mode Control NoOthers

127

Open Vehicles

92 Custom Metrics

xji_v_bat_capacity_soh_min xji_v_bat_capacity_soh_max xji_v_bat_power_soh xji_v_bat_power_soh_minxji_v_bat_power_soh_max xji_v_bat_max_regen

128 Chapter 9 Jaguar IPace

CHAPTER 10

Kia e-Niro

Vehicle Type KN

The Kia e-Niro vehicle support will be documented here

101 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable 9658635 Kia OBD-II to DB9 Data Cable for OVMSGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display Yes (based on consumption of past 20 trips longer than 1km)GPS Location YesSpeed Display Not currently supportedTemperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control Not currently supportedCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle YesValet Mode Control Not currently supportedOthers ODO Not currently supported

129

Open Vehicles

102 OBD-II cable

The Kia e-Niro have one CAN-bus available on the OBD-II port D-can You can use the standard OBD-II to DB9cable from Fasttech

In case you want to build your own cable herersquos the pinout

J1962-M DB9-F Signal4 3 Chassis Power GND6 7 CAN-0H (C-can High)14 2 CAN-0L (C-can Low)16 9 +12V Vehicle Power

A simple approach is to buy an OBDII (J1962-M) pigtail and solder the DB9-F connector end appropriately

103 Configuration

TODO Configuration is quite similar to the Kia Soul so please check that out Please use the Web based configuration

104 Estimated Range

Currently there is no known way to get the estimated range directly from the car so the estimated range is calculatedby looking at the consumption from the last 20 trips that are longer than 1 km

105 12V battery drain

OVMS will eventually drain the 12V battery but steps have been taken to minimize the drain However if you aregoing to leave the car for a fews days it is recommended to unplug OVMS OVMS will send an alert if 12V dropsunder 12V alert threshold See 12V Calibration section

130 Chapter 10 Kia e-Niro

CHAPTER 11

Kia Soul EV

Vehicle Type KS

The Kia Soul EV vehicle support will be documented here

111 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable 9658635 Kia OBD-II to DB9 Data Cable for OVMSGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display Temperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control Not currently supportedCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle YesValet Mode Control Not currently supportedOthers

131

Open Vehicles

112 OBD-II cable

The Kia Soul EV have two different CAN-busses available on the OBD-II port C-can and M-can

C-can is the main can-bus and M-can is the multimedia bus The latter one is not necessary for OVMS but somemetrics are fetched from the M-bus and these metrics will be empty if you donrsquot have the proper cable The standardOBD-II to DB9 cable from Fasttech supports only C-can so make sure you buy the Kia Soul specific one

In case you want to build your own cable herersquos the pinout

J1962-M DB9-F Signal1 5 CAN-1H (M-can High)4 3 Chassis Power GND6 7 CAN-0H (C-can High)9 4 CAN-1L (M-can Low)14 2 CAN-0L (C-can Low)16 9 +12V Vehicle Power

A simple approach is to buy an OBDII (J1962-M) pigtail and solder the DB9-F connector end appropriately

113 Configuration

There are a few Kia Soul EV specific settings that you have to consider in order to get the most out of OVMS Theseare battery size real life ideal range remote command pincode and charge port remote control

114 Battery size

Up until the 2018 version of Kia Soul all models had a 27kWh battery The 2018-version have a 30kWh batteryOVMS is by default set up with 27000Wh but you can change this configuration to fit your car using this commandin the OVMS-shell

config set xks cap_act_kwh 27000

NB Even though it says cap_act_kwh the number must be in Wh

115 Real life ideal range

Even though the Kia Soul EV is equipped with a pretty good and conservative GOM most experienced drivers knowhow far the car can go on a charge This is what we call the ideal range You can set the ideal range in kilometersexperienced at 20 degrees celsius by using this command

config set xks maxrange 160

This setting is set to 160 km by default and matches the author driving a 2015 Kia Soul Classic in 20 degrees insouthern Norway Your mileage may vary so please set it accordingly

The ideal range as shown in the OVMS APP are then derived from this number multiplied by the state of charge andadjusted using a combination of the outside temperature and the battery temperature

132 Chapter 11 Kia Soul EV

Open Vehicles

116 Open charge port using key fob

By default OVMS listens for the the third button on the key fob and opens the charge port if Pressed If you donrsquotwant this behaviour you can disable it by using this command

config set xks remote_charge_port 0

117 Security pin code for remote commands

Remote commands like lock and unlock doors among others require a pin code This pin code can be set using theweb configuration or using this command

config set password pin 1234

Please set this pin as soon as possible

118 Soul specific metrics

NB Not all metrics are correct or tested properly This is a work in progress

There are a lot of extra metrics from the Kia Soul Herersquos the current ones

Metric Descriptionxksbcellvoltmax The highest cell voltagexksbcellvoltmaxno The cell number with the highest voltagexksbcellvoltmin The lowest cell voltagexksbcellvoltminno The cell number with the lowest voltagexksbcelldetmax The highest registered cell deterioration in percentxksbcelldetmaxno The cell with the highest registered deteriorationxksbcelldetmin The lowest registered cell deterioration in percentxksbcelldetminno The cell with the lowest registered deteriorationxksbmintemp The lowest temperature in the batteryxksbmaxtemp The highest temperature in the batteryxksbinlettemp The air temperature at the air inlet to the batteryxksbheat1temp The temperature of the battery heater 1xksbheat2temp The temperature of the battery heater 2xksbbmssoc The internal state of charge from BMSxkscpower Charge power in kWxkscspeed The charge speed in kilometer per hourxksldcoutvolt The voltage out of the low voltage DC converterxksldcinvolt The voltage into the low voltage DC converterxksldcoutamps The power drawn from the low voltage DC converterxksldctemp The temperature of the LDCxksobcpilotduty The duty cycle of the pilot signalxkselowbeam Low beam onoffxksehighbeam High beam onoffxkseinsidetemp Actual cabin temperaturexkseclimatetemp Climate temperature settingxkseclimatedriveronly Climate is set to driver onlyxkseclimateresirc Climate is set to recirculate

Continued on next page

116 Open charge port using key fob 133

Open Vehicles

Table 1 ndash continued from previous pageMetric Descriptionxkseclimateauto Climate is set to autoxkseclimateac Air condition onoffxkseclimatefanspeed Climate fan speedxkseclimatemode Climate modexksepreheattimer1enabled Preheat timer 1 enableddisabledxksepreheattimer2enabled Preheat timer 2 enableddisabledxksepreheating Preheating onoffxkseposdisttodest Distance to destination (nav unit)xkseposarrivalhour Arrival time hour part (nav unit)xkseposarrivalminute Arrival time minute part(nav unit)xkseposstreet Current street Or Next streetxksvseatbeltdriver Seat belt sensorxksvseatbeltpassenger Seat belt sensorxksvseatbeltbackright Seat belt sensorxksvseatbeltbackleft Seat belt sensorxksvtractioncontrol Traction control onoffxksvcruisecontrolenabled Cruise control enableddisabledxksvemergencylights Emergency lights enableddisabledxksvsteeringmode Steering mode Sport comfort normalxksvpowerusage Power usage of the carxksvtripconsumptionkWh100km Battery consumption for current tripxksvtripconsumptionkmkWh Battery consumption for current trip

Note that some metrics are polled at different rates than others and some metrics are not available when car is off Thismeans that after a restart of the OVMS some metrics will be missing until the car is turned on and maybe driven forfew minutes

Climate and navigation-metrics are fetched from navigation unit and needs the Kia Soul compatible OBDII-cable

119 Soul specific shell commands

There are a few shell commands made for the Kia Soul Some are read only others can enable functions and some areused to write directly to a ECU and must therefore be used with caution

1191 Read only commands

xks trip

Returns info about the last trip from you put the car in drive (D or B) and til you parked the car

xks tpms

Shows the tire pressures

xks aux

Prints out the voltage level of the auxiliary battery

xks vin

134 Chapter 11 Kia Soul EV

Open Vehicles

Prints out some more information taken from the cars VIN-number Not complete

1192 Active Commands

xks trunk ltpin codegt

Opens up the trunk

xks chargeport ltpin codegt

Opens up the charge port

xks ParkBreakService ltonoffgt

Not yet working

xks IGN1 ltonoffgtltpingt

Turn on or off IGN1-relay Can be used to wake up part of the car

xks IGN2 ltonoffgtltpingt

Turn on or off IGN2-relay Can be used to wake up part of the car

xks ACC ltonoffgtltpingt

Turn on or off ACC-relay Can be used to wake up part of the car

xks START ltonoffgtltpingt

Turn on or off START-relay Can be used to wake up part of the car

xks headlightdelay ltonoffgt

Turn onoff the ldquofollow me homerdquo head light delay function

xks onetouchturnsignal lt0=Off 1=3 blinks 2=5 blinks 3=7 blinksgt

Configure one touch turn signal settings

xks autodoorunlock lt1=Off 2=On vehicle off 3=On shift to P 4=On driver doorunlockgt

Configure auto door unlock settings

xks autodoorlock lt0=Off 1=On speed 2=On shiftgt

Configure auto door unlock settings

119 Soul specific shell commands 135

Open Vehicles

1193 ECU-write commands

These commands are for the extra playful people Use with caution

xks sjb ltb1gtltb2gtltb3gt

Send command to smart junction box

xks bcm ltb1gtltb2gtltb3gt

Send command to body control module

1110 12V battery drain

OVMS will eventually drain the 12V battery but steps have been taken to minimize the drain However if you aregoing to leave the car for a fews days it is recommended to unplug OVMS

136 Chapter 11 Kia Soul EV

CHAPTER 12

Maxus eDeliver3

Vehicle Type MED3

The Maxus eDeliver3 will be documented here

121 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display NoTemperature Display Yes (External Temp and Battery)BMS v+t Display NoTPMS Display NoCharge Status Display NoCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

137

Open Vehicles

138 Chapter 12 Maxus eDeliver3

CHAPTER 13

Mercedes-Benz B250E W242

Vehicle Type SE

The Mercedes-Benz B-Klasse Electric Drive will be documented here

131 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display NoRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display NoBMS v+t Display NoTPMS Display NoCharge Status Display NoCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

139

Open Vehicles

132 Contents

1321 Standard Metrics

Metric name Notesms_v_mot_rpmms_v_env_throttle Resolution of 04 ms_v_pos_speed Resolution of 01 kmhms_v_pos_odometerResolution of 01 kmms_v_bat_12v_voltageResolution of 01 Vms_v_bat_power Car reports percents so the kW is just calculated by multiplying by 132 kW Negative side is

saturated to -50 kW This is just guess workms_v_bat_range_estms_v_bat_consumptionInstantious consumption Whkmms_v_tpms__pms_v_env_cabinsetpointThere are two figures left and right Using just one for now

1322 Custom Metrics

Metric name Example value Descriptionxmbvdisplaytripreset 27332km Dashbord Trip value since Resetxmbvdisplaytripstart 175km Dashbord Trip value since Start (today)xmbvdisplayconsumptionstart 259 kWh Dashbord Trip consumption since Start (today)xmbvdisplayaccel 89 Eco score on acceleration over last 6 hoursxmbvdisplayconst 18 Eco score on constant driving over last 6 hoursxmbvdisplaycoast 100 Eco score on coasting over last 6 hoursxmbvdisplayecoscore 69 Eco score shown on dashboard over last 6 hoursxmbvfl_speed 3783 kmh Front Left wheel speedxmbvfr_speed 3785 kmh Front Right wheel speedxmbvrl_speed 3780 kmh Rear Left wheel speedxmbvrr_speed 3782 kmh Rear Right wheel speed

140 Chapter 13 Mercedes-Benz B250E W242

CHAPTER 14

MG EV

Vehicle Types MG EV (UKEU) amp MG EV (TH)

These vehicle types support the MG ZS EV (2019-) MG5 is not yet supported in this build

141 Variants

MG ZS EVs sold in different countries seem to possess different behaviours This is why we have developed 2 differentvehicle types to support the different requirements

1411 Known Countries

Coun-try

Zombiemode

Requires GWM authenti-cation

Poll BCM causesalarm

Suggested vehicle type touse

UKEU Y N Y UKEUThai-land

N Y N TH

Aus-tralia

N N N TH

Zombie mode is when the gateway module (GWM) enters the locked state and no PIDs can be accessed This happens for UKEU cars when

1 Charger is plugged in without power car is locked and goes to sleep

2 Charger is then powered on and car starts charging

GWM authentication is required for Thai cars as GWM will be locked and no PIDs can be accessed (simiarly toZombie mode but this happens all the time rather than just during the above scenario) Note GWM authenticationdoes not work as a mitigation for UKEUrsquos Zombie mode

When the BCM is polled UKEU carsrsquo alarm (horn) can go off so this is disabled in the UKEU code

141

Open Vehicles

1412 Other Countries

For cars from other countries to decide which vehicle type you should use start off by trying the MG EV (TH) typefirst because Zombie mode mitigation has its side effects (see module notes below) and polling the BCM allows theOVMS to get more data from the car

You can follow these steps to see which variant may be suitable for your car

1 Select MG EV (TH) and use the car as you would normally Keep an eye on shell for log prints to see ifany problems occur

2 If the alarm goes off sometimes (like when doors are locked using remote) try switch to MG EV (UKEU)

3 If you do not get any alarm try put the car into Zombie mode

4 If OVMS is unable to get data (like no charging details appear on the app) try switch to MG EV (UKEU)

142 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 2019-Vehicle Cable Right hand OBDII cable (RHD) Left hand OBDII cable (LHD)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (or any compatible antenna)SOC Display YesRange Display Yes (BMS calculated and WLTP range from SoC)Cabin Pre-heatcool Control NoGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control NoLockUnlock Vehicle NoValet Mode Control NoOthers Daytime Running Light Control

143 Shell Commands

softver Get software version of ECUsdrl [on | off] Turn onoff daytime running lightsdrln [on | off] Turn onoff daytime running lights without doing BCM authentication first (for de-

bugging purposes)auth [all | gwm |bcm]

Authenticate with specified ECU lsquoauth allrsquo will authenticate GWM then BCM

142 Chapter 14 MG EV

Open Vehicles

144 Module notes

The code for each vehicle type has these behaviours

Vehicle type Zombie mode mitigation GWM authentication Poll BCMUKEU Y N NTH N Y Y

The MG EV module now monitors (and automatically calibrates) the 12V status and will automatically start pollingthe car for data when the 12V battery voltage is equal to or greater than 129V When it is below 129V it willautomatically stop polling (after a 50s delay) to not drain the 12V battery

Poll states

0 Lis-tenOnly

the OVMS module is quiet and stops sending polls

1 Charg-ing

the OVMS module sends charging specific queries

2 Driving the OVMS module sends driving specific queries3 Backup the OVMS module cannot get data from the car when it is charging so just retries SoC queries

This is unused in TH code

1441 UKEU spec

The car is accessible over the OBD port when it is running (ignition on) and for around 40 seconds after it is turnedoff or the car is ldquotweakedrdquo (lock button pushed etc)

The OBD port may be kept awake by using the ldquotester presentrdquo message to the gateway ECU This keeps a lot ofsystems awake and draws roughly 5A on the 12V bus so itrsquos not a good idea to do

The Gateway (GW GWM) is the keeper of all the data of the car and will enter a locked state when it is woken by thecar starting charging and the car is locked This we have called ldquoZombie Moderdquo and we have developed an overridefor this

This override however causes a few strange things to happen

bull If Zombie mode override is active the car will not unlock the charge cable To fix this dusrupt the chargeand wait 50s for OVMS to go back to sleep and the cable should release (or unplug OVMS)

bull Zombie mode override resets the ldquoAccumulated Total Triprdquo on the Cluster

bull Zombie mode override sets the gearshift LEDs switch on

145 Development notes

Developers welcome Follow the developerrsquos guide on httpswwwopenvehiclescomdevelopers to get started Joinour slack group (see below) to discuss the nerdy details

146 Community channels

Forum httpswwwmgevscom

144 Module notes 143

Open Vehicles

Slack httpsmgevhackersslackcom

144 Chapter 14 MG EV

CHAPTER 15

Mitsubishi Trio

Vehicle Type MI

This should be used to support the Mitsubishi i-Miev (Citroen C-Zero Peugeot iOn) vehicles

151 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display NoBMS v+t Display YesTPMS Display Not currently supportedCharge Status Display YesCharge Interruption Alerts YesCharge Control NoCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle Not currently supportedValet Mode Control Not currently supportedOthers

145

Open Vehicles

152 Trio specific metrics

NB Not all metrics are correct or tested properly This is a work in progress

Metric Descriptionxmibpowermin The battery minimum power usagexmibpowermax The battery maximum power usagexmielowbeam Low beam light statusxmiehighbeam High beam light statusxmiefrontfog Front fog light statusxmierearfog Rear fog light statusxmierightblinker Right blinker statusxmieleftblinker Left blinker statusxmiewarninglight Warning light statusxmickwhdc Charge energy on DC side in kWhxmickwhac Charge energy on AC side in kWhxmicefficiency Charge efficiency (DCAC)xmicpowerac Charge power on AC side in kWxmicpowerdc Charge power on DC side in kWxmictime Charge time (hmmss)xmicsocstart Charge start soc in xmicsocstop Charge stop soc in xmieheatingamp Heating energy usage in Axmieheatingwatt Heating energy usage in Wxmieheatingtempreturn Heater return water temperaturexmieheatingtempflow Heater flow water temperaturexmieacamp AC energy usage in Axmieacwatt AC energy usage in Wxmietrippark Trip start odometer in kmxmietripparkenergyused Energy used in kWhxmietripparkenergyrecuperated Recuperated energy in kWhxmietripparkheatingkwh Heater energy usage on trip in kWhxmietripparkackwh AC energy usage on trip in kWhxmietripparksocstart Trip start socxmietripparksocstop Trip stop socxmietripcharge Trip start odometer in km since chargexmietripchargeenergyused Energy used in kWh since chargexmietripchargeenergyrecuperated Recupe energy in kWh since chargexmietripchargeheatingkwh Heating usage in kWh since chargexmietripchargeackwh AC energy usage in kWh since chargexmietripchargesocstart Trip start soc since chargexmietripchargesocstop Trip stop soc since charge

Note that some metrics are polled at different rates than others and some metrics are not available when car is off Thismeans that after a restart of the OVMS some metrics will be missing until the car is turned on and maybe driven forfew minutes

146 Chapter 15 Mitsubishi Trio

Open Vehicles

153 Custom Commands

1531 Read only commands

xmi trip

Returns info about the last trip from you start the car with key

xmi tripc

Returns info about the trip since last charge

xmi aux

Prints out the voltage level of the auxiliary battery

xmi vin

Prints out some more information taken from the cars VIN-number

154 Trio Regen Brake Light Hack

1541 Parts required

bull 1x DA26 Sub-D 26HD Plug amp housing Note housings for Sub-D 15 fit for 26HD eg Assmann-WSW-A-HDS-26-LL-Z Encitech-DPPK15-BK-K-D-SUB-Gehaeuse

bull 1x 12V Universal Car Relay + Socket eg Song-Chuan-896H-1CH-C1-12V-DC-Kfz-Relais GoodSky-Relaissockel-1-St-GRL-CS3770

bull 1x 1 Channel 12V Relay Module With Optocoupler Isolation 12V 1 channel relay module with OptocouplerIsolation

Car wire-tap connectors car crimp connectors 05 mm2 wires zipties shrink-on tube tools

Note if you already use the switched 12V output of the OVMS for something different you can use one of the freeEGPIO outputs That requires additionally routing an EGPIO line to the DA26 connector at the expansion slot (egusing a jumper) and using a relay module (2b relay shield) with separate power input instead of the standard carrelay

I use 2b (relay shield) variant Be aware the MAX71317 outputs are open drain so you need a pull up resistor to eg+33 According to the data sheet the current should stay below 6 mA

Inside OVMS Box Connect JP1 Pin10 (GEP7) to Pin12 (EGPIO_8) with jumper

In DA26 connector

pin 24(+33) ----- [ 680 Ohms ] ---+--- [ Relay board IN ]|

pin 21 (EGPIO_8)pin 9 ----- [Relay board DC+]pin 8 ----- [Relay board DC-][Relay board COM] ----- Brake pedal switch one side[Relay board NO] ----- Brake pedal switch other side

153 Custom Commands 147

Open Vehicles

1542 Configuration

See OVMS web user interface menu Trio rarr Brake Light

Set the port as necessary and the checkbox to enable the brakelight

For monitoring and fine tuning use the bdquoregenmonldquo web plugin httpsgithubcomopenvehiclesOpen-Vehicle-Monitoring-System-3blobmastervehicleOVMSV3componentsovms_webserverdevregenmonhtm

148 Chapter 15 Mitsubishi Trio

Open Vehicles

154 Trio Regen Brake Light Hack 149

Open Vehicles

150 Chapter 15 Mitsubishi Trio

CHAPTER 16

Nissan Leafe-NV200

Vehicle Type NL

This vehicle type supports the Nissan Leaf (24kWh amp 30kWh) and Nissan e-NV200 (24kWh amp 40kWh)

161 Support Overview

1611 Hardware

Item Support StatusModule Any OVMS v3 (or later) module Vehicle support 2011-2017 (24kWh amp 30kWh LEAF 24kWh amp

40KWh e-Nv200 amp custom battery eg Muxsan)VehicleCable

1779000 Nissan Leaf OBD-II to DB9 Data Cable for OVMS

GSM An-tenna

1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)

GPS An-tenna

1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)

1612 Controls

Function Support StatusCharge Control Start and stop chargeCabin Pre-heatcool Control Yes1 (see info below)LockUnlock Vehicle Yes3 (see info below)Valet Mode Control Not currently supported

1 OVMS currently supports 2011-2017 Nissan LEAF and all models of Nissan e-NV2003 LockUnlock will work if CAR can bus is awake this can be activated by turning on AC

151

Open Vehicles

1613 Additional Features

Fea-ture

Description

BMSCellMon-itor

Allows to monitor individual battery cells in a configurable chart Can be accessed from web user interfaceaccessible over WiFi

ChargetoLimit

Allows to automatically stop the charge when target SOC (state of charge) andor range is reached Allparameters can be controlled trough metrics or web user interface Meanwhile Range and SOC can becontrolled from the app as well by adjusting fields 10 (SOC) and 11 (range) in feature section accessibletrough app settings

1614 Metrics

Item Support StatusSOC Yes (by default based on GIDS)4

Range Yes (by default based on GIDS)GPS Location Yes (from modem module GPS)Speed Yes (from vehicle speed PID)Cabin Temperature Yes (from vehicle temperature PIDs)Ambient Temperature Yes (from vehicle temperature PIDs)SetPoint Temperature Yes (from vehicle hvac PIDs)2

HVAC Fan Speed Yes (from vehicle hvac PIDs)2

HVAC HeatingCooling Status Yes (from vehicle hvac PIDs)2

HVAC On Status Yes (from vehicle hvac PIDs)2

HVAC Temperature Setpoint Yes (from vehicle hvac PIDs)2

HVAC Ventilation Mode Yes (from vehicle hvac PIDs)2

BMS v+t YesTPMS Yes (If hardware available)Charge Status YesCharge Interruption Alerts Yes

162 Remote Climate Control

1621 2014-2022 e-NV200 models

OVMS remote climate support will lsquojust workrsquo on e-Nv200 VisiaAcenta which donrsquot have a Nissan satnav headunitFor Tekna models which are fitted with a Nissan satnav headunit follow the instructions below for a 2013-2016 LEAFto unplug the TCU

IMPORTANT for remote climate to work on the e-NV200 the model year in OVMS should be set to 2015 regardlessof the the actual model year of the vehicle CAN writing also needs to be enabled

The model year can be set in the web interface or via the command

4 ZE0 (2011-2013) vehicles are required to choose SoC display from ldquorelative to fixed valuerdquo ldquodashboard displayrdquo SoC method does not workwith these vehicles

2 Some HVAC Status Items have been only verified with 2013-2016 MY cars and will only work if the year is set in configuraiton Also HVACneeds to be in ON position before powering down the vehicle for the metrics to work during pre-heat

152 Chapter 16 Nissan Leafe-NV200

Open Vehicles

config set xnl modelyear 2015

1622 2011-2012 LEAF models (ZE0)

Gen1 LEAFs (ZE0 2011-2012) require a hardware modification to enable remote climate control if the vehicle is notplugged in and charging If you are ok with this you donrsquot need to do anything further

If you want to to enable remote climate control once the charge has finished or if the vehicle is not plugged in youneed to do the following hardware modification A cable wired to the pin 11 of Nissan TCU (Telematics Control Unit)needs to receive +12V so that ldquoEV System Activation Request Signalrdquo can be generated which in turn allows to triggerclimate control independently This can be achieved by wiring the pin 18 (Ext 12V) from the OVMS DA26 socket tothe cable going to pin 11 of the TCU by using a standard single conductor wire The connection on the OVMS DA26side can be made by using dedicated DA26 connector or a standard round 1mm jumper cable Herersquos how to wire itup

Meanwhile on the TCU side the cable can be soldered or spliced in to by using a connector of your choice Whendone the original TCU can be left unplugged See this page for additional pictures

162 Remote Climate Control 153

Open Vehicles

If you have a ldquosmartrdquo EVSE (or one connected to a ldquosmartrdquo outlet you can sometimes wake up the EV system byturning it off then back on This obviously only helps if your vehicle is plugged in but may be useful for some users

1623 2013-2016 LEAF models (AZE0-01)

To use OVMS to activate remote climate the Nissan TCU (Telematics Control Unit) module must be unplugged iffitted eg satnav headunit (only on Acenta and Tekna models) The TCU is located behind the glovebox on LHD carsor on the right hand side of the drivers foot well on RHD cars The large white plug on the rear of the TCU should beunplugged push down tab in the middle and pull to unplug see video for RHD cars and this page for LHD cars

Note Unplugging the TCU will disable Nissan EV connect CARWINGS features eg Nissan mobile app All othercar functions will not be effected eg GPS maps radio Bluetooth microphone all work just the same as beforeOVMS can be used to more than substitute the loss of Nissan Connect features The TCU can be plugged back in atany point in the future if required

OVMS remote climate support will lsquojust workrsquo on LEAF Visia models and VisiaAcenta e-NV200 since these modelsdo not have a TCU fitted In the US these base models are called S

Note If you prefer not to unplug the Nissan TCU all OVMS functions appart from remote climate will function justfine alongside the Nissan TCU

1624 2016-2017 LEAF models (AZE0-2)

Remote climate control will only work when plugged in and actively charging on LEAF 2016-2017 models Thisis because in 2016 Nissan moved the TCU from the EV CAN bus to the CAR CAN bus

Set the model year as follows and if necessary configure 30 kWh model

config set xnl modelyear 2016

or

154 Chapter 16 Nissan Leafe-NV200

Open Vehicles

config set xnl modelyear 2017

Note in latest OVMS fimware version model year and battery size can be set via the web config interface

1625 2018+ models (ZE1)

2018+ 4062kWh LEAF is not yet supported Please get in touch if your interested in helping to add support Relevant2018 CANbus messages have already been decoded and documented see MyNissanLEAF thread

1626 Specific battery configs

For models with a 30 kWhr battery pack set the capacity manually with

config set xnl maxGids 356 config set xnl newCarAh 79

For models with a 40 kWhr battery pack set the capacity manually with

config set xnl maxGids 502 config set xnl newCarAh 115

For models with a 62 kWhr battery pack set the capacity manually with

config set xnl maxGids 775 config set xnl newCarAh 176

Note In latest OVMS firmware version model year and battery size can be set via the web config interface This iseasier and also the preferred method

Note 2 OVMS fully supports battery upgraded LEAFs just set the capacity according to what battery is currentlyinstalled

163 Range Calculation

The OVMS uses two configuration options to calculate remaining range whPerGid (default 80Whgid) and km-PerKWh (default 71kmkWh) The range calculation is based on the remaining gids reported by the LBC and atthe moment does not hold 5 in reserve like LeafSpy Feedback on this calculation is welcomed

164 Resources

bull Nissan LEAF support added by Tom Parker see his wiki for lots of documentation and resources Some info isoutdated eg climate control now turns off automatically

bull Nissan LEAF features are being added by Jaunius Kapkan see his github profile to track the progress

bull MyNissanLEAF thread for Nissan CANbus decoding discussion

bull Database files (DBC) for ZE0 and AZE0 Leaf can be found here Github LEAF Canbus database files

Assistance is appreciated as I havenrsquot had time to try to override the TCU using the OVMS or find an alternativesolution to prevent the TCU overriding the messages while still allowing the hands free microphone to work

163 Range Calculation 155

Open Vehicles

156 Chapter 16 Nissan Leafe-NV200

CHAPTER 17

OBDII Vehicles

Vehicle Type O2

Support for generic OBDII is provided by this module

157

Open Vehicles

171 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support Not widely tested but should be all that

support OBDII standard PIDs over CAN busVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display Yes (based on fuel level PID)Range Display NoGPS Location Yes (from modem module GPS)Speed Display Yes (from vehicle speed PID)Temperature Dis-play

Yes (from vehicle temperature PIDs)

BMS v+t Display NoTPMS Display NoCharge Status Dis-play

No

Charge Interrup-tion Alerts

No

Charge Control NoCabin Pre-heatcool Control

No

LockUnlockVehicle

No

Valet Mode Con-trol

No

Others VIN and RPMs should be available

158 Chapter 17 OBDII Vehicles

CHAPTER 18

Renault Twizy

Vehicle Type RT

159

Open Vehicles

181 Support Overview

Function Support StatusHardware No specific requirements (except for regen brake light

control see below)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right

or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any

compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or

any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display YesBMS v+t Display YesTPMS Display NoCharge Status Display YesCharge Interruption Alerts YesCharge Control Current limit stop SOCrange limitCabin Pre-heatcool Control NoLockUnlock Vehicle Mapped to dynamic speed lockValet Mode Control Mapped to odometer based speed lockOthers

bull Battery amp motor power amp energy monitoringbull Battery health amp capacitybull SEVCON monitoring amp tuning (Note tuning

only SC firmware lt= 07120002 ~072016)bull Kickdownbull Auto power adjustbull Regen brake lightbull Extended trip amp GPS logging

Note regarding the Twizy V3 works very similar to V2 All telemetry data tables and tuning profiles are fullycompatible and the commands are very similar Therefore the basic descriptions and background info from the V2manual are valid for V3 as well

bull V2 FAQ (english)

bull V2 FAQ (german)

bull V2 documents directory

bull V2 user manual (PDF)

182 Hints on V3 commands vs V2

bull V3 commands need to be in lower case

bull When accessing via USB terminal first issue enable (login)

bull V3 commands are similar to V2 commands just structured slightly different

160 Chapter 18 Renault Twizy

Open Vehicles

bull Try help and xrt Twizy commands are subcommands of xrt

bull TAB only works via USB SSH Shortcuts can be used generally eg mo t instead of module tasks

bull A usage info is shown if a command syntax is wrong or incomplete

183 Contents

1831 Configuration

The Twizy configuration is stored in the OVMS config parameter (section) xrt To list the current values issue

config list xrt

For reference the following table includes the equivalent OVMS V2 feature or parameter number amp bit value whereapplicable You may use the parameter amp feature editors on the App (values are mapped) the commands have beenmerged into the config command in V3

183 Contents 161

Open Vehicles

Config instancename

Examplevalue

V2FP

Description

autopower yes F158 Bool SEVCON automatic power level adjustment (Default yes)autoreset yes F152 Bool SEVCON reset on error (Default yes)aux_charger_port 0 ndash EGPIO port to control auxiliary charger (Default 0 = disabled)aux_fan_port 0 ndash EGPIO port to control auxiliary charger fan (Default 0 = disabled)canwrite yes F151 Bool CAN write enabled (Default no)cap_act_prc 822288 F13 Battery actual capacity level [] (Default 1000)cap_nom_ah 108 ndash Battery nominal capacity [Ah] (Default 1080)chargelevel 0 F7 Charge power level [1-7] (Default 0=unlimited)chargemode 0 F6 Charge mode 0=notify 1=stop at sufficient SOCrange (Default 0)console no F1516 -unused- (reserved for possible V3 SimpleConsole presence)dtc_autoreset no ndash Reset DTC statistics on every drivecharge start (Default no)gpslogint 5 (F8) Seconds between RT-GPS-Log entries while driving (Default 0 =

disabled)kd_compzero 120 F2 Kickdown pedal compensation (Default 120)kd_threshold 35 F1 Kickdown threshold (Default 35)kickdown yes F154 Bool SEVCON automatic kickdown (Default yes)lock_on 6 ndash Speed limit [kph] to engage lock mode at (Default undefined = off)maxrange 55 F12 Maximum ideal range at 20 degC [km] (Default 80)motor_rpm_rated 2050 ndash Powermap V3 control rated speed [RPM] (Default 0 = V2)mo-tor_trq_breakdown

210375 ndash Powermap V3 control breakdown torque [Nm] (Default 0 = V2)

profileNN XaZwt5ehZQ (P16-21)

Tuning profile NN [NN=01 99] base64 code

profileNNlabel PWR ndash button labelprofileNNtitle Power ndash titleprofile_buttons 0123 ndash Tuning drivemode button configurationprofile_cfgmode 2 ndash Tuning profile last loaded in config (pre-op) modeprofile_user 2 P15 Tuning profile last loaded in user (op) modesuffrange 0 F11 Sufficient range [km] (Default 0=disabled)suffsoc 80 F10 Sufficient SOC [] (Default 0=disabled)type ndash ndash Twizy custom SEVCONGearbox type [SC80GB45SC45GB80]

(Default - = auto detect)valet_on 123456 ndash Odometer limit [km] to engage valet mode at (Default undefined =

off)

1832 Custom Metrics

Metric name Example value Descriptioncocan1nd1emcycode SEVCON emergency codecocan1nd1emcytype SEVCON emergendy typecocan1nd1state Operational SEVCON state (preopop)xrtbusocmax 7052 Current tripcharge pack SOC maxxrtbusocmin 508 Current tripcharge pack SOC minxrtbutempmax 20degC Current tripcharge pack temp maxxrtbutempmin 181429degC Current tripcharge pack temp minxrtbuvoltmax 55V Current tripcharge pack volt maxxrtbuvoltmin 502V Current tripcharge pack volt min

Continued on next page

162 Chapter 18 Renault Twizy

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxrtbmsbalancing 248101314 Custom BMS cell balancing statusxrtbmserror 0 Custom BMS error statusxrtbmsstate1 4 Custom BMS main statexrtbmsstate2 1 Custom BMS auxiliary statexrtbmstemp 52degC Custom BMS internal temperaturexrtbmstype 1 Custom BMS type (0=VirtualBMS 1=eDriver BMS 7=Standard)xrtcfgapplied yes Tuning working set has been applied to SEVCONxrtcfgbase 2 Tuning base profile (preop mode params)xrtcfgprofile 144110111182 Tuning profile paramsxrtcfgtype Twizy80 Tuning vehicle typexrtcfgunsaved yes Tuning working set has unsaved changesxrtcfguser 2 Tuning userlive profile (op mode params)xrtcfgws 0 Tuning profile last loaded into working setxrticuract 0A SC monitor motor current levelxrtifrqoutput 0 SC monitor motor output frequencyxrtifrqslip 0 SC monitor motor slip frequencyxrtipwract 0kW SC monitor motor power levelxrtitrqact 0 SC monitor motor torque levelxrtitrqdemand 0 SC monitor motor torque demandxrtitrqlimit 0 SC monitor motor torque limitxrtivltact 0V SC monitor output voltage level (motor)xrtivltbat 0 SC monitor input voltage level (battery)xrtivltcap 0A SC monitor capacitor voltage levelxrtivltmod 0 SC monitor motor modulation factorxrtmversion 124 Sep 17 2019 OVMS Twizy component versionxrtpstatsaccdist 06267km Power stats accelerating distancexrtpstatsaccrecd 130133e-05kWh Power stats accelerating energy recoveredxrtpstatsaccspdavg 27kmhs Power stats accelerating speed averagexrtpstatsaccused 017692kWh Power stats accelerating energy usedxrtpstatscstdist 05331km Power stats coasting distancexrtpstatscstrecd 423289e-05kWh Power stats coasting energy recoveredxrtpstatscstspdavg 2618kmh Power stats coasting speed averagexrtpstatscstused 009703kWh Power stats coasting energy usedxrtpstatsdecdist 05436km Power stats decelerating distancexrtpstatsdecrecd 00140886kWh Power stats decelerating energy recoveredxrtpstatsdecspdavg 26kmhs Power stats decelerating speed averagexrtpstatsdecused 00379027kWh Power stats decelerating energy usedxrtpstatsldndist 02km Power stats downwards distancexrtpstatsldnhsum 3m Power stats downwards height sumxrtpstatsldnrecd 000300565kWh Power stats downwards energy recoveredxrtpstatsldnused 00356104kWh Power stats downwards energy usedxrtpstatslupdist 131km Power stats upwards distancexrtpstatsluphsum 66m Power stats upwards height sumxrtpstatsluprecd 0010866kWh Power stats upwards energy recoveredxrtpstatslupused 0263831kWh Power stats upwards energy usedxrtsbpwrdrv SC monitor virtual dyno drive power levelsxrtsbpwrrec SC monitor virtual dyno recup power levelsxrtsmtrqdrv SC monitor virtual dyno drive torque levelsxrtsmtrqrec SC monitor virtual dyno recup torque levels

Continued on next page

183 Contents 163

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxrtvbalert12v no Display service indicator 12V alertxrtvbalertbatt no Display service indicator Battery alertxrtvbalerttemp no Display service indicator Temperature alertxrtvbstatus 0 Internal BMS status (CAN frame 628)xrtvcstatus 0 Internal Charger status (CAN frame 627)xrtvistatus 0 Internal SEVCON status (CAN frame 629)xrtvelockedspeed 0 Speed limit [kph] set for Twizy lock modexrtvevaletodo 0 Odometer limit [km] set for Twizy valet mode

1833 Events

The Renault Twizy module emits these specific events additionally to the general OVMS events

Event Data Purposevehiclechargesubstatescheduledstop Charge stopped by user request (command)vehiclectrlcfgmode SEVCON in configuration mode (preop)vehiclectrlloggedin SEVCON session establishedvehiclectrlrunmode SEVCON in normal mode (op)vehicledrivemodechanged SEVCON tuning profile changedvehicledtcpresent ltdtc_descrgt OBD2 DTC (diagnostic trouble code) presentvehicledtcstored ltdtc_descrgt OBD2 DTC storedvehiclefaultcode ltcodegt SEVCON fault code receivedvehiclekickdownengaged Kickdown detected drive power changedvehiclekickdownreleased Kickdown mode end normal power restoredvehiclekickdownreleasing Kickdown mode about to end

1834 Custom Commands

Note This is currently just a brief overview to feed the search engine See each commandrsquos usage info and whereapplicable corresponding V2 manual entries on details

bull V3 commands need to be in lower case

bull When accessing via USB terminal first issue enable (login)

bull V3 commands are similar to V2 commands just structured slightly different

bull Try help and xrt Twizy commands are subcommands of xrt

bull TAB only works via USB SSH Shortcuts can be used generally eg mo t instead of module tasks

bull A usage info is shown if a command syntax is wrong or incomplete

OVMS xrt batt Battery monitorca Charge attributescfg SEVCON tuningdtc Show DTC report clear DTCmon SEVCON monitoringobd OBD2 toolspower Powerenergy info

164 Chapter 18 Renault Twizy

Open Vehicles

Battery Monitor

OVMS xrt batt data-cell Output cell recorddata-pack Output pack recordreset Reset alerts amp watchesstatus Status reporttdev Show temperature deviationstemp Show temperaturesvdev Show voltage deviationsvolt Show voltages

Note Also see standard BMS commands (bms )

Charge Attributes

OVMS xrt ca Usage xrt ca [R] | [ltrangegt] [ltsocgt] [Llt0-7gt] [S|N|H]

Note Also see standard charge control commands (charge )

SEVCON Tuning

OVMS xrt cfg brakelight Tune brakelight trigger levelsclearlogs Clear SEVCON diag logsdrive Tune drive power levelget Get tuning profile as base64 stringinfo Show tuning profileload Load stored tuning profileop Leave configuration mode (go operational)power Tune torque power amp current levelspre Enter configuration mode (pre-operational)querylogs Send SEVCON diag logs to serverramplimits Tune max pedal reactionramps Tune pedal reactionread Read registerrecup Tune recuperation power levelsreset Reset tuning profilesave Save current tuning profileset Set tuning profile from base64 stringshowlogs Display SEVCON diag logssmooth Tune pedal smoothingspeed Tune max amp warn speedtsmap Tune torquespeed mapswrite Read amp write registerwriteonly Write register

183 Contents 165

Open Vehicles

Show DTC Report Clear DTC

OVMS xrt dtc clear Clear stored DTC in carreset Reset OVMS DTC statisticsshow Show DTC report

SEVCON Monitoring

OVMS xrt mon reset Reset monitoringstart Start monitoringstop Stop monitoring

OBD2 Tools

OVMS xrt obd request Send OBD2 request output responseOVMS xrt obd request bms Send OBD2 request to BMSbroadcast Send OBD2 request as broadcastcharger Send OBD2 request to charger (BCB)cluster Send OBD2 request to cluster (display)device Send OBD2 request to a device

PowerEnergy Info

OVMS xrt power report Trip efficiency reportstats Generate RT-PWR-Stats entrytotals Power totals

1835 Notifications

The Renault Twizy module sends the custom or customized notifications described here additionally to the systemnotifications

See Notifications for general info on notifications

166 Chapter 18 Renault Twizy

Open Vehicles

Type Subtype Purpose Contentalert batterystatus Battery packcell alert status report (alerts amp watches)alert bmsstatus Battery management system alert (for custom BMS only)info chargestatussufficient Sufficient charge reached (SOCrange as configured)alert valetmodeodolimit Odometer limit reached speed reduction engagedalert vehicledtc OBD2 DTC (diagnostic trouble code) alertdata xrtbatterylog Battery packcell monitoring logdata xrtgpslog Extended GPS logdata xrtobdclusterdtc OBD2 DTC log for cluster (displayUCH)data xrtpowerdyno SEVCON live monitoring (virtual dyno) datadata xrtpowerlog Power statisticsinfo xrtpowertotals Current usage cycle power totalsdata xrttriplog Trip history loginfo xrttripreport Trip energy usage reportalert xrtsevconfault SEVCON fault condition detecteddata xrtsevconlog SEVCON faults amp events logsinfo xrtsevconprofilereset A tuning RESET has been performedinfo xrtsevconprofileswitch Tuning profile switch result

Trip history log

The trip history log can be used as a source for long term statistics on your trips and typical trip power usages as wellas your battery performance in different environmental conditions and degradation over time

Entries are created at the end of a trip and on each change in the charge state so you can also see where chargesstopped or how long they took and how high the temperatures got

bull Notification subtype xrttriplog

bull History record type RT-PWR-Log

bull Format CSV

bull Maximum archive time 365 days

bull Fieldscolumns

ndash odometer_km

ndash latitude

ndash longitude

ndash altitude

ndash chargestate

ndash parktime_min

ndash soc

ndash soc_min

ndash soc_max

ndash power_used_wh

ndash power_recd_wh

ndash power_distance

183 Contents 167

Open Vehicles

ndash range_estim_km

ndash range_ideal_km

ndash batt_volt

ndash batt_volt_min

ndash batt_volt_max

ndash batt_temp

ndash batt_temp_min

ndash batt_temp_max

ndash motor_temp

ndash pem_temp

ndash trip_length_km

ndash trip_soc_usage

ndash trip_avg_speed_kph

ndash trip_avg_accel_kps

ndash trip_avg_decel_kps

ndash charge_used_ah

ndash charge_recd_ah

ndash batt_capacity_prc

ndash chg_temp

Extended GPS log

The extended GPS log contains additional details about power and current levels the BMS power limits and theautomatic power level adjustments done by the OVMS You can use this to create detailed trip power charts and toverify your auto power adjust settings

The log frequency is once per minute while parkingcharging and controlled by config xrt gpslogint (web UITwizy rarr Features) while driving Logging only occurs if logged metrics have changed

bull Notification subtype xrtgpslog

bull History record type RT-GPS-Log

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash odometer_mi_10th

ndash latitude

ndash longitude

ndash altitude

ndash direction

ndash speed

168 Chapter 18 Renault Twizy

Open Vehicles

ndash gps_fix

ndash gps_stale_cnt

ndash gsm_signal

ndash current_power_w

ndash power_used_wh

ndash power_recd_wh

ndash power_distance

ndash min_power_w

ndash max_power_w

ndash car_status

ndash max_drive_pwr_w

ndash max_recup_pwr_w

ndash autodrive_level

ndash autorecup_level

ndash min_current_a

ndash max_current_a

Battery packcell monitoring log

The extended GPS log contains additional details about power and current levels the BMS power limits and theautomatic power level adjustments done by the OVMS You can use this to create detailed trip power charts and toverify your auto power adjust settings

The standard log frequency is once per minute logging only occurs if logged metrics have changed Additionalrecords are created on battery alert events Note an entry consists of a pack level record (RT-BAT-P) and up to 16(for LiFePO4 batteries) cell entries (RT-BAT-C)

bull Notification subtype xrtbatterylog

bull History record type RT-BAT-P (pack status)

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash packnr

ndash volt_alertstatus

ndash temp_alertstatus

ndash soc

ndash soc_min

ndash soc_max

ndash volt_act

ndash volt_min

183 Contents 169

Open Vehicles

ndash volt_max

ndash temp_act

ndash temp_min

ndash temp_max

ndash cell_volt_stddev_max

ndash cmod_temp_stddev_max

ndash max_drive_pwr

ndash max_recup_pwr

ndash bms_state1

ndash bms_state2

ndash bms_error

ndash bms_temp

bull Notification subtype xrtbatterylog

bull History record type RT-BAT-C (cell status)

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash cellnr

ndash volt_alertstatus

ndash temp_alertstatus

ndash volt_act

ndash volt_min

ndash volt_max

ndash volt_maxdev

ndash temp_act

ndash temp_min

ndash temp_max

ndash temp_maxdev

ndash balancing

ndash been_balancing

ndash balancetime

Power statistics

The power statistics are the base for the trip reports and can be used to analyze trip sections regarding speed andaltitude changes and their respective effects on power usage The log is also written when charging that data can beused to log changes in the charge current for example triggered externally by some solar charge controller

Log frequency is once per minute logging only occurs if metrics have changed

170 Chapter 18 Renault Twizy

Open Vehicles

bull Notification subtype xrtpowerlog

bull History record type RT-PWR-Stats

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash speed_const_dist

ndash speed_const_use

ndash speed_const_rec

ndash speed_const_cnt

ndash speed_const_sum

ndash speed_accel_dist

ndash speed_accel_use

ndash speed_accel_rec

ndash speed_accel_cnt

ndash speed_accel_sum

ndash speed_decel_dist

ndash speed_decel_use

ndash speed_decel_rec

ndash speed_decel_cnt

ndash speed_decel_sum

ndash level_up_dist

ndash level_up_hsum

ndash level_up_use

ndash level_up_rec

ndash level_down_dist

ndash level_down_hsum

ndash level_down_use

ndash level_down_rec

ndash charge_used

ndash charge_recd

OBD2 cluster DTC log

This server table stores DTC occurrences for one week This is mostly raw data and the DTCs are internal Renaultvalues that have not yet been decoded

See httpswwwtwizy-forumdeovms86362-liste-df-codes-dtc

bull Notification subtype xrtobdclusterdtc

183 Contents 171

Open Vehicles

bull History record type RT-OBD-ClusterDTC

bull Format CSV

bull Maximum archive time 7 days

bull Fieldscolumns

ndash EntryNr

ndash EcuName

ndash NumDTC

ndash Revision

ndash FailPresentCnt

ndash G1

ndash G2

ndash ServKey

ndash Customer

ndash Memorize

ndash Bt

ndash Ef

ndash Dc

ndash DNS

ndash Odometer

ndash Speed

ndash SOC

ndash BattV

ndash TimeCounter

ndash IgnitionCycle

SEVCON faults amp events

These logs are created on request only eg by the SEVCON logs tool in the Android App or by using the xrt cfgquerylogs command The command queries the SEVCON (inverter) alerts faults events and statistics (SEVCONneeds to be online) The results are then transmitted to the server using the following records

bull Notification subtype xrtsevconlog

bull History record type RT-ENG-LogKeyTime

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash KeyHour

ndash KeyMinSec

bull Notification subtype xrtsevconlog

172 Chapter 18 Renault Twizy

Open Vehicles

bull History record type RT-ENG-LogAlerts

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash Code

ndash Description

ndash TimeHour

ndash TimeMinSec

ndash Data1

ndash Data2

ndash Data3

bull Notification subtype xrtsevconlog

bull History record type RT-ENG-LogSystem

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash Code

ndash Description

ndash TimeHour

ndash TimeMinSec

ndash Data1

ndash Data2

ndash Data3

bull Notification subtype xrtsevconlog

bull History record type RT-ENG-LogCounts

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash Code

ndash Description

ndash LastTimeHour

ndash LastTimeMinSec

ndash FirstTimeHour

ndash FirstTimeMinSec

ndash Count

bull Notification subtype xrtsevconlog

183 Contents 173

Open Vehicles

bull History record type RT-ENG-LogMinMax

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash BatteryVoltageMin

ndash BatteryVoltageMax

ndash CapacitorVoltageMin

ndash CapacitorVoltageMax

ndash MotorCurrentMin

ndash MotorCurrentMax

ndash MotorSpeedMin

ndash MotorSpeedMax

ndash DeviceTempMin

ndash DeviceTempMax

SEVCON live monitoring

These records store the measurement results of the virtual dyno included in the SEVCON live monitor (Twizy rarrSEVCON Monitor) The virtual dyno records a torquepower profile from the actual car performance during drivingThe profile has four data sets

bull Maximum battery drive power over speed (metric xrtsbpwrdrv unit kW)

bull Maximum battery recuperation power over speed (metric xrtsbpwrrec unit kW)

bull Maximum motor drive torque over speed (metric xrtsmtrqdrv unit Nm)

bull Maximum motor recuperation torque over speed (metric xrtsmtrqrec unit Nm)

Power is measured at the battery so you can derive the efficiency Speed is truncated to integer the value arrays takeup to 120 entries (0 119 kph)

These datasets are visualized by the web UI using a chart and transmitted to the server on any monitoring ldquostoprdquo orldquoresetrdquo command in the following records

bull Notification subtype xrtpowerdyno

bull History record types RT-ENG-BatPwrDrv RT-ENG-BatPwrRec RT-ENG-MotTrqDrvRT-ENG-MotTrqRec

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns max 120 values for speed levels beginning at 0 kph

1836 Twizy Regen Brake Light Hack

174 Chapter 18 Renault Twizy

Open Vehicles

Why

The Twizy recuperation levels are very low by default regenerative braking is so weak it doesnlsquot need to trigger thebrake light ndash so a regen braking indication has been omitted by Renault The Twizy can be tuned to one pedal drivingthough with high neutral braking power

The SEVCON normally can generate a regen braking signal itself That signal can be configured using the xrt cfgbrakelight tuning command Pin 11 on the SEVCON main connector will go to GND on activation The problemis that pin is not connected on the Twizy using it needs modification of the connector To my knowledge this hasnlsquotbeen done successfully up to now so we donlsquot even know if the Twizy SEVCON firmware includes that functionality

How does it work

The OVMS generates a secondary regen braking signal itself That signal is used to control a relay to provide powerto the brake light independant of the brake pedal

Integration is simple and does not require to change the existing connections

The Twizy UCHdisplay recognizes the regen brake light activation despite the foot brake being pushed and turns onthe SERV indicator Depending on your preferences you may see this as a problem or as an indicator for the regenbraking

Switching the 65A line does not avoid the SERV indicator (tested) Most probably the brake light is monitored by thecurrent flowing at the fuse box so the SERV indicator cannot be avoided without changing that system

Parts required

1 1x DA26 Sub-D 26HD Plug amp housing

bull Note housings for Sub-D 15 fit for 26HD

bull eg Assmann-WSW-A-HDS-26-LL-Z

183 Contents 175

Open Vehicles

bull Encitech-DPPK15-BK-K-D-SUB-Gehaeuse

2 1x 12V Universal Car Relay + Socket

bull eg Song-Chuan-896H-1CH-C1-12V-DC-Kfz-Relais

bull GoodSky-Relaissockel-1-St-GRL-CS3770

3 Car wire-tap connectors car crimp connectors 05 mm2 wires zipties shrink-on tube tools

Note if you already use the switched 12V output of the OVMS for something different you can use one of the freeEGPIO outputs That requires additionally routing an EGPIO line to the DA26 connector at the expansion slot (egusing a jumper) and using a relay module (relay shield) with separate power input instead of the standard car relay

Build

1 Solder ~ 40 cm two-core wire to the DA26 plug pins 8 (GND) and 18 (+12V switched) use shrink-on tubes toprotect the terminals mount the housing

2 Crimp 63mm sockets to the other ends of the wire isolate using shrink-on tube crimp 63mm plugs to the relaycoil (pins 85 + 86) isolate using shrink-on tube

176 Chapter 18 Renault Twizy

Open Vehicles

3 Extend the relay switch terminals by ~ 30 cm wires crimp on plugs for the tap connectors

4 Unmount the Twizy glovebox locate the red wire on the right above the parking brake

183 Contents 177

Open Vehicles

5 Crimp a tap connector onto the red wire and connect it to the relay (pin 30)

178 Chapter 18 Renault Twizy

Open Vehicles

6 Connect switched +12V likewise to pin 87 of the relay

bull +12V may be taken from the radio or 12V aux socket to simplify things

bull the dedicated brake light supply is fuse no 23 which is very hard to reach without dismounting the whole fuseholder

7 Place the relay in the free area on the upper left of the fuse holder (not below the door dampener that may crushthe relay) secure the relay using a ziptie

8 Pull the OVMS DIAG cable through the glovebox bottom hole and connect it to the relay inputs (pins 8586polarity doesnlsquot matter)

9 Do a test plug in the OVMS (Note the relay switches on during the first OVMS boot) switch on the Twizyissue commands

bull egpio output 1 1 should activate the brakelight

bull egpio output 1 0 should deactivate the brakelight

bull Note if youlsquore using another EGPIO port use the according port number (3-9) instead

10 Mount the glovebox and youlsquore done

Configuration

See OVMS web user interface menu Twizy rarr Brake Light

183 Contents 179

Open Vehicles

Set the port as necessary and the checkbox to enable the brakelight

For monitoring and fine tuning use the regenmon web plugin

httpsgithubcomopenvehiclesOpen-Vehicle-Monitoring-System-3blobmastervehicleOVMSV3componentsovms_webserverdevregenmonhtm

1837 Auxiliary Charge Fan

The builtin Elips 2000W chargerrsquos officially specified temperature operation range is -20+50 degC This is exceededby the Twizy easily even on moderate summer days The charger temperature can easily rise above 60 degC and this is

180 Chapter 18 Renault Twizy

Open Vehicles

possibly the main reason why Twizy chargers eventually die It also leads to the Twizy reducing the maximum chargepower available resulting in charges taking much longer than usual

A counter measure can be to add an additional fan to cool the charger and switch that fan on as necessary (seebelow) The fan can be controlled using one of the OVMS EGPIO output ports (see EGPIO) The easiest way is to usethe switched 12V supply available at the DA26 expansion plug without additional hardware The 12V port can delivera nominal output of 25W or 18A and up to 40W or 29A short term so can be used to power many auxiliary fansdirectly

To enable the auxiliary fan simply configure the EGPIO to be used in config parameter xrt aux_fan_port Forexample to use the switched 12V port = EGPIO port 1 do

OVMS config set xrt aux_fan_port 1

Set the port to 0 to disable the feature

Mode of operation

bull The OVMS continously monitors the charger temperature It turns on the fan when the charger temperaturerises above 45 degC (gt= 46 degC) and off when the temperature drops below 45 degC (lt= 44 degC)

bull After end of charge (Twizy system switched off) the OVMS does not get temperature updates so it keeps thefan running for another 5 minutes

The fan control works during charging and driving as during driving the charger also has to supply +12V by thebuiltin DCDC converter (heating up the charger) and a trip may start with an already hot charger

1838 Auxiliary Charger

The Elips 2000W (as the name says) does only charge with ~2 kW thus needing 3-35 hours to charge the originalTwizy battery Thatlsquos quite slow and gets worse when replacing the battery by a larger one

The Elips is running a special Renault firmware and also taking a crucial role in the Twizy system communication forexample to control the BMS So it cannot easily be replaced by a third party charger

But a third party charger can run in parallel to the Elips to boost the charge power This can be done best fromthe ldquorear endrdquo ie using the battery main connector as the power input (like the SEVCON does during regenerativebraking)

Some documented examples of additional chargers

bull httpswwwtwizy-forumdewerkstatt-twizy84935-twizy-schnelllader

bull httpswwwtwizy-forumdeprojekte-twizy83603-schnell-lader-extern

bull httpswwwtwizy-forumdetipps-und-tricks-twizy80814-twizy-schnellladen-die-wave-kann-kommen

The caveat to avoid damaging the battery additional charge power should not be supplied when the battery is nearlyfull So the additional charger needs to be switched off before the main charger finishes

The OVMS can automate switching the additional charger both on and off Any of the available EGPIO output ports(see EGPIO) can be used for this task If the charger has no digital power control input a convenient way is to use theswitched 12V supply available at the DA26 expansion plug without additional hardware The 12V port can deliver anominal output of 25W or 18A and up to 40W or 29A short term so can be used to power a standard automotiverelay directly

Configuration

Simply set the EGPIO to be used in config parameter xrt aux_charger_port For example to use the switched12V port = EGPIO port 1 do

183 Contents 181

Open Vehicles

OVMS config set xrt aux_charger_port 1

Set the port to 0 to disable the feature

Mode of operation

bull The port is switched ON when the Twizy charges is below 94 SOC is still within the CC phase (ie nottopping off balancing) and the charge current is not under user control

bull The port is switched OFF when the Twizy stops charging reaches 94 SOC or enters the topping off phase(whichever comes first) or when you set a custom charge current

Charge current control

If you set the charge current to level 7 (35 A) only the original charger will run but at full power You can set levels6 1 (30 5 A) to reduce the charge power only using the Elips charger Setting the current to level 0 (no chargethrottling) will allow maximum charge current from the Elips charger and additionally enable the second charger

182 Chapter 18 Renault Twizy

CHAPTER 19

Renault Zoe

Vehicle Type RZ

This vehicle type supports the Renault Zoe(PH1) and Kangoo(2011 - ~2019) The newer Zoe ph2 and Kangoo are notsupported yet

191 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display Yes (External Temp and Battery)BMS v+t Display YesTPMS Display Zoe Yes (pressure only)TPMS Display Kangoo NoCharge Status Display YesCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

After selecting the Renault ZoeKangoo vehicle module the corresponding settings have to be made in the web inter-face via the ldquoRenault ZoeKangoordquo menu under ldquoFeaturesrdquo

183

Open Vehicles

184 Chapter 19 Renault Zoe

CHAPTER 20

Smart ED Gen3

Vehicle Type SE

The Smart ED will be documented here

201 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display NoCharge Status Display YesCharge Interruption Alerts YesCharge Control Current limitCabin Pre-heatcool Control When charging and CAN-Bus ActiveLockUnlock Vehicle NoValet Mode Control NoOthers

185

Open Vehicles

202 Contents

2021 Custom Metrics

Metric name Example value DescriptionxsemybmsHWrev 12380 BMS hardware-revision year week patchlevelxsemybmsSWrev 12351 BMS soft-revision year week patchlevelxsemybmsadccvoltsmax 4171 maximum cell voltages in mV add offset +1500xsemybmsadccvoltsmean 4165 average cell voltage in mV no offsetxsemybmsadccvoltsmin 4145 minimum cell voltages in mV add offset +1500xsemybmsadcvoltsoffset 103 calculated offset between RAW cell voltages and ADCref about 90mVxsemybmsamps 65483A battery current in ampere (x32) reported by by BMSxsemybmsamps2 204634A battery current in ampere read by live data on CAN or from BMSxsemybmsbattvin WME4513901K661441 VIN stored in BMSxsemybmsdcfault 0 Flag to show DC-isolation faultxsemybmshv total voltage of HV system in Vxsemybmshvcontactcyclesleft 281991 counter related to ONOFF cyles of the carxsemybmshvcontactcyclesmax 300000 static seems to be maxiumum of contactor cyclesxsemybmsisolation 10239 Isolation in DC path resistance in kOhmxsemybmspower 794186kW power as product of voltage and amps in kWxsevbccapacity 184911853618536 Cell capacity [As]xsevbccapacitydevmax 451901901 Cell maximum capacity deviation observed [As]xsevbccapacitymax 184911853618536 Cell maximum capacity [As]xsevbccapacitymin 184911853618536 Cell minimum capacity [As]xsevbenergyusedreset 1634kWh Energy used Reset (Dashbord)xsevbenergyusedstart 169kWh Energy used Start (Dashbord)xsevbhvactive no HV Batterie Statusxsevbpcapacityasaverage 18625 cell capacity statistics from BMS measurement cyclexsevbpcapacityasmaximum 19193 cell capacity statistics from BMS measurement cyclexsevbpcapacityasminimum 18843 cell capacity statistics from BMS measurement cyclexsevbpcapacityavg 184459 Cell capacity - pack average [As]xsevbpcapacitycombinedquality 0515328 some sort of estimation factor constantly updatedxsevbpcapacitymax 18670 Cell capacity - strongest cell in pack [As]xsevbpcapacitymaxcell 9 Cell capacity - number of strongest cell in packxsevbpcapacitymin 18229 Cell capacity - weakest cell in pack [As]xsevbpcapacitymincell 59 Cell capacity - number of weakest cell in packxsevbpcapacityquality 0742092 some sort of estimation factor after measurement cyclexsevbpcapacitystddev 908 Cell capacity - current standard deviation [As]xsevbpcapacitystddevmax 908 Cell capacity - maximum standard deviation observed [As]xsevbphvlowcurrent 0Sec counter time of no current reset eg with PLC heater or drivingxsevbphvofftime 0Sec HighVoltage contactor off time in secondsxsevbplastmeasdays 13 days elapsed since last successful measurementxsevbpocvtimer 2676Sec counter time in seconds to reach OCV statexsevbpvoltagemaxcell 1 Cell volatage - number of strongest cell in packxsevbpvoltagemincell 5 Cell volatage - number of weakest cell in packxsevbrealsoc 978 real state of chargexsevbusawake no CAN-Bus Statusxsevcactive no Charging Statusxsevdisplaytime 738Min Dashbord Timexsevdisplaytripreset 27332km Dashbord Trip value at Reset

Continued on next page

186 Chapter 20 Smart ED Gen3

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxsevdisplaytripstart 175km Dashbord Trip value at Startxsevnlg6ampscablecode 0A Onboard Charger Ampere Cablexsevnlg6ampschargingpoint 0A Onboard Charger Ampere xsevnlg6ampssetpoint 41A Onboard Charger Ampere setpointxsevnlg6dccurrent 0A Onboard Charger LV current Amperexsevnlg6dchv 0V Onboard Charger HV Voltagexsevnlg6dclv 135V Onboard Charger LV Voltagexsevnlg6mainamps 000A Onboard Charger main Phasen Amperexsevnlg6mainvolts 000V Onboard Charger main Phasen Voltagexsevnlg6pnhw 4519820621 Onboard Charger Hardware Serial Noxsevnlg6present no Onboard Charger OBL or NLG6 presentxsevnlg6tempcoolingplate 0degC Onboard Charger coolingplate Temperaturexsevnlg6tempreported 0degC Onboard Charger reported Temperaturexsevnlg6tempsocket 0degC Onboard Charger socket Temperaturexsevnlg6temps Onboard Charger Temperaturesxsevposodometerstart 41940km Odo at last Ignition on For Trip calc Valuexsevdisplayaccel 89 Eco score on acceleration over last 6 hoursxsevdisplayconst 18 Eco score on constant driving over last 6 hoursxsevdisplaycoast 100 Eco score on coasting over last 6 hoursxsevdisplayecoscore 69 Eco score shown on dashboard over last 6 hours

2022 Custom Commands

xse trip

show last Trip value

xse recu up

xse recu down

set Rekuperation up or down Works only if Rekuperation is enabled in car

xse charge

set charge and leave Time

Example

xse charge 7 15 off

set Time at 715 clock with pre climate off

xse charge 9 55 on

set Time at 955 clock with pre climate on

2023 BMS Diagnose Tool

xse rptdata get a Battery Status Report

xse bmsdiag get Battery Diagnose Report

Original Tool ED BMSdiag

description DE

description EN

202 Contents 187

Open Vehicles

188 Chapter 20 Smart ED Gen3

CHAPTER 21

Smart EDEQ Gen4 (453)

Vehicle Type SQ

The Smart EDEQ Gen4 will be documented here

211 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display Yes (External Temp and Battery)BMS v+t Display only Cell Volts atmTPMS Display NoCharge Status Display YesCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

189

Open Vehicles

190 Chapter 21 Smart EDEQ Gen4 (453)

CHAPTER 22

Tesla Model 3

Vehicle Type T3

At present support for the Tesla Model 3 in OVMS is experimental and under development This vehicle type shouldnot be used by anyone other than those actively involved in development of support for this vehicle

221 Support Overview

Function Support StatusHardware tbaVehicle Cable tbaGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna tbaSOC Display tbaRange Display tbaGPS Location tbaSpeed Display tbaTemperature Display tbaBMS v+t Display tbaTPMS Display tbaCharge Status Display tbaCharge Interruption Alerts tbaCharge Control tbaCabin Pre-heatcool Control tbaLockUnlock Vehicle tbaValet Mode Control tbaOthers tba

191

Open Vehicles

192 Chapter 22 Tesla Model 3

CHAPTER 23

Tesla Model S

Vehicle Type TS

At present support for the Tesla Model S in OVMS is experimental and under development This vehicle type shouldnot be used by anyone other than those actively involved in development of support for this vehicle

231 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support Not widely tested but should be

allVehicle Cable 9665972 OVMS Data Cable for Early TeslasGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna None not requiredSOC Display YesRange Display YesGPS Location Yes (from carrsquos built in GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display Not currently supportedCharge Status Display YesCharge Interruption Alerts YesCharge Control Not currently supportedCabin Pre-heatcool Con-trol

Not currently supported

LockUnlock Vehicle Not currently supportedValet Mode Control Not currently supportedOthers Adhesive velcro strips useful for vehicle attachment

193

Open Vehicles

232 TPMS Option

Reading and writing TPMS wheel sensor IDs fromto the Baolong TPMS ECU is supported by OVMS in Tesla ModelS cars using the Baolong system (vehicles produced up to around August 2014) You can easily tell if you have thisTesla Model S Baolong TPMS system as Tesla doesnrsquot support displaying tyre pressures in the instrument cluster Bycontrast the later Continental TPMS system does show the pressures in the instrument cluster

OVMS directly supports the Baolong TPMS in Tesla Model S cars without any extra hardware required You simplyneed the usual OVT1 cable

To read the current wheel sensor IDs from the Baolong TPMS ECU ensure that the car is ON (simplest is to wake thecar up and put in drive) and issue the lsquotpms readrsquo command in OVMS

Similarly to write wheel sensor IDs to the Baolong TPMS ECU ensure that the car is ON and issue the lsquotpms writersquocommand in OVMS

194 Chapter 23 Tesla Model S

CHAPTER 24

Tesla Roadster

Vehicle Type TR

The Tesla Roadster support in OVMS is perhaps the most mature in the project All versions (1x 2x and 3x) aresupported for both North American and other variants

241 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 1x 2x and 30 roadsters (all

markets)Vehicle Cable 9665972 OVMS Data Cable for Early TeslasGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna None not requiredSOC Display YesRange Display YesGPS Location Yes (from carrsquos built in GPS)Speed Display YesTemperature Display YesBMS v+t Display Not currently supportedTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control YesCabin Pre-heatcool Con-trol

Not currently supported

LockUnlock Vehicle YesValet Mode Control YesOthers Adhesive velcro strips useful for vehicle attachment

195

Open Vehicles

242 Module Installation in the vehicle

The OVMS module is connected to your Roadster via the CAN bus diagnostic port connector which is located in thepassenger footwell It is made of plastic that is wrapped in grey foam as shown in the photo Typically the connectoris wedged into the front wall near the center console so it wonrsquot rattle Pull the connector out and note the orientationof the pins especially the void above the +12V and Ground pins

The OVMS Data Cable for Tesla Roadster can then be plugged in connecting the car to the OVMS module Makesure to tighten the screws holding the module-side DB9 connector

At this point check the car Tap on the VDS in the centre console and make sure it turns on Insert the key turn on thecar and make sure everything works as expected If you see any problems at all with the car disconnect the OVMSmodule and contact Open Vehicles support for assistance

WarningIf when you plug the OVMS into the car you see any interference to or strange behaviour of car systemsimmediately unplug the module and contact Open Vehicles for assistance Never leave a module connected in suchcircumstances

The OVMS Module is best secured to the front wall of the passenger footwell using adhesive velcro tape With themodule connected to the car diagnostics port connector experiment with various placements until you find a suitablespot For the velcro attachment to work yoursquoll want to choose a spot on the front wall thatrsquos flat for the entire size ofthe module (hint avoid the big round black plastic plug)

Mounting is straightforward

1 Ensure that both velcro strips are fixed together

2 Remove the adhesive backing from one side fasten it to the back of the OVMS module

3 Using a clean dry cloth clean the area of the car passenger footwell wall to which you are going to attach themodule

4 Remove the adhesive backing from the side of the velcro strip facing the car and then firmly push the OVMSmodule into place - holding it still for a few seconds to allow the adhesive to work

5 You can then remove and reinstall the OVMS module as desired via the velcro

196 Chapter 24 Tesla Roadster

Open Vehicles

243 Antenna Installation

You will find the performance of this antenna fantastic - and much better than even your cellphone but proper place-ment is essential Since it has a very long cable you can place the antenna just about wherever you want but pleaseensure it is high-up on the car and away from any metal objects that might interfere with the signal

Possible areas include the bottom of the windscreenwindshield on the passenger side the top of the windscreen onthe passenger side (hidden by the sun visor) behind the passenger on the side pillar in the rear window or under thedashboard (for the brave and experienced at dismantling Tesla Roadster dashboards)

The antenna is connected to the port marked GSM on the OVMS v3 module The GPS port is not used on the TeslaRoadster (as your car already has GPS installed and we can read that positioning information off the CAN bus directly)

2431 Antenna beside rear passenger headrest

The antenna cable is long enough to reach back to the area around the left side seat head This approach is generallyeasiest The module is placed in the left seat footwell near the diagnostic port connector From there the antennacable is routed through the base of the waterfall under the door sill and up the side of the door frame

The door sill is held in place by velcro and is easily removed You may have to loosen the waterfall (held in place byfour screws around the fuse box area) The antenna cable can then be placed on top of the metal of the chassis sillbetween the velcro strips and routed up through the existing plastic trunking At this point the door sill can then beput back in place

2432 Antenna on windshieldwindscreen

To route the antenna cable up to the front windshieldwindscreen you will need to remove the fuse-box cover (onescrew that needs to be turned 90 degrees) then two screws from the box below the fuse box (these screws should becompletely removed in order to be able to remove the box and access the compartment beneath) You do not need toadjust anything in the fuse box - you only need the cover removed to make it easier to route the cable

Start with the cable at the windscreenwindshield and route it down the side of the left side door front pillar Theplastic corner can be pulled back slightly and you can push the cable through into the open bottom compartmentPull the cable through there so that the antenna is where you want it and there is no loose cable outside the box Theantenna itself can be mounted to the windscreenwindshield by first cleaning the area with a clean dry cloth removingthe adhesive backing tape then firmly pushing the antenna against the glass and waiting a few seconds for the adhesiveto stick

Now for the tricky bit You need to get the cable through to the passenger footwell but it is tight It is much easier toget a guide wire up into the fuse box compartment than to get the antenna cable down into the passenger footwell Sowe recommend you use a small (12 inches 30 cm or so) piece of stiff wire to use as a guide and push it up from thearea marked by the green arrow on the bottom right of the picture below Once the guide wire is in the fuse box pushit down into the lower compartment you opened and wrap it around the antenna cable You can then pull the guidewire back down into the passenger footwell bringing the antenna cable with it

The antenna cable can then be screwed in to the OVMS module You can then tidy up any loose cable and screw-backthe lower compartment box (two screws) and fuse box cover (one screw 90 degrees to lock)

244 Configuration Options

The Tesla Roadster specific configuration options are in configuration parameter xtr

243 Antenna Installation 197

Open Vehicles

Instance Default Descriptiondigitalspeedo no Set to yes to enable digital speedometer (2x cars only)digitalspeedoreps 3 Number of CAN bus repeat transmissionscooldowntimelimit 60 Number of minutes after which cooldown is stoppedcooldowntemplimit 31 Temperature (in Celcius) after which cooldown is stoppedprotectlock yes Refuse to lock vehicle when switched on

245 Tesla Roadster Notes

1 In general the OVMS module in a Tesla Roadster acts exactly like the little VDS screen We should be able todo anything that screen can do but no more Here are some notes

2 The lockunlock and valet functions rely on a PIN code This is the same PIN code you enter into the vehicleusing the VDS screen when activating valet mode If you donrsquot know the PIN code either try the default 1234or contact Tesla for assistance

3 While OVMS can lockunlock the doors of all Tesla Roadster models cars outside North America are fitted withan immobiliser and neither OVMS nor the VDS will disarmarm that The OVMS lockunlock functionality onlyapplies to the doors not the alarm in vehicles sold outside North America

4 OVMS v3 can calculate an overall battery health metric This metric is calculated using our own algorithm andis in no way approved by Tesla Battery health is dependent on many factors and hard to bring down to just onesimple number

5 The Tesla Roadster requires the ignition key to be on and manual switches turned to coolheat the cabin It isnot technically possible to do this remotely via OVMS

The digital speedometer function replaces the AMPS display in the dashboard instrument cluster with the vehiclespeed It is only supported on v2x cars (not v15) This is an experimental feature and works 99 of the time butsometimes the car wins and displays AMPS for a split second A better solution is to use the HUD functionality ofOVMS v3 and install an external Heads Up Display in the car

246 TPMS Option

Reading and writing TPMS wheel sensor IDs fromto the Baolong TPMS ECU is supported in v2x Tesla Roadstersusing the optional OVMS K-Line Expansion Board You will need a v32 module (or v31 module labelled on boardas July 2018 or later with K-line pin connected) and an OVT1 vehicle cable (clearly labelled with ldquoOVT1rdquo on thecable)

The optional OVMS K-line Expansion Board should be configured with SW1 set to position 2 (LDO 5v) and S1 into OFF position (away from the ON label)

To read the current wheel sensor IDs from the Baolong TPMS ECU ensure that the ignition switch is ON (so instru-ment panel lights are on) and issue the lsquotpms readrsquo command in OVMS

Similarly to write wheel sensor IDs to the Baolong TPMS ECU ensure that the ignition switch is ON (so instrumentpanel lights are on) and issue the lsquotpms writersquo command in OVMS

Note that this functionality will not work with v15 Tesla Roadsters (that use a different TPMS ECU to the v2x cars)

198 Chapter 24 Tesla Roadster

Open Vehicles

247 Thanks

There are so many people to thank for Tesla Roadster support in OVMS WPetefish for sourcing the car connectorFuzzylogic for the original hardware and software design and demonstration of it working Scott451 for figuring outmany of the Roadster CAN bus messages Tom Saxton for v15 Roadster testing Michael Thwaite for pictures ofantenna installation Bennett Leeds for wordsmithing the manual Mark Webb-Johnson for CAN bus hacking andwriting the vehicle module support Sonny Chen for beta testing and tuning and many others for showing that thiskind of thing can work in the real world

247 Thanks 199

Open Vehicles

200 Chapter 24 Tesla Roadster

CHAPTER 25

Toyota RAV4 EV

Vehicle Type TYR4

At present support for the 2012-2014 Toyota RAV4 EV in OVMS is experimental and under development Thisvehicle type can be used by early adopters as long as you understand the limitations The current release only showsinformation from the Tesla CAN bus not the Toyota CAN bus and is read-only

201

Open Vehicles

251 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support All 2012-2014 RAV4 EV are identical

and no other years are supportedVehicle Cable A custom cable is required to connect at the left rear of the vehicle Tesla and Toyota CAN

buses are available at the Gateway ECUGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA)SOC Display Yes (Tesla BMS value)Range Display Not currently supportedGPS Location YesSpeed Display YesTemperature Dis-play

Yes

BMS v+t Display YesTPMS Display Not currently supportedCharge Status Dis-play

Yes

Charge InterruptionAlerts

Yes

Charge Control Not currently supportedCabin Pre-heatcool Control

Not currently supported

LockUnlock Vehi-cle

Not currently supported

Valet Mode Control Not currently supportedOthers

The Tesla CAN bus already had decodes available so those were implemented already The primary focus goingforward will be decoding the Toyota CAN bus to replicate SafetyConnect connected features like Remote Climatebefore the 3G shutdown ends that manufacturer provided functionality

The file xr4monhtm should be installed as a Page type Web Plugin to display detailed information about the carrsquosstatus

202 Chapter 25 Toyota RAV4 EV

CHAPTER 26

Tracking Vehicles

Vehicle Type XX

The track vehicle will be documented here

261 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support Not widely tested but should be allVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left) or any cable

proving powerGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display NoRange Display NoGPS Location Yes (from modem module GPS)Speed Display Yes (from modem module GPS)Temperature Display NoBMS v+t Display NoTPMS Display NoCharge Status Display NoCharge InterruptionAlerts

No

Charge Control NoCabin Pre-heatcoolControl

No

LockUnlock Vehicle NoValet Mode Control NoOthers None

203

Open Vehicles

204 Chapter 26 Tracking Vehicles

CHAPTER 27

VW e-Up

Vehicle Type VWUP

This vehicle type supports the VW e-UP (2013- 2020-) Skoda Citigo E IV and the Seat MII electric (2020-) Con-nection can be made via the OBD2 port to the top left of the driving pedals andor the Comfort CAN bus eg belowthe passenger seat (T26 connector instead of the VW OCU there)

The main difference currently is that the OBD connection enables access to way more metrics (eg down to cellvoltages) while the Comfort CAN connection is necessary if write access is needed eg for remote climate controlThe Comfort CAN also provides data in more cases without turning on the car or charging as the bus wakes on manyevents (eg opening of doors) and can also be woken via OVMS

For the full experience making both connections is recommended

271 Using OBD2

Connection to OBD2 is done with the standard OVMS OBD2-cable just below the fuses left of the driving pedals

205

Open Vehicles

272 Using Comfort CAN

Connection to Comfort CAN can be done by removing the OCU below the passenger seat using a custom 26-pinadapter cable to the T26A plug (advantage the connections for the GSM amp GPS-antennas of the car can be used usinga Fakra-SMA adapter)

206 Chapter 27 VW e-Up

Open Vehicles

272 Using Comfort CAN 207

Open Vehicles

The passenger seat doesnrsquot need to be removed completely you can access the OCU connection from the back whentilting the unscrewed seat to the front To unscrew the seat yoursquoll need an XZN (triple-square german ldquoVielzahnrdquo)M10 bit Hint raise the seat to gain access to the rear screws

The T26a plug is secured by the white clamp open it fully to the left to unplug

273 Using both Connections

This document shows two options to use both connections

1 Variant 1 connects to the Comfort CAN using the OCU T26A connector

2 Variant 2 connects to the Comfort CAN by tapping the Comfort CAN cables

Both variants allow keeping the OCU in place If you intend to replace the OCU by the OVMS and reuse the OCUantennas for the OVMS variant 1 will probably be the better choice

2731 Variant 1

Connecting to the Comfort CAN using the OCU T26A connector

You need to establish a connection between the OBD2 and the OCU ports If installing the OVMS near the OBD2port you need to make a cable to connect to the T26A plug (or tap into the T26A cable there) If installing the OVMSreplacing the OCU you need to connect the OBD2 CAN bus from there

An adapter cable has to be made with the following connections

208 Chapter 27 VW e-Up

Open Vehicles

The cable used between the OBD plug and the DB9-F plug needs to be twisted to avoid transmission problems Agood cable to use here is a CAT-5 or CAT-6 double shielded network cable Be sure to not only connect CAN hi andCAN lo but also connect ground

T26 OBD DB9-F Signal26 4 3 Chassis Power GND 14 2 can1 L (OBD2 CAN Low) 6 7 can1 H (OBD2 CAN High) 4 can2 L (not used) 5 can2 H (not used)2 6 can3 L (Comfort-CAN Low)14 8 can3 H (Comfort-CAN High)1 9 +12V Vehicle Power

Important note the VW T26a pin numbering scheme does not follow the IT standard (zig zag) but instead has pins1-13 left to right on the top and 14-26 left to right on the bottom row See image above

2732 Variant 2

Connecting to the Comfort CAN by tapping the Comfort CAN cables

Description amp images by courtesy of GE user donaldduck8

This approach installs the OVMS near the OBD2 port and keeps the OCU in place Advantages

1 The OCU remains untouched and can be switched onoff as needed (fuse SD1)

2 No need to unmount the passenger seat

3 The OVMS can be disabledenabled any time simply via the OBD2 plug

The OVMS will be mounted on the driver side behind the footwell panel near the OBD2 port The Comfort CANsignal will be taken by tapping the cables behind the passengerrsquos footwell panel

The cable used needs to be twisted to avoid transmission problems A good cable to use here is a CAT-5 or CAT-6double shielded network cable A network cable has four pairs you will only need one pair here We recommendconnecting the shielding as well to avoid issues

273 Using both Connections 209

Open Vehicles

To connect to the OVMS you can use either a custom DB9 plug or add a DA26 connector You need to connect toCAN3

Comfort CAN OBD DB9-F DA26 Signal 4 3 8 Chassis Power GND 14 2 5 can1 L (OBD2 CAN Low) 6 7 15 can1 H (OBD2 CAN High) 12 4 7 can2 L (not used) 13 5 17 can2 H (not used)orangebrown 6 6 can3 L (Comfort-CAN Low)orangegreen 8 16 can3 H (Comfort-CAN High) 16 9 9 +12V Vehicle Power

Step 1 Remove the passenger footwell panel

Step 2 Tap into the Comfort CAN

Comfort CAN is on cables orangegreen (rarrCAN3-H) and orangebrown (rarrCAN3-L) Carefully remove a part of theisolation solder on your twisted pair cables then restore the isolation (eg by applying PlastiDip)

210 Chapter 27 VW e-Up

Open Vehicles

Step 3 Lay the cable towards the fuse box amp OBD2 port on the left

273 Using both Connections 211

Open Vehicles

Step 4 Use velcro tape to mount the OVMS on the side wall

Step 5 Stick the GPS antenna eg onto the air vent pipe To disable the OCU unplug fuse SD1

212 Chapter 27 VW e-Up

Open Vehicles

Step 6 Stick the GSM antenna eg on the lower panelrsquos rear side

Finally Refit all panels

273 Using both Connections 213

Open Vehicles

274 Basic Configuration

After selecting the VW e-Up vehicle module the corresponding settings have to be made in the web interface via theldquoVW e-Uprdquo menu under ldquoFeaturesrdquo

214 Chapter 27 VW e-Up

Open Vehicles

By default both connections are activated

For more details on the two connection types please see the corresponding projects

VW e-Up via Comfort CAN (T26A)

VW e-Up via OBD2

The initial code is shamelessly copied from the original projects for the Comfort CAN by Chris van der Meijden andfor the OBD2 port by SokoFromNZ

List of (possible) metrics via OBD2 httpswwwgoingelectricdewikiListe-der-OBD2-Codes

If OBD is selected a sample page with some charging metrics is shown in the web interface

274 Basic Configuration 215

Open Vehicles

216 Chapter 27 VW e-Up

Open Vehicles

Beware obviously these values have great uncertainties (in my car the DC output voltage of the charger is alwayslower than the voltage of the battery ) But eg the internal energy counters are very informative )

Additional custom web pages (code for the example above is below) can be defined as described here httpsdocsopenvehiclescomenlatestpluginREADMEhtmlhighlight=web20plugininstalling-web-plugins

274 Basic Configuration 217

Open Vehicles

275 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 2013-Vehicle Ca-ble

Comfort CAN T26A (OCU connector cable located under front passenger seat) to DB9 Data Cablefor OVMS using pin 6 and 8 for can3 _AND_ OBD-II to DB9 Data Cable for OVMS (1441200right or 1139300 left) for can1

GSMAntenna

T4AC - R205 with fakra_sma adapter cable or 1000500 Open Vehicles OVMS GSM Antenna (orany compatible antenna)

GPS An-tenna

T4AC - R50 with fakra_sma adapter cable or 1020200 Universal GPS Antenna (or any compatibleantenna)

SOC Dis-play

Yes

Range Dis-play

Yes

Cabin Pre-heatcoolControl

Yes

GPS Loca-tion

Yes (from modem module GPS)

Speed Dis-play

Yes

Tempera-ture Display

Yes (see list of metrics below)

BMS v+tDisplay

Yes

TPMS Dis-play

tba

Charge Sta-tus Display

Yes

ChargeInterruptionAlerts

Yes (per notification on the charging state)

ChargeControl

tba

LockUnlockVehicle

No

Valet ModeControl

No

Others See list of metrics below

276 Supported Standard Metrics

The second column specifies the bus from which the metrics are obtained Metrics via OBD are only updated when thevehicle is on (ignition started) or some in charging mode Metrics via T26 (Comfort CAN) can be updated on demandby waking the Comfort CAN from the OVMS module During charging the Comfort CAN automatically wakes every5 of SoC

218 Chapter 27 VW e-Up

Open Vehicles

Metric name bus Example value Descriptionvb12vvoltage direct 129 V Current voltage of the 12V batteryvbconsumption OBD 0Whkm Main battery momentary consumptionvbcurrent OBD 232 A Current current into (negative) or out of (positive) the main batteryvbenergyrecdtotal OBD 578323 kWh Energy recovered total (life time) of the main battery (charging and recuperation)vbenergyusedtotal OBD 540342 kWh Energy used total (life time) of the main batteryvbpower OBD 23234 kW Current power into (negative) or out of (positive) the main batteryvbrangeest T26 99km Estimated rangevbrangeideal T26 48km Ideal rangevbsoc OBD T26 882 Current usable State of Charge (SoC) of the main batteryvbtemp OBD 225 degC Current temperature of the main batteryvbvoltage OBD 3202 V Current voltage of the main batteryvc12vcurrent OBD 78A Output current of DCDC-convertervc12vpower OBD 0123kW Output power of DCDC-convertervc12vtemp OBD 345degC Temperature of DCDC-convertervc12vvoltage OBD 123V Output voltage of DCDC-convertervccharging T26 true Is vehicle charging (true = ldquoVehicle CHARGINGrdquo state veon=false if this is true)vcclimit fixed 1632A Maximum charger output currentvccurrent OBD 125A Momentary charger output currentvcefficiency OBD 913 Charging efficiency calculated by vbpower and vcpowervckwh OBD 26969kWh Energy sum for running chargevcmode T26 standard standard range performance storagevcpilot T26 no Pilot signal presentvcpower OBD 7345 kW Input power of chargervcstate T26 done charging topoff done prepare timerwait heating stoppedvcsubstate T26 scheduledstop scheduledstart onrequest timerwait powerwait stopped interruptedvctemp OBD 16degC Charger temperaturevctime T26 0Sec Duration of running chargevcvoltage OBD 0V Momentary charger supply voltagevdcp T26 yes yes = Charge port openvdfl T26 yes = Front left door openvdfr T26 yes = Front right door openvdhood T26 yes = Hoodfrunk openvdrl T26 yes = Rear left door openvdrr T26 yes = Rear right door openvdtrunk T26 yes = Trunk openveawake T26 no yes = Vehiclebus awake (switched on)vecabintemp T26 20degC Cabin temperaturevedrivetime T26 0Sec Seconds driving (turned on)veheadlights T26 yes = Headlights onvehvac T26 yes = HVAC activevelocked T26 yes = Vehicle lockedveon T26 true Is ignition on and drivable (true = ldquoVehicle ONrdquo false = ldquoVehicle OFFrdquo state)veparktime T26 49608Sec Seconds parking (turned off)veservrange OBD 12345km Distance to next scheduled maintenanceservice [km]veservtime OBD 1572590910Sec Time of next scheduled maintenanceservice [UTC]vetemp OBD T26 Ambient temperaturevitemp OBD Inverter temperaturevmtemp OBD 0degC Motor temperaturevpodometer OBD T26 2340 km Total distance traveledvpspeed T26 0kmh Vehicle speed

Continued on next page

276 Supported Standard Metrics 219

Open Vehicles

Table 1 ndash continued from previous pageMetric name bus Example value Descriptionvvin T26 VF1ACVYB012345678 Vehicle identification number

277 Custom Metrics

In addition to the standard metrics above the following custom metrics are read from the car or internally calculatedby OVMS using read values

Metricname

bus Examplevalue

Description

xvubcelldeltaOBD 0012 V Delta voltage between lowest and highest cell voltagexvubsocabs OBD 853 Current absolute State of Charge (SoC) of the main batteryxvucsocnormOBD 805 Current normalized State of Charge (SoC) of the main battery as reported by

charge management ECUxvucaci1 OBD 59 A AC current of AC charger phase 1xvucaci2 OBD 70 A AC current of AC charger phase 2 (only for model 2020+)xvucacp OBD 7223 kW Current charging power on AC side (calculated by ECUrsquos AC voltages and

AC currents)xvucacu1 OBD 223 V AC voltage of AC charger phase 1xvucacu2 OBD 233 V AC voltage of AC charger phase 2 (only for model 2020+)xvucdci1 OBD 12 A DC current of AC charger 1xvucdci2 OBD 12 A AC current of AC charger 2 (only for model 2020+)xvucdcp OBD 6500 kW Current charging power on DC side (calculated by ECUrsquos DC voltages and

DC currents)xvucdcu1 OBD 380 V DC voltage of AC charger 1xvucdcu2 OBD 375 V DC voltage of AC charger 2 (only for model 2020+)xvuceffcalc OBD 900 Charger efficiency calculated by AC and DC powerxvuceffecu OBD 923 Charger efficiency reported by the Charger ECUxvuclosscalc OBD 0733 kW Charger power loss calculated by AC and DC powerxvuclossecu OBD 0620 kW Charger power loss reported by the Charger ECUxvueservdaysOBD 78 days Time to next scheduled maintenanceservice [days]xvumsocabs OBD 853 Current absolute State of Charge (SoC) of the main battery as reported by

motor electronics ECUxvumsocnormOBD 805 Current normalized State of Charge (SoC) of the main battery as reported by

motor electronics ECU

278 Example Code for Web Plugin with some custom metrics

ltdiv class=panel panel-primarygtltdiv class=panel-headinggtCustom Metricsltdivgtltdiv class=panel-bodygt

lthrgt

ltdiv class=receivergtltdiv class=clearfixgtltdiv class=metric progress data-metric=vbsoc data-prec=1gtltdiv class=progress-bar value-low text-left role=progressbar

(continues on next page)

220 Chapter 27 VW e-Up

Open Vehicles

(continued from previous page)

aria-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoCltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=xvubsocabs data-prec=1gtltdiv class=progress-bar progress-bar-info value-low text-left role=progressbar

rarr˓aria-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoC (absolute)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbenergyusedtotal data-prec=2gtltspan class=labelgtTOTALSampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbsp

rarr˓ampnbspampnbspampnbspUsedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vbenergyrecdtotal data-prec=2gtltspan class=labelgtChargedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vpodometer data-prec=0gtltspan class=labelgtOdoltspangtltspan class=valuegtltspangtltspan class=unitgtkmltspangt

ltdivgtltdiv class=metric number data-metric=veservrange data-prec=0gtltspan class=labelgtSERVICEampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbspamp

rarr˓nbspampnbspampnbspampnbspRangeltspangtltspan class=valuegtltspangtltspan class=unitgtkmltspangt

ltdivgtltdiv class=metric number data-metric=xvueservdays data-prec=0gtltspan class=labelgtDaysltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

lth4gtBatterylth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=vbvoltage data-prec=1gtltdiv class=progress-bar value-low text-left role=progressbararia-valuenow=0 aria-valuemin=300 aria-valuemax=420 style=width0gtltdivgt

(continues on next page)

278 Example Code for Web Plugin with some custom metrics 221

Open Vehicles

(continued from previous page)

ltspan class=labelgtVoltageltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbcurrent data-prec=1gtltdiv class=progress-bar progress-bar-danger value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-200 aria-valuemax=200 style=width0gtltdivgtltspan class=labelgtCurrentltspangtltspan class=valuegtltspangtltspan class=unitgtAltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbpower data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-70 aria-valuemax=70 style=width0gtltdivgtltspan class=labelgtPowerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgtltdivgt

ltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbtemp data-prec=1gtltspan class=labelgtTempltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangtltdivgtltdiv class=metric number data-metric=xvubcelldelta data-prec=3gtltspan class=labelgtCell deltaltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangtltdivgt

ltdivgt

lth4gtTemperatureslth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=vetemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtAmbientltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vecabintemp data-prec=1gt

(continues on next page)

222 Chapter 27 VW e-Up

Open Vehicles

(continued from previous page)

ltdiv class=progress-bar progress-bar-warning value-low text-left role=rarr˓progressbar

aria-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtCabinltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbtemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtBatteryltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vctemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtChargerltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vc12vtemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtDCDC-Converterltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vitemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtInverterltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vmtemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbar(continues on next page)

278 Example Code for Web Plugin with some custom metrics 223

Open Vehicles

(continued from previous page)

aria-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtMotorltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgt

ltdivgtltdivgt

ltdivgtltdivgt

ltdivgt

279 Custom Data Logs

2791 SOC Monitoring Log

The SOC monitoring log provides detailed data about the correlations and connections between the various SOCsvoltage level amp energycoulomb chargedischarge amounts

You need to enable this log explicitly by configuring a storage time via config param xvu logsocmonstoretime (in days) Set to 0empty to disable the log Already stored log entries will be kept on the serveruntil expiry or manual deletion

Log entries are created on SOC changes while charging and every 10 seconds while driving

bull Notification subtype xvulogsocmon

bull History record type XVU-LOG-SOCMon

bull Format CSV

bull Archive time config xvu logsocmonstoretime (days 0=off)

bull Fieldscolumns

ndash temp ndash battery temperature [degC]

ndash charging ndash 01

ndash soc_abs_bms ndash absolute SOC from BMS (ECU 8C PID 028C) []

ndash soc_abs_eng ndash absolute SOC from engine (ECU 01 PID F45B) []

ndash soc_norm_cmg ndash normalized user SOC from charge manager (ECU BD PID 1DD0) []

ndash soc_norm_eng ndash normalized user SOC from engine (ECU 01 PID 1164) []

ndash soc_norm ndash previously selected soc_norm_eng while driving now always soc_norm_cmg []

ndash voltage ndash momentary total battery voltage [V]

ndash current ndash momentary battery current negative = charging [A]

ndash soh ndash state of health sourced as configured []

ndash cac ndash battery capacity sourced as configured [Ah]

ndash energy_used ndash total car energy discharge counter [kWh]

ndash energy_recd ndash total car energy charge counter [kWh]

224 Chapter 27 VW e-Up

Open Vehicles

ndash coulomb_used ndash total car coulomb discharge counter [Ah]

ndash coulomb_recd ndash total car coulomb charge counter [Ah]

ndash pack_vavg ndash average cell voltage [V]

ndash pack_vmin ndash minimum cell voltage [V]

ndash pack_vmax ndash maximum cell voltage [V]

ndash pack_vstddev ndash cell voltage standard deviation [V]

ndash pack_vgrad ndash cell voltage series quality (gradient)

ndash energy_range ndash remaining usable energy from MDF range estimation (ECU 17 PID 22E4) [kWh]

279 Custom Data Logs 225

Open Vehicles

226 Chapter 27 VW e-Up

CHAPTER 28

VW e-Up via OBD2

Vehicle Type VWUPOBD

This vehicle type supports the VW e-UP (new model from year 2020 onwards) Untested (so far) but probably workingThe older models of the e-Up as well as Skoda Citigo E IV and Seat MII electric

Connection is via the standard OBD-II port (above the drivers left foot)

All communication with the car is read-only For changing values (ie climate control) see the T26A connection tothe Comfort CAN bus

281 Support Overview

Function Support StatusHardware No specific requirementsVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display YesBMS v+t Display Yes (including cell details)TPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers See list of metrics below

227

Open Vehicles

282 Vehicle States

Warning For proper state detection the 12V calibration is crucial Calibrate using the OVMS Web UI Configrarr Vehicle rarr 12V Monitor

Three vehicle states are supported and detected automatically

Vehicle ON The car is on It is drivable

Vehicle CHARGING The car is charging The carrsquos Charger ECU is responsive and reports charging activity

Vehicle OFF The car is off It hasnrsquot drawn (or charged) any current into the main battery for a period of time andthe 12V battery voltage is smaller than 129V

283 Supported Standard Metrics

Metrics updated in state ldquoVehicle ONrdquo or ldquoVehicle CHARGINGrdquo

Metric name Examplevalue

Description

veon yes Is ignition on and drivable (true = ldquoVehicle ONrdquo false = ldquoVehicle OFFrdquostate)

vccharging yes Is vehicle charging (true = ldquoVehicle CHARGINGrdquo state veon=false if thisis true)

vclimitsoc 100 Sufficient SOC timer mode SOC destination or user CTP configuration (seebelow)

vcmode range ldquorangerdquo = charging to 100 SOC else ldquostandardrdquovctimermode no Yes = currentnext charge under timer controlvcstate done charging stopped donevcsubstate scheduledstop scheduledstop scheduledstart onrequest timerwait stopped interruptedvb12vvoltage1 129 V Current voltage of the 12V batteryvbvoltage 3202 V Current voltage of the main batteryvbcurrent 232 A Current current into (negative) or out of (positive) the main batteryvbpower 23234 kW Current power into (negative) or out of (positive) the main batteryvbenergyusedtotal 540342 kWh Energy used total (life time) of the main batteryvbenergyrecdtotal 578323 kWh Energy recovered total (life time) of the main battery (charging and recu-

peration)vbtemp 225 degC Current temperature of the main batteryvpodometer 2340 km Total distance traveled

Metrics updated only in state ldquoVehicle ONrdquo

Metric name Example value Descriptionvbsoc2 882 Current usable State of Charge (SoC) of the main batteryvedrivemode 2 1=STD 2=ECO 3=ECO+vegear 1 1=forward 0=neutral -1=reverse (2020 model only)

Metrics updated only in state ldquoVehicle CHARGINGrdquo1 Also updated in state ldquoVehicle OFFrdquo2 Restriction by the ECU Supplied when the ignition is on during charging Use xvubsoc as an alternative when charging with ignition off

228 Chapter 28 VW e-Up via OBD2

Open Vehicles

Metric name Example value Descriptionvcpower 7345 kW Input power of chargervcefficiency 913 Charging efficiency calculated by vbpower and vcpower

284 Custom Metrics

In addition to the standard metrics above the following custom metrics are read from the car or internally calculatedby OVMS using read values

State metrics

Metric name Example value Descriptionxvuehvchgmode 0 High voltage charge mode 0=off 1=Type2 4=CCSxvuelvautochg 1 Auxiliary battery (12V) auto charge mode (01)xvuelvpwrstate 0 Low voltage (12V) power state (0=off 4=12V 8=HVAC 15=on)

Timed charge metrics

Metric name Example value Descriptionxvuclimitsocmax 80 Charge schedule maximum SOCxvuclimitsocmin 20 Charge schedule minimum SOCxvuctimermodedef yes Charge timer defined amp default

xvuctimermodedef tells if a charge schedule has been configured and enabled If so the car uses timedcharging by default (the charge mode button will be lit) vctimermode tells if the charge timer is or will actuallybe used for the current or next charge ie reflects the mode selected by pushing the button

With timed charging the car first charges to the minimum SOC as soon as possible (when connected) If the maximumSOC configured for the schedule hasnrsquot been reached by then it will then wait for the timer to signal the second phaseto charge up to the maximum SOC The ldquosufficient SOCrdquo vclimitsoc will be the maximum SOC if less than100 If the timer is disabled or set to charge up to 100 the sufficient SOC is set to the user configured charge timeprediction SOC limit (config xvu ctpsoclimit)

Charging above vclimitsoc is classified as the ldquotopping offrdquo charge phase When crossing that SOC thresholdan intermediate charge status notification is sent

Note xvuclimitsocmin will show the configured minimum SOC also if no schedule is currently enabledxvuclimitsocmax shows the maximum for the currentnext schedule to apply If no schedule is enabled itwill be zero

Metrics updated in state ldquoVehicle ONrdquo or ldquoVehicle CHARGINGrdquo

Metric name Example value Descriptionxvubcelldelta 0012 V Delta voltage between lowest and highest cell voltagexvubsoc 853 Current absolute State of Charge (SoC) of the main battery

Metrics updated only in state ldquoVehicle CHARGINGrdquo

284 Custom Metrics 229

Open Vehicles

Metric name Examplevalue

Description

xvuceffecu3 923 Charger efficiency reported by the Charger ECUxvuclossecu3 0620 kW Charger power loss reported by the Charger ECUxvucacp 7223 kW Current charging power on AC side (calculated by ECUrsquos AC voltages and AC

currents)xvucdcp 6500 kW Current charging power on DC side (calculated by ECUrsquos DC voltages and DC

currents)xvuceffcalc 900 Charger efficiency calculated by AC and DC powerxvuclosscalc 0733 kW Charger power loss calculated by AC and DC powerxvucccsu4 3315V CCS charger supplied voltage [V]xvucccsi4 622A CCS Charger supplied current [A]xvucccsp4 206193kW CCS Charger supplied power [kW]

285 Battery Capacity amp SOH

e-Up Model Total capacity Usable capacityGen 1 (2016) 187 kWh 50 Ah 164 kWh 439 Ah (877)Gen 2 (2020) 368 kWh 120 Ah 323 kWh 1053 Ah (877)

There are currently two ways to get an estimation of the remaining capacity of the e-Up

1 By deriving a usable energy capacity from the MFD range estimation

2 By deriving a total coulomb capacity from the coulombs charged

You can configure which of the estimations you want to use as the standard SOH from the ldquoFeaturesrdquo web page or bysetting the config parameter xvu batsohsource to either charge (default) or range

Note Consider the capacity estimations as experimental preliminary We need field data to optimize thereadings If yoursquod like to help us see below

The MFD range estimation seems to include some psychological factors with an SOC below 30 so we onlyprovide this and the derived capacity in two custom metrics The capacity derivation is only calculated with SOC gt=30 (initial value needs SOC gt= 70) but if so is available immediately after switching the car on This can serve asa quick first estimation relate it to the usable capacity of your model

The range based SOH is taken at itrsquos maximum peaks observed and copied if higher than the previously observedvalue or added smoothed if lower So to take the next reading directly set metric xvubsohrange to 0 beforeswitching on the car

The charge coulomb based estimation provides a better estimation but will need a little more time to settle Usablemeasurements need charges of at least 30 SOC the more the better Estimations are only calculated if a charge hasexceeded 30 SOC and results are smoothed over multiple charges to provide stable readings

bull To get a rough capacity estimation charge at least 30 normalized SOC difference

3 Only supplied by ECU when the car ignition is on during charging4 These are not measurements by the car but provided as is by the charger and typically deviate from the battery metrics According to IEC

61851 CCS currents may be off by +- 3 and voltages by +- 5 The power figures displayed by some chargers also typically wonrsquot match thesevalues possibly because the charger displays the power drawn from the grid (including losses)

230 Chapter 28 VW e-Up via OBD2

Open Vehicles

bull To get a good capacity estimation do at least three charges with each covering 60 or more normalized SOCdifference

Charging by CCS (DC) apparently yields higher results especially on the energy estimations We donrsquot know yet thereason or if we need to compensate this

Note the SOH (state of health) is currently coupled directly and solely to the calculated amp-hour capacity CAC

To log your capacity data on a connected V2 server do

OVMS config set xvu logchargecapstoretime 30

30 is the number of days to keep the data set to 0 to disable The counters will be stored in tableXVU-LOG-ChargeCap with one entry every 24 absolute SOC difference Resulting CACSOH updates willbe logged in table XVU-LOG-ChargeCapSOH You can also extract the data from your module log file by filteringlines matching ChargeCap

2851 Capacity and SOH metrics

Metric name Example value Descriptionxvubsohcharge 9923 SOH based on charge energy sumxvubsohrange 9889 SOH based on MFD range estimationxvubcapahabs 12271Ah Total coulomb capacity estimationxvubcapahnorm 11363Ah Usable coulomb capacity estimationxvubcapkwhabs 391kWh Total energy capacity estimationxvubcapkwhnorm 3621kWh Usable energy capacity estimationxvubcapkwhrange 328947kWh Usable energy capacity estimation from MFD rangexvubenergyrange 185kWh Current energy used by MFD range estimation

2852 Provide Data to the Developers

To help us with optimizing the capacity estimations first of all enable file logging if not already enabled Then enableextended polling and logging before a charge by

OVMS config set xvu dc_interval 30OVMS log level verbose v-vweup

After the charge disable the extended polling and logging

OVMS config set xvu dc_interval 0OVMS log level info v-vweup

Then download all log files written during the charge (archived and current) zip them and mail the zip to MichaelBalzer ltdexterdexters-webdegt The log data will only be used for technical analysis and deleted afterwards

Note if you forgot enabling the local log but still have chargecap logs on the server these can help as well

Thanks

286 Configuration Variables

The main configuration variables can be set through the web configuration page

286 Configuration Variables 231

Open Vehicles

bull VW e-Up rarr Features

Some configuration variables are kept ldquounder the hoodrdquo as these will normally not need to be changed except forsome special use cases or for development debugging

Configuration variables can be listed using command config list xvu and changed using command configset xvu ltvariablegt ltvaluegt

Configuration variable Default value Descriptionbatsohsource charge SOH source ndash see abovebmsautoreset no Reset BMS statistics on use phase transitionscanwrite no Allow CAN write accesscell_interval_awk 60 BMS cell query interval in awake state [s]cell_interval_chg 60 BMS cell query interval in charge state [s]cell_interval_drv 15 BMS cell query interval in drive state [s]con_obd yes Enable OBDII connectioncon_t26 yes Enable T26 connectionctpmaxpower 0 Charge time prediction fallback power limit [kW] (0=none)ctpsoclimit 80 Charge time prediction fallback SOC limit []dc_interval 0 Development additional DC charge PID query interval [s] (0=off)logchargecapcpstep 24 Charge capacity checkpoint interval [110]logchargecapminvalid 272 Charge capacity min SOC hub for SOH change [110]logchargecapstoretime 0 Charge capacity server log archive time [days] (0=off)modelyear 2012 Vehicle model yearnotifychargestartdelay 24 Charge start notification delay [s]5

287 Shell Commands

bull xvu polling ltstatus|pause|continuegt ndash control OBD2 polling

The OBD2 polling is normally continuously active as long as the vehicle module is loaded To free the CANbus from this load during an extended OBD2 diagnostics or modification (coding adaptation) session you cantemporarily pause the polling using this command

There is no time limit for a pause keep in mind you need to explicitly continue the polling when yoursquore doneDuring a polling pause no vehicle state changes can be detected

288 Custom Status Page for Web UI

Note This plugin is obsolete use the standard page VW e-Up rarr Charging Metrics instead We keep the sourcehere as a base for user customization

The easiest way to display custom metrics is using the Web Plugins feature of OVMS (see Installing Web Plugins)

This page plugin content shows the metrics in a compact form which can be displayed on a phone in landscape modeon the dashboard of the car Best approach is to connect the phone directly to the OVMS AP-WiFi and access the webUI via the static IP (19216841) of OVMS

5 Charge start needs some time to ramp up the charge current which implies charge speed amp time estimations If you want the start notificationas fast as possible reduce the value

232 Chapter 28 VW e-Up via OBD2

Open Vehicles

ltdiv class=panel panel-primarygtltdiv class=panel-headinggtVW eUpltdivgtltdiv class=panel-bodygt

lthrgt

ltdiv class=receivergtltdiv class=clearfixgtltdiv class=metric progress data-metric=vbsoc data-prec=2gtltdiv class=progress-bar value-low text-left role=progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoCltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=xvubsoc data-prec=2gtltdiv class=progress-bar progress-bar-info value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoC (absolute)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

(continues on next page)

288 Custom Status Page for Web UI 233

Open Vehicles

(continued from previous page)

ltdivgtltdivgt

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbenergyusedtotal data-prec=3gtltspan class=labelgtTOTALSampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbspamp

rarr˓nbspampnbspampnbspampnbspUsedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vbenergyrecdtotal data-prec=3gtltspan class=labelgtChargedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vpodometer data-prec=0gtltspan class=labelgtDistanceltspangtltspan class=valuegtltspangtltspan class=unitgtkmltspangt

ltdivgtltdivgt

lth4gtBatterylth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=vbvoltage data-prec=1gt

ltdiv class=progress-bar value-low text-left role=progressbararia-valuenow=0 aria-valuemin=300 aria-valuemax=350 style=width0gtltdivgtltspan class=labelgtVoltageltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbcurrent data-prec=1gtltdiv class=progress-bar progress-bar-danger value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-200 aria-valuemax=200 style=width0gtltdivgtltspan class=labelgtCurrentltspangtltspan class=valuegtltspangtltspan class=unitgtAltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbpower data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-70 aria-valuemax=70 style=width0gtltdivgtltspan class=labelgtPowerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgt

(continues on next page)

234 Chapter 28 VW e-Up via OBD2

Open Vehicles

(continued from previous page)

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbtemp data-prec=1gtltspan class=labelgtTempltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdiv class=metric number data-metric=xvubcelldelta data-prec=3gtltspan class=labelgtCell deltaltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangt

ltdivgtltdivgt

lth4gtChargerlth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=xvucacp data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=8 style=width0gtltdivgtltspan class=labelgtAC Powerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=xvucdcp data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=8 style=width0gtltdivgtltspan class=labelgtDC Powerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgt

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vcefficiency data-prec=1gt

ltspan class=labelgtEfficiency (total)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdiv class=metric number data-metric=xvuceffcalc data-prec=1gtltspan class=labelgtEfficiency (charger)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdiv class=metric number data-metric=xvuclosscalc data-prec=3gtltspan class=labelgtLoss (charger)ltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgt(continues on next page)

288 Custom Status Page for Web UI 235

Open Vehicles

(continued from previous page)

ltdivgtltdivgtltdivgt

ltdivgt

236 Chapter 28 VW e-Up via OBD2

CHAPTER 29

VW e-Up via Comfort CAN (T26A)

Vehicle Type integrated in VWUP

This part was the initial code for the OVMS VWUP vehicle module Development started in January 2020 by Chrisvan der Meijden

It supports the VW e-UP (2013- 2020-) Skoda Citigo E IV and the Seat MII electric (2020-) directly connected tothe comfort can bus through the lsquoT26Arsquo socket

237

Open Vehicles

291 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 2020- (2013- VW e-Up as well)Vehicle Cable Comfort CAN T26A (OCU connector cable located under front passenger seat) to DB9 Data

Cable for OVMS using pin 6 and 8 for can3GSM Antenna T4AC - R205 with fakra_sma adapter cable or 1000500 Open Vehicles OVMS GSM Antenna

(or any compatible antenna)GPS Antenna T4AC - R50 with fakra_sma adapter cable or 1020200 Universal GPS Antenna (or any com-

patible antenna)SOC Display YesRange Display YesCabin Pre-heatcool Control

Yes

GPS Location Yes (from modem module GPS)Speed Display YesTemperature Dis-play

Yes (outdoor cabin)

BMS v+t Display NoTPMS Display NoCharge Status Dis-play

Yes

Charge Interrup-tion Alerts

Yes (per notification on the charging state)

Charge Control tbaLockUnlockVehicle

No

Valet Mode Con-trol

No

Others Odometer trip VIN status of lock plug lights doors trunk and bonnet

292 Pinout OCU T26A - OVMS DB9 adapter

For the T26A approach we directly tap into the comfort can bus via the original OCU cable

The OCU connector is located under the passenger seat

238 Chapter 29 VW e-Up via Comfort CAN (T26A)

Open Vehicles

Advantage is the direct write access to the comfort can bus

Disadvantage is that we wonrsquot be able to access all control units of the car

OCU DB9-F Signal26 3 Chassis Power GND 2 can1 L (Can Low not used) 7 can1 H (Can High not used) 4 can2 L (Can Low not used) 5 can2 H (Can High not used)2 6 can3 L (Comfort-can Low)14 8 can3 H (Comfort-can High)1 9 +12V Vehicle Power

For confectioning the T26A adapter cable you can use a standard 26 pin ribbon cable (2x13 pins 254mm grid dimen-sion) and a DB9 female D-Sub connector You will need to grind down the rim of the socket of the ribbon cable

To make a GSMGPS adapter cable to connect to the original VW fakra socket you can use a double fakra maleconnector with two SMA male connectors attached

292 Pinout OCU T26A - OVMS DB9 adapter 239

Open Vehicles

293 User notes

bull Remove the passenger seat (on right hand drive cars the driverrsquos seat)

bull Open the carpet lid

bull Disconnect the T26A cable and the fakra cable from the OCU (online communication unit)

bull Remove the OCU

bull Connect the confectioned T26A adapter DB9 cable attached to the OVMS to the VW T26A connector of thecar

bull Connect your GMSGPS fakra adapter to the VW fakra cable

bull Fit OVMS in the compartment

bull Close the carpet lid

bull Reinstall the passenger seat

bull Configure OVMS as described in the OVMS user manual

bull Configure lsquoModel yearrsquo lsquoCan write accessrsquo and lsquoConnection typersquo under VW e-Up -gt Features

bull lsquoModel yearrsquo and lsquoCan write accessrsquo can also be set from within the app (FEATURES 20 and 15)

bull Register and connect OVMS to a server (as guided within the OVMS setup)

bull Turn the ignition in the car on and off to receive initial values (also needed after updates)

bull Install the OVMS app on your smartphone or tablet and configure it to connect to the server

240 Chapter 29 VW e-Up via Comfort CAN (T26A)

Open Vehicles

bull Enjoy -)

294 Climate control

Climate control works as long as write access to the comfort can has been enabled in the app or in the OVMSwebinterface (VW e-Up -gt Features)

To turn on or off the AC from within the Android app just press the ldquoACrdquo button Within the iOS app press ldquoHomelink1rdquo for AC on and ldquoHomelink 2rdquo for AC off

Once the AC is turned on by the app there will be a delay of about 17 seconds untill the AC actually starts in the carFurther 10 seconds all communication from the app to the car is blocked

The communication from the app to the car is also blocked for 10 seconds after the ldquoAC offrdquo command from the appto the car There is no delay between the ldquoAC offrdquo signal of the app and the actually turning off in the car

In rare cases lsquoAC offrsquo does not respond There will be a delay of 40 seconds before you can try again

The cabin target temperature can be set from the OVMS webinterface (VW e-Up (Komfort CAN) -gt Climate control)or via the app under FEATURES 21

294 Climate control 241

Open Vehicles

295 IDs on Comfort CAN Bus

ID Conversion Unit Function61A d72 State of Charge (relative)320 (d4ltlt8+d3-1)190 kmh Speed65F 3 Msg d5-7d1-7d1-7 String VIN number571 5+(05d0) Volt 12 Volt battery voltage65D d3ampfltlt12|d2ltlt8|d1 km Odometer3E3 (d2-100)2 degC Cabin temperature527 (d52)-50 degC Outdoor temperature531 d0 00 Headlights off52D d0 +255 if d1 41 km Calculated range381 d0 02 Status doors locked470 d1 12482010 Integer Doors trunk hood opened or closed3E1 d4 Integer Blower speed(57667D98BBDEFA)575 d0 00 to 0F Integer Key position575 d3 00 or 10 windshield heater (off or on)569 b07 ldquoACrdquo-LED69C d110+10 degC temperature setpoint for remote AC (only in message D2 ltd1gt 00 1E 1E

0A 00 00)61C d2 lt 07 bool Charging detection43D d1 01 or 11 TX Working or sleeping in the ring5A7 d1 16 TX OCU AC blocking signal5A9 all 00 TX OCU heartbeat69E multiple msg d0 C1 d6

xxdegC TX AC on off signals TX set cabin temperature for 69C

242 Chapter 29 VW e-Up via Comfort CAN (T26A)

Open Vehicles

296 Development notes

Under this vehicle component part we use the original T26A approach which can write to the comfort can and is ableto manage the climate control of the car

You will normally use the OVMS binaries provided ie here

The VWUP T26A component part with working climate control is publicly available within the OVMS binary version3215 lsquoedgersquo and upwards (lsquomainrsquo lsquoeaprsquo and lsquoedgersquo) The Android app version has to be 3171 or higher to haveaccess to the climate control functions for this vehicle component

If you want to compile the binary yourself you will need to read the OVMS development documentation on how to setup the tool chain check out the repository and the submodules and copy the file

sdkconfigdefaulthw31

from the OVMSV3support folder to the OVMSV3 folder and rename it to

sdkconfig

297 Vehicle log files

To be able to implement the VWUP vehicle component for OVMS the CAN logging of the VW e-UP provided bylsquosharkcowrsquo was of tremendous help

The implementation of this vehicle component could not have been done without these great files

They can be found here

httpsgithubcomsharkcowVW-e-UP-OBD-CAN-logs

296 Development notes 243

Open Vehicles

244 Chapter 29 VW e-Up via Comfort CAN (T26A)

CHAPTER 30

Command Line Interpreter

The command line interpreter or command parser presented by the OVMS async serial console is constructed as a treeof command word tokens Enter a single question mark followed by RETURN to get the root command list like this

OVMS Run a scriptbms BMS frameworkboot BOOT frameworkcan CAN framework

A root command may be followed by one of a list of additional tokens called subcommands which in turn may befollowed by further subcommands down multiple levels forming a tree The command and subcommand tokens maybe followed by parameters Use question mark at any level in the command sequence to get the list of subcommandsapplicable at that point If the next item to be entered is a parameter rather than a subcommand then a usage mes-sage will be displayed to indicate the required or optional parameters The usage message will also be shown if thecommand as entered is not valid The usage message is described in further detail below

Command tokens can be abbreviated so long as enough characters are entered to uniquely identify the command Op-tionally pressing TAB at that point will auto-complete the token If the abbreviated form is not sufficient to be unique(in particular if no characters have been entered yet) then TAB will show a concise list of the possible subcommandsand retype the portion of the command line already entered so it can be completed Pressing TAB is legal at any pointin the command if there is nothing more that can be completed automatically then there will just be no response tothe TAB

301 OvmsCommand API

Each command word token in the tree is represented by an OvmsCommand object TheOvmsCommandRegisterCommand() function is used to create and add a command or subcommand to-ken object into the tree returning an OvmsCommand pointer to the new object New commands are added to theroot of the tree using the global MyCommandAppRegisterCommand() Subcommands are added as childrenof a command by calling RegisterCommand() using the OvmsCommand pointer to the parent object thusbuilding the tree For example

245

Open Vehicles

OvmsCommand cmd_wifi = MyCommandAppRegisterCommand(wifiWIFI framework wifi_rarr˓status)cmd_wifi-gtRegisterCommand(statusShow wifi statuswifi_status)cmd_wifi-gtRegisterCommand(reconnectReconnect wifi clientwifi_reconnect)

The RegisterCommand() function takes the following arguments

bull const char name ndash the command token

bull const char title ndash one-line description for the command list

bull void (execute)() ndash does the work of the command

bull const char usage ndash parameter description for ldquoUsagerdquo message

bull int min ndash minimum number of parameters allowed

bull int max ndash maximum number of parameters allowed

bull bool secure ndash true for commands permitted only after enable

bull int (validate)() ndash validates parameters as explained later

The RegisterCommand() function tolerates duplicate registrations of the same name at the same node of the treeby assuming that the other arguments are also the same and returning the existing object This allows mulitple modulesthat can be configured independently to share the same top-level command For example the obdii command is sharedby the vehicle and obd2ecu modules

Modules that can be dynamically loaded and unloaded must remove their commands from the tree usingUnregisterCommand(const char name) before unloading

Itrsquos important to note that many of the arguments to RegisterCommand() can and should be defaulted The defaultvalues are as follows

execute = NULLusage = min = 0max = 0secure = truevalidate = NULL

For example for secure non-terminal commands (those with child subcommands) such as the top-level frameworkcommands like bms in the list of root commands shown earlier the model should simply be

RegisterCommand(name Title)

For secure terminal subcommands (those with no children) that donrsquot require any additional parameters the modelshould be

RegisterCommand(name Title execute)

This model also applies if the command has children but the command itself wants to execute a default operation if nosubcommand is specified It is incorrect to specify min = 0 max = 1 to indicate an optional subcommand that isindicated by the presence of the execute function along with a non-empty array of child subcommands

Any command with required or optional parameters should provide a ldquousagerdquo string hinting about the parameters inaddition to specifying the minimum and maximum number of parameters allowed

RegisterCommand(name Title execute usage min max)

246 Chapter 30 Command Line Interpreter

Open Vehicles

The usage argument only needs to describe the parameters that follow this (sub)command because the full usagemessage is dynamically generated The message begins with the text ldquoUsage rdquo followed by the names of the ancestorsof this subcommand back to the root of the tree plus the name of this subcommand itself That is the message startswith all the tokens entered to this point The message continues with a description of subcommands andor parametersthat may be entered next as specified by the usage string

Note The usage message is not resricted to a single line the usage string can include additional lines of explana-tory text separated by n (newline) characters to help convey the meaning of the paramters and the purpose of thecommand

The usage string syntax conventions for specifying alternative and optional parameters are similar to those of usagemessages in Unix-like systems The string can also include special codes to direct the dynamic generation of themessage

bull $C expands to the list of children commands as child1|child2|child3

bull [$C] expands to list optional children as [child1|child2|child3]

bull $G$ expands to the usage string of the first child this would typically used after $C so the usage message showsthe list of children and then the parameters or next-level subcommands that can follow the children This isuseful when the usage string is the same for all or most of the children as in this example

Usage power adc|can1|can2|can3|egpio|esp32|sdcard|simcom|spi|wifirarr˓deepsleep|devel|off|on|sleep|status

bull $Gfoo$ expands to the usage of the child named ldquofoordquo this variant would be used when not all the childrenhave the same usage but it would still be helpful to show the usage of one thatrsquos not first

bull $L lists a full usage message for each of the children on separate lines This provides more help than justshowing the list of children but at the expense of longer output

For subcommands that take parameters the usage string contains explicit text to list the parameters

bull Parameter names or descriptions are enclosed in angle brackets to distinguish the them from command tokensfor example ltmetricgt ltvaluegt Since the angle brackets demarcate each parameter spaces may be in-cluded in the description

bull Parameters that are optional are further enclosed in square brackets like ltidgt ltnamegt [ltvaluegt]

bull When there are alternative forms or meanings for a parameter the alternatives are separated by vertical bar asin lttask names or idsgt||= which indicates that the parameter can be either of the characters or =instead of a list of task names or ids A variant form encloses the alternatives in curly braces as in ltparamgtltinstancegt |

bull One or more additional lines of explanatory text can be included like this

ltidgtnUse ID from connection list 0 to close all

For non-terminal commands (those with children subcommands) the usage argument can be omitted because thedefault value of is interpreted as $C For commands that have children subcommands that are optional (because anexecute function is included) the default usage argument is interpreted as [$C]

3011 Execute Function

The execute function performs whatever work is required for the command Its signature is as follows

301 OvmsCommand API 247

Open Vehicles

void (execute)(int verbosity OvmsWriter writer OvmsCommand cmd int argc constrarr˓char const argv)

bull int verbosity ndash tells how much output is appropriate (eg shell vs SMS)

bull OvmsWriter writer ndash object to which output is delivered eg console

bull OvmsCommand cmd ndash the command that held the execute function pointer

bull int argc ndash how many parameters are being supplied to the function

bull const char const argv ndash the parameter list

Any output appropriate for the command is accomplished through puts() or printf() calls on the writerobject The cmd pointer may allow sharing one execute function among multiple related command objects andprovides access to members of the command object such as GetName()

The argc count will be constrained to the min and max values specified for the cmd object so if the minimum andmaximum are the same then the execute function does not need to check However if parameters are expected thentheir values must be validated

3012 Validate Function

Most commands do not need to specify a validate function It supports extensions of the original command parserdesign for two use cases

1 For commands that store the possible values of a parameter in a NameMapltTgt or CNameMapltTgt thevalidate function enables TAB auto-completion when entering that parameter

2 The original design only allowed parameters to be collected by the terminal subcommand That forced anunnatural word order for some commands The validate function enables non-terminal subcommands totake one or more parameters followed by multiple levels of children subcommands The parameters may bestrings looked up in a NameMapltTgt or CNameMapltTgt or they could be something else like a number that canbe validated by value The validate function must indicate success for parsing to continue to the childrensubcommands The return value is the number of parameters validated if successful or -1 if not

The signature of the validate function is as follows

int (validate)(OvmsWriter writer OvmsCommand cmd int argc const char constrarr˓argv bool complete)

bull OvmsWriter writer ndash object to which output is delivered eg console

bull OvmsCommand cmd ndash the command that held the validate function pointer

bull int argc ndash how many parameters are being supplied to the function

bull const char const argv ndash the parameter list

bull bool complete ndash true for TAB completion of the last parameter (case 1) false when validating intermediateparameters before calling execute on the terminal descendant command (case 2)

The writer and cmd arguments are the same as for the execute function The argc count is never more than maxand if complete is false never less than min However when complete is true to request TAB auto-completionand max is greater than 1 argc will be at least 1 but may be less than min because it indicates how many parametershave been entered so far The TAB auto-completion is performed on the last parameter entered after validating anypreceding parameters If min and max are both 1 then it is not necessary to check argc

If the acceptable values of a parameter are stored in a NameMapltTgt or CNameMapltTgt those maps implement aValidate() function that will perform the validation needed for the validate function covering both the true

248 Chapter 30 Command Line Interpreter

Open Vehicles

and false cases of complete Those maps also implement a FindUniquePrefix() function that may be used tovalidate preceding parameters for commands that take multiple parameters

The config_validate() function for the config command in mainovms_configcpp is an example imple-mentation of use case 1 for a command taking three parameters with TAB auto-completion on the first two

int config_validate(OvmsWriter writer OvmsCommand cmd int argc const charrarr˓const argv bool complete)if (MyConfigismounted())return -1

argv[0] is the ltparamgtif (argc == 1)return MyConfigm_mapValidate(writer argc argv[0] complete)

argv[1] is the ltinstancegtif (argc == 2)OvmsConfigParam const p = MyConfigm_mapFindUniquePrefix(argv[0])if (p) ltparamgt was not valid so cant check ltinstancegtreturn -1

return (p)-gtm_mapValidate(writer argc argv[1] complete)

argv[2] is the value which we cant validatereturn -1

The location command in componentsovms_locationsrcovms_locationcpp is an example of usecase 2 as it includes an intermediate parameter and also utilizes the $L form of the usage string

OVMS location action enter Usage location action enter ltlocationgt acc ltprofilegtUsage location action enter ltlocationgt homelink 1|2|3Usage location action enter ltlocationgt notify lttextgt

The following excerpt shows the implementation of the location_validate() function and a subset of theRegisterCommand() calls to build the command subtree This example shows how simple the validation codecan be ndash sometimes just one line to call Validate() In this case the code does need to check argc because thefunction is shared by multiple subcommand objects taking 1 or 2 parameters

int location_validate(OvmsWriter writer OvmsCommand cmd int argc const charrarr˓const argv bool complete)if (argc == 1)return MyLocationsm_locationsValidate(writer argc argv[0] complete)

return -1

OvmsCommand cmd_location = MyCommandAppRegisterCommand(locationLOCATIONrarr˓framework)OvmsCommand cmd_action = cmd_location-gtRegisterCommand(actionSet an action for

rarr˓a location)OvmsCommand cmd_enter = cmd_action-gtRegisterCommand(enterSet an action upon

rarr˓entering a location NULL ltlocationgt $L 1 1 true location_validate)OvmsCommand enter_homelink = cmd_enter-gtRegisterCommand(homelinkTransmit

rarr˓Homelink signal)enter_homelink-gtRegisterCommand(1Homelink 1 signallocation_homelink 0 0

rarr˓true)enter_homelink-gtRegisterCommand(2Homelink 2 signallocation_homelink 0 0

rarr˓true) (continues on next page)

301 OvmsCommand API 249

Open Vehicles

(continued from previous page)

enter_homelink-gtRegisterCommand(3Homelink 3 signallocation_homelink 0 0rarr˓true)cmd_enter-gtRegisterCommand(accACC profilelocation_accltprofilegt 1 1

rarr˓true)cmd_enter-gtRegisterCommand(notifyText notificationlocation_notifylttextgt 1

rarr˓ INT_MAX true)

250 Chapter 30 Command Line Interpreter

CHAPTER 31

CAN Bus Data Logging

OVMS can be used as CAN bus datalogging tool

311 Physical Connections

OVMS hardware V3 supports up to three CAN bus connections The connections to OVMS are as follows

DB9-F Signal----- ------

2 CAN1-L7 CAN1-H

4 CAN2-L5 CAN2-H

6 CAN3-L8 CAN3-H

Note the board schematics refer to CAN012 These correspond to CAN123 here in the documentation and sourcecode The first is handled by ESP32 io lines directly and CAN23 are handled by MCP2515 ICs via SPI from theESP

CAN1 is the fastest bus use this one if possible The CAN logging tool is able to log all buses at the same time to thesame file or stream

Vehicle CAN bus(s) are usually accesable via the vehiclersquos OBD2 port Most modern cars have multiple CAN bussesThe OBD2 lsquostandardrsquo CAN will be available on OBD2 pin 6 CAN-H and pin 14 CAN-L However modern vehicles(especially EVrsquos) often have other CAN buses available on non-standard OBD2 pins

A voltmeter (ideally oscilloscope) can be used to determine which OBD2 pins contain CAN data

bull Can high pins should normally be between 25 and 35 volts (to ground) - maybe 27 to 33 volts if there istraffic

bull Can low pins should normally be between 15 and 25 volts (to ground) - maybe 17 to 23 volts if there is traffic

251

Open Vehicles

Pre-fabricated OBD2 gt DB9-F for several specific vehicles can be purchased via OpenVehicles

312 Enable OVMS CAN bus

Once physical connections has been made and OVMS is up and running connect to OVMS shell via web browser SSH or serial

If a specific vehicle module is loaded the CAN bus will already be enabled in OVMS To check which CAN buses areenabled use

OVMS can list

If no vehicle module is selected the CAN bus must be started eg

OVMS can can1 start listen 500000

This will enable CAN1 in listen mode (read only) at 500k baud active can be used instead of listen to enableread-write mode To stop a CAN1 bus

OVMS can can1 stop

OVMS supports the following CAN bauds rates 100000 125000 250000 500000 1000000

313 Logging to SD card

It is possible to view CAN data directly in OVMS monitor shell however since modern cars have very busy CANbuses there is often too much data which swamps the monitor or exceeds the logging queue resulting in droppedmessages Logging to SD card is the better option

If using a good quality SD card with a current OVMS V3 module (ie PCB revision 32 20190523 or later) increasethe SD card speed for best performance with

config set sdcard maxfreqkhz 20000

Start logging all CAN messages using CRTD log file format with

ovms can log start vfs crtd sdcancrtd

or log specific CAN packets by applying a filter eg 0x55b the Nissan LEAF SoC CAN message

ovms can log start vfs crtd sdcancrtd 55b

Other CAN log file formats are supported eg crtd gvret-a gvret-b lawricel pcap raw

Check CAN logging satus with

ovms can log status

To Stop CAN logging

ovms can log stop

Note the can logging must be stopped before the file can be viewed

To View the CAN log

ovms vfs head sdcancrtd

tail and cat commands can also be used However be careful the log file can quickly become very large cat mayoverwhelm the shell

The log file can also be viewed in a browser with httpltovms-ipaddressgtsdcancrtd

252 Chapter 31 CAN Bus Data Logging

Open Vehicles

The logfiles can then be imported into a tool like SavvyCan for analysis

314 Network Streaming

CAN data can be streamed directly to SavvyCan (or other compatible application) using the OVMS tcpserver CANlogging feature over a local network Start tcpserver CAN logging with

OVMS can log start tcpserver discard gvret-b 23

This will start a tcpserver on port 23 (as required by SavvyCan) using the GVRET format supported by SavvyCAN

Once OVMS CAN logging tcpserver is running open up SavvyCan and select

Connection gt Add New Device Connection gt Network Connection

then enter the OVMS WiFi local network IP address (no port number required) CAN packets should now appearstreaming into SavvyCan

Note CAN tcpserver network streaming is a beta feture currently in edge firmware and may be buggy

315 Optimizing the Performance

On can log stop the system will output some statistics Check especially the dropped frame count Framedrops can occur because the system was busy with other tasks like handling network traffic There are two options tooptimize this

a) Reduce background activities ie stop all services not needed for the logging If possible do the loggingwithout an active vehicle module (eg set the ldquoemptyrdquo vehicle via vehicle module NONE)

b) Raise the log queue size The default queue size has a capacity of 100 frames To eg allow 200 frames doconfig set can logqueuesize 200

314 Network Streaming 253

Open Vehicles

254 Chapter 31 CAN Bus Data Logging

CHAPTER 32

CRTD CAN Log Format

321 Introduction

The CRTD CAN Log format is a textual log file format designed to store information on CAN bus frames and eventsIt was introduced as a human readable file format capable of supporting data dumps from multiple CAN buses

Files or network data streams in CRTD format contain only textual data in UTF-8 with each record being on anindividual line terminated by a single linefeed (ascii 10) character or CRLF (ascii 13 ascii 10)

Each line is made up from the following fields separated by single spaces (ASCII 32)

bull Timestamp Julian timestamp seconds and millisecondsmicroseconds separated by a decimal point

bull Record Type Mnenomic to denote the record type

bull Record Data The remaining data is dependant on the record type

Here are some examples

1542473901020305 1R11 1542473901020305 2T11 1542473901020305 R11 1542473901021 1R11

322 History

bull 10 Initial version supporting CXX R11 R29 T11 and T29 messages only

bull 20 Add optional bus ID prefix to record types

bull 30 Add support for comment commands and clarify documentation inconsistencies

255

Open Vehicles

323 Specification

CRTD files are UTF-8 text files using LF or CR+LF line termination to separate each record

ltcrtd-filegt = ltcrtd-recordgt [CR] LF

The records are formatted as follows

ltcrtd-recordgt = lttimestampgt ltspacegt ltcrtd-typegt lttimestampgt = ltjuliansecondsgt [ ltmillisecondsgt| ltmicrosecondsgt ] ltjuliansecondsgt = ltdigtigt ltdigitgt ltmillisecondsgt = ltdigitgt ltdigitgt ltdigitgtltmicrosecondsgt = ltdigitgt ltdigitgt ltdigitgt ltdigitgt ltdigitgt ltdigitgt ltdigitgt = [ 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |8 | 9 ] lthexdigitgt = [ ltdigitgt

A | B | C | D | E | F | a | b | c | d | e | f ]

ltspacegt = ASCII character 32 decimal (0x20 hex)

ltcrtd-typegt = [ ltcrtd-commentgt | ltcrtd-transmitgt | ltcrtd-receivegt ]

ltcrtd-commentgt = CXX ltspacegt lttextual-commentgt

ltcrtd-receivegt = R11 ltspacegt ltrxtx-datagt

ltbusgtR11 ltspacegt ltrxtx-datagtR29 ltspacegt ltrxtx-datagtltbusgtR29 ltspacegt ltrxtx-datagt

ltcrtd-transmitgt = T11 ltspacegt ltrxtx-datagt

ltbusgtT11 ltspacegt ltrxtx-datagtT29 ltspacegt ltrxtx-datagtltbusgtT29 ltspacegt ltrxtx-datagt

ltbusgt = ltdigitgt ltdigitgt

ltrxtx-datagt = ltcan-idgt ltspacegt ltcan-bytegt ltcan-idgt = lthexdigitgt lthexdigitgt ] ltcan-bytegt =lthexdigitgt [ lthexdigitgt ]

324 Timestamps

Timestamps can be provided in either millisecond or microsecond precision It is recommended that they be based onthe julian seconds in UTC but there is no specific requirement for that It is suggested that a comment may optionallybe placed at the start of the file to describe the timezone The timestamps should however increase monotonically inthe file (ie time flows forward with subsequent records)

If the timestamp contains 3 digits after the decimal point it should be consider millisecond precision and handledappropriately Similarly if the timestamp contains 6 digits after the decimal point it should be considered microsecondprecision

325 Case Independence

CAN IDs and data bytes are in case-independent hex and may or may not be padded with leading zeros CRTDprocessors should be as flexible as possible in their handling of this

256 Chapter 32 CRTD CAN Log Format

Open Vehicles

326 CAN Bus Designation

Record types may optionally be prefixed by the CAN bus number (1 n) If no bus number is provided 1 shouldbe assumed

327 Data bytes

The number of data bytes is limited by the CAN specification to a maximum of 8 bytes Similarly the range ofacceptable CAN IDs is limited by the 11bit 29bit encoding in the CAN protocol specification

328 Record Types

Each record can be one of a comment receive or transmit data Other record types should be discarded to allow newrecord types to be introduced without breaking existing processors

3281 Comment Records

Comment records start with the letter lsquoCrsquo and the record type has two characters following to denote the sub-typeThe rest of the record is to be considered a comment (or data for the command)

The following comment record types are defined

bull CXX General textual comment

bull CER An indication of a (usually recoverable) error

bull CST Periodical statistics

bull CEV An indication of an event

bull CVR Version of CRTD protocol adhered to (with version number as text comment)

and the following command record types are defined

bull CBC A command to configure a CAN bus

bull CDP A command to pause the transmission of messages

bull CDR A command to resume the transmission of messages

bull CFC A command to clear all filters for this connection

bull CFA A command to add a filter for this connection

Here are some examples

169971289 CXX Info Typecrtd Pathsdcan3crtd Filter30-ffffffffrarr˓VehicleTSHK19292299819 CEV vehiclealert this is a textual vehicle alert198923283738 CST intr=0 rxpkt=0 txpkt=0 errflags=0 rxerr=0 txerr=0 rxovr=0 txovr=0rarr˓txdelay=0 wdgreset=02783384726 CER intr=0 rxpkt=0 txpkt=0 errflags=0 rxerr=0 txerr=0 rxovr=0 txovr=0rarr˓txdelay=0 wdgreset=0

326 CAN Bus Designation 257

Open Vehicles

3282 Command Record CBC - Configure a CAN bus

The CBC command is used to configure a CAN bus It should be prefixed with the bus ID in the usual way or defaultto bus 1 if not defined

The command should have the following space separated parameters

bull mode either L for listen or A for active

bull speed the baud rate of the CAN bus

3283 Command Record CDP - Pause transmission

The CDP command is used to pause transmission of messages for this connection Upon receiving this commandthe device producing CRTD logs should henceforth discard those logs and not transmit them to this connection untilresumed

3284 Command Record CDR - Resume transmission

The CDR command is used to resume transmission of messages for this connection It clears the condition previouslyset by the CDP command

3285 Command Record CFC - Clear filters

The CFC command is used to clear the message filters for this connection

By default connections receive all messages for all CAN buses and that is indicated by the filter list being initiallyempty This command resets the filters to this default condition

Note that external to the per-message filters CAN data sources may also have incoming filters that apply to all incom-ing data (regardless of the logging destination) These incoming filters are not affected by this

3286 Command Record CFA - Add a filter

The CFA command is used to add a filter to the list of message filters for this connection If one or more filters aredefined only messages matching those filters will be forwarded

The command should have the filter passed as a single parameter

bull filter the filter to add

Filters are formatted as

Filter = ltbusgt | ltidgt[-ltidgt] | ltbusgtltidgt[-ltidgt]

For example

bull 22a0-37f for bus 2 IDs 0x2a0 - 0x37f

bull 10-37f for bus 1 IDs 0x000 - 0x37f

bull 3 for bus 3 all messages

bull 100-200 for bus 1 IDs 0x100 - 0x200

258 Chapter 32 CRTD CAN Log Format

Open Vehicles

3287 Received Frame Record

Received frame records describe a frame received from the CAN bus and start with the letter lsquoRrsquo Two types aredefined

bull R11 A standard 11bit ID CAN frame

bull R29 An extended 29bit ID CAN frame

The record type is followed by the frame ID (in hexadecimal) and then up to 8 bytes of CAN frame data

Here are some examples

1542473901020305 1R11 213 00 00 00 00 c0 01 00 001542473901020970 2R11 318 92 0b 13 10 11 3a 00 001542473901021259 2R11 308 00 ff f6 a6 06 03 80 001542473901021560 2R11 408 001542473901030341 1R11 358 18 08 20 00 00 00 00 201542473901034872 2R11 418 801542473901035514 1R11 408 101542473901036694 3R11 41C 101542473901040289 R11 428 00 301542473901042516 2R11 168 e0 7f 70 00 ff ff ff1542473901042809 2R11 27E c0 c0 c0 c0 00 00 00 001542473901043073 1R11 248 29 29 0f bc 01 10 00

3288 Transmitted Frame Record

Transmitted frame records describe a frame transmitted onto the CAN bus and start with the letter lsquoTrsquo Two types aredefined

bull T11 A standard 11bit ID CAN frame

bull T29 An extended 29bit ID CAN frame

The record type is followed by the frame ID (in hexadecimal) and then up to 8 bytes of CAN frame data

Here are some examples

1542473901020305 1T11 213 00 00 00 00 c0 01 00 001542473901020970 2T11 318 92 0b 13 10 11 3a 00 001542473901021259 2T11 308 00 ff f6 a6 06 03 80 001542473901021560 2T11 408 001542473901030341 1T11 358 18 08 20 00 00 00 00 201542473901034872 2T11 418 801542473901035514 1T11 408 101542473901036694 3T11 41C 101542473901040289 T11 428 00 301542473901042516 2T11 168 e0 7f 70 00 ff ff ff1542473901042809 2T11 27E c0 c0 c0 c0 00 00 00 001542473901043073 1T11 248 29 29 0f bc 01 10 00

329 Conclusions

The CRTD format is intended to be very simple to process either by automated code or humans manually It can beloaded into text editors for manipulation (search replace etc) and easily processed by command line tools such aslsquocutrsquo lsquogreprsquo lsquoawkrsquo etc

329 Conclusions 259

Open Vehicles

260 Chapter 32 CRTD CAN Log Format

CHAPTER 33

Web Framework amp Plugins

331 TLDR Examples

The following examples include their documentation in the HTML page and source Read the source and install themas plugins (see below) to see how they work

3311 Metric Displays

OVMS V3 is based on metrics Metrics can be single numerical or textual values or complex values like sets and arraysThe web framework keeps all metrics in a global object which can be read simply by eg metrics[vbsoc]

Metrics updates (as well as other updates) are sent to all DOM elements having the receiver class To hook intothese updates simply add an event listener for msgmetrics

Listening to the event is not necessary though if all you need is some metrics display This is covered by the metricwidget class family as shown here

261

Open Vehicles

Single Values amp Charts

The following example covers

bull Text (String) displays

bull Number displays

bull Progress bars (horizontal light weight bar charts)

bull Gauges

bull Charts

Gauges amp charts use the HighCharts library which is included in the web server The other widgets are simple standardBootstrap widgets extended by an automatic metrics value update mechanism

Highcharts is a highly versatile charting system For inspiration have a look at

bull httpswwwhighchartscomdemo

bull httpswwwhighchartscomdocs

Wersquore using styled mode so some options donrsquot apply but everything can be styled by standard CSS

Install the example as a web page plugin

metricshtm (hint right click save as)

262 Chapter 33 Web Framework amp Plugins

Open Vehicles

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltdiv class=panel panel-primarygt6 ltdiv class=panel-headinggtMetrics Displays TestDemoltdivgt7 ltdiv class=panel-bodygt8

9 ltpgtOVMS V3 is based on metrics Metrics can be single numerical or textual valuesrarr˓or complex values

10 like sets and arrays The web framework keeps all metrics in a global objectrarr˓which can be read

11 simply by eg ltcodegtmetrics[vbsoc]ltcodegtltpgt12

13 ltpgtMetrics updates (as well as other updates) are sent to all DOM elements havingrarr˓the

14 ltcodegtreceiverltcodegt class To hook into these updates simply add an eventrarr˓listener for

15 ltcodegtmsgmetricsltcodegt Listening to the event is not necessary if all yourarr˓need is some metrics

16 display This is covered by the ltcodegtmetricltcodegt class family as shown hererarr˓ltpgt

17

18 ltpgt19 ltbutton type=button class=btn btn-default action-gendatagtGenerate random

rarr˓dataltbuttongt20 ltbutton type=button class=btn btn-default action-showsrcgtShow page sourcelt

rarr˓buttongt21 ltpgt22

23 lthrgt24

25 ltdiv class=receivergt26

27 lth4gtBasic usagelth4gt28

29 ltpgtAll elements of class ltcodegtmetricltcodegt in a ltcodegtreceiverltcodegt arerarr˓checked for the

30 ltcodegtdata-metricltcodegt attribute If no specific metric class is given therarr˓metric value

31 is simply set as the element text ltspan class=metric data-metric=mnetrarr˓providergtltspangt

32 is your current network providerltpgt33

34 lth4gtText ampamp Numberlth4gt35

36 ltpgtltcodegtnumberltcodegt ampamp ltcodegttextltcodegt displays get the metric valuerarr˓set in their child of

37 class ltcodegtvalueltcodegt They may additionally have labels and units ltcodegtrarr˓data-precltcodegt can

38 be used on ltcodegtnumberltcodegt to set the precision ltcodegtdata-scaleltcodegtrarr˓to scale the raw

39 values by a factor They have fixed min widths and float by default so yourarr˓can simply put

40 multiple displays into the same containerltpgt41

42 ltdiv class=clearfixgt

(continues on next page)

331 TLDR Examples 263

Open Vehicles

(continued from previous page)

43 ltdiv class=metric number data-metric=vethrottle data-prec=0gt44 ltspan class=labelgtThrottleltspangt45 ltspan class=valuegtltspangt46 ltspan class=unitgtltspangt47 ltdivgt48 ltdiv class=metric number data-metric=vb12vvoltageref data-prec=1gt49 ltspan class=valuegtltspangt50 ltspan class=unitgtVltsubgtrefltsubgtltspangt51 ltdivgt52 ltdiv class=metric text data-metric=mnetprovidergt53 ltspan class=labelgtNetworkltspangt54 ltspan class=valuegtltspangt55 ltdivgt56 ltdivgt57

58 lth4gtProgress Barlth4gt59

60 ltpgtBootstrap ltcodegtprogressltcodegt bars can be used as lightweight graphicalrarr˓indicators

61 Labels and units are available also ltcodegtdata-precltcodegt and ltcodegtdata-rarr˓scaleltcodegt

62 Again all you need is a bit of markupltpgt63

64 ltdiv class=clearfixgt65 ltdiv class=metric progress data-metric=vethrottle data-prec=0gt66 ltdiv class=progress-bar progress-bar-success value-low text-left role=

rarr˓progressbar67 aria-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gt68 ltdivgt69 ltspan class=labelgtThrottleltspangt70 ltspan class=valuegtltspangt71 ltspan class=unitgtltspangt72 ltdivgt73 ltdivgt74 ltdivgt75 ltdiv class=metric progress data-metric=vb12vvoltageref data-prec=1gt76 ltdiv class=progress-bar progress-bar-info value-low text-left role=

rarr˓progressbar77 aria-valuenow=0 aria-valuemin=5 aria-valuemax=15 style=width0gt78 ltdivgt79 ltspan class=labelgt12V refltspangt80 ltspan class=valuegtltspangt81 ltspan class=unitgtVltspangt82 ltdivgt83 ltdivgt84 ltdivgt85 ltdivgt86

87 lth4gtGauges ampamp Chartslth4gt88

89 ltpgtThe OVMS web framework has builtin support for the highly versatile ltbgtrarr˓Highcharts libraryltbgt

90 with loads of chart types and options ltcodegtchartltcodegt metric examplesltpgt91

92 ltdiv class=rowgt93 ltdiv class=col-sm-6gt94 ltdiv class=metric chart data-metric=vethrottle style=height220pxgt

(continues on next page)

264 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

95 ltdiv class=chart-box gaugechart id=throttle-gaugegt96 ltdivgt97 ltdivgt98 ltdiv class=col-sm-6gt99 ltdiv class=metric chart data-metric=vbcvoltagevbcvoltagemin

rarr˓style=height220pxgt100 ltdiv class=chart-box barchart id=cell-voltagesgt101 ltdivgt102 ltdivgt103 ltdivgt104

105 ltpgtltbutton type=button class=btn btn-default action-gendatagtGenerate randomrarr˓dataltbuttongtltpgt

106

107 ltpgtFor charts a little bit of scripting is necessary108 The scripts for these charts contain the chart configuration part of which

rarr˓is the update109 function you need to define The update function translates metrics data into

rarr˓chart data110 This is trivial for single values like the throttle the cell voltage chart

rarr˓is an example111 on basic array processingltpgt112

113 ltpgtAlso while charts ltemgtcanltemgt be defined with few options youll ltemgtloverarr˓ltemgt to explore

114 all the features and fine tuning options provided by Highcharts Forrarr˓inspiration

115 have a look at the lta target=_blank href=httpswwwhighchartscomdemogtrarr˓Highcharts demosltagt

116 and the lta target=_blank href=httpswwwhighchartscomdocsgtHighchartsrarr˓documentationltagt

117 Were using lta target=_blank href=httpswwwhighchartscomdocschart-rarr˓design-and-stylestyle-by-cssgt

118 styled modeltagt so some options dont apply but everything can be styled byrarr˓standard CSSltpgt

119

120 ltdivgt121

122 ltdivgt123 ltdivgt124

125 ltscriptgt126 (function()127

128 Get page source before chart rendering 129 var pagesrc = $(main)html()130

131 Init throttle gauge 132 $(throttle-gauge)chart(133 chart 134 type gauge135 spacing [0 0 0 0]136 margin [0 0 0 0]137 animation duration 500 easing easeOutExpo 138 139 title text Throttle verticalAlign middle y 75 140 credits enabled false

(continues on next page)

331 TLDR Examples 265

Open Vehicles

(continued from previous page)

141 tooltip enabled false 142 plotOptions 143 gauge dataLabels enabled false overshoot 1 144 145 pane [146 startAngle -125 endAngle 125 size 100 center [50 60]147 ]148 yAxis [149 title text 150 className throttle151 reversed false152 min 0 max 100153 plotBands [154 from 0 to 60 className green-band 155 from 60 to 80 className yellow-band 156 from 80 to 100 className red-band 157 ]158 minorTickInterval auto minorTickLength 5 minorTickPosition inside159 tickPixelInterval 40 tickPosition inside tickLength 13160 labels step 2 distance -28 x 0 y 5 zIndex 2 161 ]162 series [163 name Throttle data [0]164 className throttle165 animation duration 0 166 pivot radius 10 167 dial radius 88 topWidth 1 baseLength 20 baseWidth 10

rarr˓rearLength 20 168 ]169 Update method 170 onUpdate function(update) 171 Create gauge data set from metric172 var data = [ metrics[vethrottle] ]173 Update chart174 thisseries[0]setData(data)175 176 )177

178 Init cell voltages chart 179 $(cell-voltages)chart(180 chart 181 type column182 animation duration 500 easing easeOutExpo 183 184 title text Cell Voltages 185 credits enabled false 186 tooltip 187 enabled true188 shared true189 headerFormat Cell pointkeyltbrgt190 pointFormat seriesname ltbgtpointyltbgtltbrgt191 valueSuffix V192 193 legend enabled true 194 xAxis 195 categories []196

(continues on next page)

266 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

197 yAxis [198 title text null 199 labels format value2fV 200 tickAmount 4 startOnTick false endOnTick false201 floor 33 ceiling 42202 minorTickInterval auto203 ]204 series [205 name Current data []206 className cell-voltage207 animation duration 0 208 209 name Minimum data []210 className cell-voltage-min211 animation duration 0 212 ]213 Update method 214 onUpdate function(update) 215 Note the update parameter contains the actual update set216 You can use this to reduce chart updates to the actual changes217 For this demo we just use the global metrics object218 var219 m_vlt = metrics[vbcvoltage] || []220 m_min = metrics[vbcvoltagemin] || []221 Create categories (cell numbers) amp rounded values222 var cat = [] val0 = [] val1 = []223 for (var i = 0 i lt m_vltlength i++) 224 catpush(i+1)225 val0push(Number((m_vlt[i]||0)toFixed(3)))226 val1push(Number((m_min[i]||0)toFixed(3)))227 228 Update chart229 thisxAxis[0]setCategories(cat)230 thisseries[0]setData(val0)231 thisseries[1]setData(val1)232 233 )234

235 Test metrics generator 236 $(action-gendata)on(click function() 237 var td = 238 td[mnetprovider] = [hologramVodafoneTelekom][Mathfloor(Math

rarr˓random()3)]239 td[vethrottle] = Mathrandom() 100240 td[vb12vvoltageref] = 10 + Mathrandom() 4241 var m_vlt = [] m_min = []242 for (var i = 1 i lt= 16 i++) 243 m_vltpush(36 + Mathrandom() 05)244 m_minpush(34 + Mathrandom() 02)245 246 td[vbcvoltage] = m_vlt247 td[vbcvoltagemin] = m_min248 $(receiver)trigger(msgmetrics $extend(metrics td))249 )250

251 Display page source 252 $(action-showsrc)on(click function()

(continues on next page)

331 TLDR Examples 267

Open Vehicles

(continued from previous page)

253 $(ltdivgt)dialog(254 title Source Code255 body ltpre style=font-size85 heightcalc(100vh - 230px)gt256 + encode_html(pagesrc) + ltpregt257 size lg258 )259 )260

261 )()262 ltscriptgt

Vector Tables

Some metrics for example the battery cell voltages or the TPMS tyre health data may contain vectors of arbitrarysize Besides rendering into charts these can also be displayed by their textual values in form of a table

The following example shows a live view of the battery cell voltages along with their recorded minimum maximummaximum deviation and current warningalert state Alert states 0-2 are translated into icons

The metric table widget uses the DataTables library which is included in the web server The DataTables Javascriptlibrary offers a wide range of options to create tabular views into datasets

Install the example as a web page plugin

metrics-tablehtm (hint right click save as)

1 lt--2 Web UI page plugin DataTables metrics widget demonstration3 --gt4

5 ltstylegt6 td i

(continues on next page)

268 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

7 font-style normal8 font-size 1409 line-height 90

10 font-weight bold11 12 td iwarning color orange 13 td idanger color red 14 ltstylegt15

16

17 ltdiv class=panel panel-primary panel-single receiver id=my-receivergt18 ltdiv class=panel-headinggtMetrics Table Widget Exampleltdivgt19 ltdiv class=panel-bodygt20

21 ltpgtThe following table shows a live view of the battery cell voltages along withrarr˓their recorded

22 minimum maximum maximum deviation and current warningalert stateltpgt23 ltpgtTry resizing the window or using a mobile phone to see how the table adapts to

rarr˓the screen24 width The table will also keep the selected sorting over data updatesltpgt25 ltpgtHint if you dont have live battery cell data click the generator button to

rarr˓create26 some random values The random data is only generated in your browser not on

rarr˓the moduleltpgt27

28 ltdiv class=metric table29 data-metric=vbcvoltagevbcvoltageminvbcvoltagemaxvbcvoltage

rarr˓devmaxvbcvoltagealertgt30 lttable class=table table-striped table-bordered table-hover id=v-table gt31 ltdivgt32

33 ltpgtSee lta target=_blank href=httpsdatatablesnetmanualgtDataTables manualrarr˓ltagt for all

34 options and API methods availableltpgt35

36 ltdivgt37 ltdiv class=panel-footergt38 ltpgtltbutton type=button class=btn btn-default action-gendatagtGenerate random

rarr˓dataltbuttongtltpgt39 ltdivgt40 ltdivgt41

42

43 ltscriptgt44 (function()45

46 Utilities47 var alertMap = 48 0 49 1 lti class=warninggtltigt50 2 lti class=dangergtltigt51 52

53 function fmtCode(value map) 54 return (map[value] == undefined) map[value] null55 56 function fmtNumber(value prec)

(continues on next page)

331 TLDR Examples 269

Open Vehicles

(continued from previous page)

57 return (value == undefined) Number(value)toFixed(prec) null58 59

60 Init table61 $(v-table)table(62 responsive true63 paging true64 searching false65 info false66 autoWidth false67 columns [68 title className dt-body-center width 6

rarr˓responsivePriority 1 69 title Voltage className dt-body-right width 22

rarr˓responsivePriority 3 70 title Minimum className dt-body-right width 22

rarr˓responsivePriority 4 71 title Maximum className dt-body-right width 22

rarr˓responsivePriority 5 72 title MaxDev className dt-body-right width 22

rarr˓responsivePriority 2 73 title Alert className dt-body-center width 6

rarr˓responsivePriority 1 74 ]75 rowId 076 onUpdate function(update) 77 Get vector metrics to display78 var v = [79 metrics[vbcvoltage] || []80 metrics[vbcvoltagemin] || []81 metrics[vbcvoltagemax] || []82 metrics[vbcvoltagedevmax] || []83 metrics[vbcvoltagealert] || []84 ]85 var lcnt = 086 vmap(el =gt lcnt = Mathmax(lcnt ellength))87 Transpose vectors to columns88 var l d = []89 for (l = 0 l lt lcnt l++) 90 dpush([91 l+192 fmtNumber(v[0][l] 2)93 fmtNumber(v[1][l] 2)94 fmtNumber(v[2][l] 2)95 fmtNumber(v[3][l] 3)96 fmtCode(v[4][l] alertMap)97 ])98 99 Display new data

100 thisclear()rowsadd(d)draw()101 102 )103

104

105 Test data generator106 $(action-gendata)on(click function() 107 var td =

(continues on next page)

270 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

108 var m_vlt = [] m_min = [] m_max = [] m_devmax = [] m_alert = []109 for (var i = 1 i lt= 16 i++) 110 m_vltpush(36 + Mathrandom() 05)111 m_minpush(34 + Mathrandom() 02)112 m_maxpush(38 + Mathrandom() 02)113 m_devmaxpush(-02 + Mathrandom() 04)114 m_alertpush(Mathfloor(Mathrandom() 3))115 116 td[vbcvoltage] = m_vlt117 td[vbcvoltagemin] = m_min118 td[vbcvoltagemax] = m_max119 td[vbcvoltagedevmax] = m_devmax120 td[vbcvoltagealert] = m_alert121 $(receiver)trigger(msgmetrics $extend(metrics td))122 )123

124 )()125 ltscriptgt

3312 Command Buttons amp Monitors

commandshtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltstylegt6 h3 7 margin-top 40px8 margin-bottom 20px9

10 ltstylegt11

12 ltdiv class=panel panel-primarygt13 ltdiv class=panel-headinggtCommands ampamp Monitorsltdivgt14 ltdiv class=panel-bodygt15

16 ltpgtCommand execution is only allowed for an authorized session The command API will17 output Unauthorized and a Login button as necessary The login state is also18 available in the global variable ltcodegtloggedinltcodegt To send the user to the19 login page and return to the current page after login call ltcodegtlogin()ltcodegt

rarr˓ltpgt20

21 ltpgt22 ltbutton type=button class=btn btn-default action-login onclick=login()gtLogin

rarr˓ltbuttongt23 ltbutton type=button class=btn btn-default action-logout onclick=logout()gt

rarr˓Logoutltbuttongt24 ltpgt25

26 ltscriptgt27 $(action-login)prop(disabled loggedin)28 $(action-logout)prop(disabled loggedin)29 ltscriptgt

(continues on next page)

331 TLDR Examples 271

Open Vehicles

(continued from previous page)

30

31

32 lth3gtCommand Execution on Loadlth3gt33

34 ltpgtTo execute a command automatically on page load simply add the ltcodegtmonitorltrarr˓codegt class

35 to an output element set ltcodegtdata-updcmdltcodegt to the command to be executedrarr˓and

36 ltcodegtdata-updcntltcodegt to 1ltpgt37

38 ltpre class=monitor data-updcmd=boot status data-updcnt=1gtFetching bootrarr˓statusltpregt

39

40 ltpgtOutput elements typically are ltcodegtsampltcodegt or ltcodegtpreltcodegt as commands41 normally output formatted plain text but any element can be used ltcodegtsamplt

rarr˓codegt42 by default compresses white space and has no visible area while ltcodegtpreltcodegt43 is visible and preserves all spacingltpgt44

45 ltpgtltcodegtupdcntltcodegt will count down to zero and stop or run indefinitely ifrarr˓started

46 below zero The execution interval can be given in ltcodegtdata-updintltcodegt (inrarr˓seconds)

47 You can set the data attributes any time using jQuery all monitors are checkedrarr˓and

48 updated by the framework once per secondltpgt49

50

51 lth3gtCommand Execution on Eventslth3gt52

53 ltpgtTo automatically trigger a monitor update on OVMS events additionally set the54 ltcodegtdata-eventsltcodegt attribute to a regular expression matching the event(s)

rarr˓of55 interest This example monitor lists the active network channels and automatically56 updates on all server connection eventsltpgt57

58 ltpgtltpre class=monitor59 data-events=server(connect|open|close|stop)60 data-updcmd=network list61 data-updcnt=1gtltpregtltpgt62

63 ltpgt64 Try65 lta class=btn btn-default onclick=windowopen( _blank width=400

rarr˓height=500)gtOpen new windowltagt66 lta class=btn btn-default href= data-cmd=server v2 stopgtStop V2 serverltagt67 lta class=btn btn-default href= data-cmd=server v2 startgtStart V2 serverltagt68 lta class=btn btn-default href= data-cmd=event raise serverfakeopengtSend

rarr˓fake eventltagt69 ltpgt70

71

72 lth3gtCommand Buttonslth3gt73

74 ltpgtA bootstrap button has the base class ltcodegtbtnltcodegt Add the command torarr˓execute

75 as attribute ltcodegtdata-cmdltcodegt and optionally the output element as(continues on next page)

272 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

76 ltcodegtdata-targetltcodegt and youre doneltpgt77

78 ltdiv class=rowgt79

80 ltdiv class=col-sm-6gt81 ltbutton type=button class=btn btn-default data-target=out1 data-cmd=

rarr˓wifi statusgt82 Wifi Status rarr ltcodegtampltsampampgtltcodegt83 ltbuttongt84 ltsamp id=out1 gt85 ltdivgt86

87 ltdiv class=col-sm-6gt88 ltbutton type=button class=btn btn-default data-target=out2 data-cmd=

rarr˓wifi statusgt89 Wifi Status rarr ltcodegtampltpreampgtltcodegt90 ltbuttongt91 ltpre id=out2 gt92 ltdivgt93

94 ltdivgt95

96 ltpgtAdd class ltcodegtsamp-inlineltcodegt or wrap in a ltcodegtullist-inlineltcodegt torarr˓place

97 the output element on the same line with the button Prefix the target with a +rarr˓to

98 append to itltpgt99

100 ltpgt101 External 12V power102 ltbutton type=button class=btn btn-info data-target=+out3 data-cmd=power

rarr˓ext12v ongtonltbuttongt103 ltbutton type=button class=btn btn-info data-target=+out3 data-cmd=power

rarr˓ext12v offgtoffltbuttongt104 ltsamp class=samp-inline id=out3 gt105 ltpgt106

107

108 lth3gtCombining Buttons ampamp Monitorslth3gt109

110 ltpgtBy combination of a button and a monitor you can let the button start a repeated111 execution of a command set ltcodegtdata-watchcntltcodegt on the button to the

rarr˓number of112 repetitions (default 0) and ltcodegtdata-watchintltcodegt to the interval in seconds113 (default 2)ltpgt114

115 ltpgt116 ltbutton type=button class=btn btn-default data-target=out4117 data-cmd=power cellular on data-watchcnt=-1 data-watchint=3gt118 Power on cellular modem ampamp get status updates every 3 seconds119 ltbuttongt120 ltpre class=monitor id=out4 data-updcmd=cellular status gt121 ltpgt122

123 ltpgtNote to stop a monitor set ltcodegtdata-updcntltcodegt to 0124 ltbutton type=button class=btn btn-default onclick=$(out4)data(updcnt

rarr˓0)gt(continues on next page)

331 TLDR Examples 273

Open Vehicles

(continued from previous page)

125 Stop updates126 ltbuttongtltpgt127

128

129 lth3gtExecute Javascriptlth3gt130

131 ltpgtTo execute Javascript code directly (ie without calling ltcodegtscript evalltrarr˓codegt)

132 simply exchange the ltcodegtdata-cmd data-updcmdltcodegt attribute by133 ltcodegtdata-js data-updjsltcodegt Exampleltpgt134

135 ltpgt136 ltbutton type=button class=btn btn-default data-target=out5137 data-js=JSONprint(OvmsConfigGetValues(vehicle))gt138 Show vehicle config139 ltbuttongt140 ltpre id=out5 gt141 ltpgt142

143 ltdivgt144 ltdivgt145

146

147 ltscriptgt148 (function()149 Show page source 150 var pagesrc = $(main)html()151 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +152 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)153 $(action-showsrc)on(click function() 154 $(ltdivgt)dialog(155 title Source Code156 body ltpre style=font-size85 heightcalc(100vh - 230px)gt157 + encode_html(pagesrc) + ltpregt158 size lg159 )160 )161 )()162 ltscriptgt

3313 Notifications

notificationshtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web file path eg sddevnotificationshtm5 - open in framework by eg httptest1localdevnotificationshtm6 --gt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtNotification TestDemoltdivgt

10 ltdiv class=panel-bodygt

(continues on next page)

274 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

11 lth4gtReceiverlth4gt12 lt--13 You can use data-subscriptions to preconfigure subscriptions14 Note types info error and alert get sent to all receivers15 --gt16 ltpre id=log class=receiver data-subscriptions=notifystreammyappgtIm

rarr˓preconfigured to receive notifystreammyappltpregt17 ltdivgt18 ltdiv class=panel-footergt19 ltdivgt20 ltlabel for=topicsgtTest commandltlabelgt21 ltinput type=text class=form-control font-monospace id=cmd value=notify

rarr˓raise text stream myappinput my first streamgt22 ltpgtJSON example ltcode class=autoselectgtnotify raise text stream myappinput

rarr˓myJSON streampi3141fib[1235813]ltcodegtltpgt23 ltbutton type=button class=btn btn-default id=action-execgtExecuteltbuttongt24 ltsamp id=cmdres gt25 ltdivgt26 ltdivgt27 ltlabel for=topicsgtTopic subscription (separate topics by space)ltlabelgt28 ltinput type=text class=form-control font-monospace id=topics value=

rarr˓notifystreammyappgt29 ltbutton type=button class=btn btn-default id=action-subgtSubltbuttongt30 ltbutton type=button class=btn btn-default id=action-unsubgtUnsubltbuttongt31 ltbutton type=button class=btn btn-default id=action-unsuballgtUnsub alllt

rarr˓buttongt32 ltdivgt33 ltdivgt34 ltdivgt35

36 ltscriptgt37

38 Receiver event handling39 $(log)on(msgnotify function(ev msg) 40 You normally should filter by typesubtype here eg41 if (subtypestartsWith(myapp)) 42 msg has type subtype and value43 Dump the msg into the receiver to show the structure44 $(this)text(JSONstringify(msg null 2))45

46 A convenient way to transport complex data is JSON47 To decode a JSON string use JSONparse()48 Note JSONparse() needs strict JSON syntax ie quoted names49 var payload50 try 51 payload = JSONparse(msgvalue)52 if (payload) 53 $(this)append(ltdivgtFound JSON payloadltdivgt)54 append($(ltdiv gt)text(JSONstringify(payload null 2))html())55 consolelog(payload)56 57 catch(e) 58 no JSON59 consolelog(e)60 61 )62

(continues on next page)

331 TLDR Examples 275

Open Vehicles

(continued from previous page)

63 Topic subscription can be done on page load using the data-subscriptions attribute64 andor on demand using the subscribe amp unsubscribe calls65 $(action-sub)on(click function(ev) 66 var topics = $(topics)val()67 $(log)subscribe(topics)text(added + topics)68 )69 The receiver remembers the subscriptions and does an auto unsubscribe on unload70 You can also unsubscribe topics dynamically Your data producer can check for71 active subscriptions using the MyNotifyHasReader() method72 $(action-unsub)on(click function(ev) 73 var topics = $(topics)val()74 $(log)unsubscribe(topics)text(removed + topics)75 )76 $(action-unsuball)on(click function(ev) 77 $(log)unsubscribe()text(removed all subscriptions)78 )79

80 Command handler81 $(action-exec)on(click function(ev) 82 var cmd = $(cmd)val()83 if (cmd) loadcmd(cmd cmdres)84 )85 $(cmd)on(keydown function(ev) 86 if (evwhich == 13) $(action-exec)trigger(click)87 )88

89 ltscriptgt

3314 Hook Plugins

hookshtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 --gt4

5 ltdiv class=panel panel-primarygt6 ltdiv class=panel-headinggtPage Hook Pluginsltdivgt7 ltdiv class=panel-bodygt8

9 ltpgtPlugins can provide pages on their own or extend existing pages To extend anrarr˓existing

10 page the page needs to support this by offering hook pointsltpgt11

12 ltpgtYou are not limited to the hook points for page modifications To insert yourrarr˓extensions

13 at arbitrary placesltpgt14 ltulgt15 ltligtinsert your extensions dynamically or with ltcodegtdisplaynoneltcodegtltligt16 ltligtregister a onetime handler for the ltcodegtloadltcodegt event on ltcodegtmainlt

rarr˓codegtltligt17 ltligtmove your extensions into place and show them from the event handlerltligt18 ltulgt19

20 ltpgtand yes youre also not limited to adding stuffltpgt(continues on next page)

276 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

21

22 lth3gtExamplelth3gt23

24 ltpgtThe following hook plugin adds a custom menu and some color to ltcodegthomeltcodegtrarr˓ltpgt

25

26 ltpre id=plugindisplay style=font-size85gtltpregt27

28 lth3gtAvailable Hookslth3gt29

30 ltpgtas of January 2019 This is work in progress if you miss a hook somewhererarr˓contact usltpgt

31

32 lttable class=table table-condensed font-monospacegt33 lttrgtltth colspan=2gtFrameworkltthgtlttrgt34 lttrgtlttdgt lttdgtlttdgthtmlpre headpost bodypost

rarr˓ lttdgtlttrgt35 lttrgtlttdgthome lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt36 lttrgtlttdgtdashboard lttdgtlttdgtbodypre

rarr˓ lttdgtlttrgt37 lttrgtlttdgtstatus lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt38 lttrgtlttdgtshell lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt39 lttrgtltth colspan=2gtRenault Twizyltthgtlttrgt40 lttrgtlttdgtxrtdrivemode lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt41 lttrgtlttdgtxrtscmon lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt42 lttablegt43

44 ltdivgt45 ltdivgt46

47 ltscriptgt48 (function()49 var pluginsrc = $(pluginsrc)html()50 $(plugindisplay)html(encode_html(pluginsrcsubstr(1)))51 )()52 ltscriptgt53

54 ltdiv id=pluginsrc style=displaynonegt55 lt--56 Hook plugin for homebodypre57 - custom coloring of menu titles58 - add custom menu Test Demo after Main59 --gt60

61 ltstylegt62 menu legend 63 color brown64 65 ltstylegt66

67 ltfieldset class=menu id=fieldset-menu-demo1 style=displaynonegt68 ltlegendgtTest Demoltlegendgt

(continues on next page)

331 TLDR Examples 277

Open Vehicles

(continued from previous page)

69 ltul class=list-inlinegt70 ltligtlta class=btn btn-default href=usrdemometrics target=maingtMetrics lt

rarr˓agtltligt71 ltligtlta class=btn btn-info href=logslog target=_blankgtOpen Log File ltagtlt

rarr˓ligt72 ltulgt73 ltfieldsetgt74

75 ltscriptgt76 $(main)one(load function(ev) 77 $(fieldset-menu-demo1)insertAfter(fieldset-menu-main)show()78 )79 ltscriptgt80 ltdivgt

3315 Solid Gauges

solidgaugehtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltstylegt6 solidgauge highcharts-yaxis-grid highcharts-grid-line7 solidgauge highcharts-yaxis-grid highcharts-minor-grid-line 8 display none9

10 solidgauge highcharts-pane 11 fill eee12 fill-opacity 113 stroke aaa14 stroke-width 2px15 16 night solidgauge highcharts-pane 17 fill b1b1b118 stroke b1b1b119 20 solidgauge highcharts-point 21 transition fill 500ms stroke 500ms see stops styles note 22 23 throttle-gauge highcharts-color-0 24 fill eee initial colors = pane for smooth fade in 25 stroke aaa26 fill-opacity 0827 stroke-width 3px28 stroke-opacity 0529 30 rpm-gauge highcharts-color-0 31 fill 55e32 stroke none33 34 ltstylegt35

36 ltdiv class=panel panel-primarygt

(continues on next page)

278 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

37 ltdiv class=panel-headinggtSolid Gaugeltdivgt38 ltdiv class=panel-bodygt39

40 ltdiv class=receivergt41

42 ltdiv class=rowgt43 ltdiv class=col-sm-6gt44 ltdiv class=metric chart data-metric=vethrottle style=height220pxgt45 ltdiv class=chart-box solidgauge id=throttle-gaugegt46 ltdivgt47 ltpgt48 Note stops dont work by default in styled mode This example includes a

rarr˓simple redraw49 event callback that applies styles from the stops To get a smooth color

rarr˓transition50 the CSS transition time needs to be equal to the chart animation time51 ltpgt52 ltdivgt53 ltdiv class=col-sm-6gt54 ltdiv class=metric chart data-metric=vmrpm style=height220pxgt55 ltdiv class=chart-box solidgauge gaugechart id=rpm-gaugegt56 ltdivgt57 ltpgt58 Note the ltcodegtgaugechartltcodegt CSS class pulls in the default styling

rarr˓for the bands59 labels and ticks here You can also copy those CSS rules from ltcodegtovms

rarr˓cssltcodegt60 and do your own styling61 ltpgt62 ltdivgt63 ltdivgt64

65 ltpgtltbutton type=button class=btn btn-default action-gendatagtGenerate randomrarr˓dataltbuttongtltpgt

66

67 ltdivgt68

69 ltdivgt70 ltdivgt71

72 ltscriptgt73 (function()74

75 Show page source 76 var pagesrc = $(main)html()77 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +78 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)79 $(action-showsrc)on(click function() 80 $(ltdivgt)dialog(81 title Source Code82 body ltpre style=font-size85 heightcalc(100vh - 230px)gt83 + encode_html(pagesrc) + ltpregt84 size lg85 )86 )87

(continues on next page)

331 TLDR Examples 279

Open Vehicles

(continued from previous page)

88 Init throttle gauge 89 $(throttle-gauge)chart(90 chart 91 type solidgauge92 spacing [0 0 0 0]93 margin [0 0 0 0]94 animation duration 500 easing easeOutExpo 95 events 96 Apply stops styles on redraw97 redraw function(ev) 98 var y = thisseries[0]yData[0] $pt = $(thisrenderTo)find(highcharts-

rarr˓point)99 $map(thisyAxis[0]stops function(stop) if (y gt= stop[0]) $pt

rarr˓css(stop[1]) )100 101 102 103 title text Throttle verticalAlign middle y 75 104 credits enabled false 105 tooltip enabled false 106 plotOptions 107 solidgauge dataLabels enabled false overshoot 1 108 109 pane [110 startAngle -90 endAngle 90 size 140 center [50 85]111 background innerRadius 60 outerRadius 100 shape arc 112 ]113 yAxis [114 title text 115 className throttle116 reversed false117 min 0 max 100118 stops [119 [0 fill afa stroke 4f4 ]120 [50 fill ffa stroke ff4 ]121 [80 fill faa stroke f44 ]122 ]123 tickPixelInterval 40 tickPosition inside tickLength 13124 labels step 2 distance 10 x 0 y 0 zIndex 2 125 ]126 series [127 name Throttle data [40]128 className throttle129 animation duration 0 130 ]131 Update method 132 onUpdate function(update) 133 Create gauge data set from metric134 var data = [ metrics[vethrottle] ]135 Update chart136 thisseries[0]setData(data)137 138 )139

140 Init rpm gauge 141 $(rpm-gauge)chart(142 chart

(continues on next page)

280 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

143 type solidgauge144 spacing [0 0 0 0]145 margin [0 0 0 0]146 animation duration 500 easing easeOutExpo 147 148 title text RPM verticalAlign middle y 75 149 credits enabled false 150 tooltip enabled false 151 plotOptions 152 solidgauge dataLabels enabled false overshoot 1 153 154 pane [155 startAngle -90 endAngle 90 size 140 center [50 85]156 background innerRadius 70 outerRadius 100 shape arc 157 ]158 yAxis [159 title text rpm 160 className rpm161 reversed false162 min 0 max 11000163 plotBands [164 from 0 to 7000 className green-band 165 from 7000 to 9000 className yellow-band 166 from 9000 to 11000 className red-band 167 ]168 minorTickInterval auto minorTickLength 5 minorTickPosition inside169 tickPixelInterval 40 tickPosition inside tickLength 10170 labels step 2 distance 10 x 0 y 0 zIndex 2 171 ]172 series [173 name RPM data [4500]174 className rpm175 animation duration 0 176 innerRadius 72177 radius 92178 ]179 Update method 180 onUpdate function(update) 181 Create gauge data set from metric182 var data = [ metrics[vmrpm] ]183 Update chart184 thisseries[0]setData(data)185 186 )187

188 Test metrics generator 189 $(action-gendata)on(click function() 190 var td = 191 td[vethrottle] = Mathrandom() 100192 td[vmrpm] = Mathrandom() 11000193 $(receiver)trigger(msgmetrics $extend(metrics td))194 )195

196 )()197 ltscriptgt

331 TLDR Examples 281

Open Vehicles

3316 Command Streaming

loadcmdhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltdiv class=panel panel-primarygt6 ltdiv class=panel-headinggtAsynchronous Command Streamingltdivgt7 ltdiv class=panel-bodygt8

9 lth3gtSynopsislth3gt10

11 ltp class=leadgtltcodegt[jqxhr=] loadcmd(command [target] [filter] [timeout])ltrarr˓codegtltpgt

12

13 ltpgtThe ltcodegtloadcmd()ltcodegt function executes a shell command or evaluatesrarr˓javascript

14 code with asynchronous streaming of the output into a target element or onto ararr˓functionltpgt

15

16

17 lth3gtBasic Usagelth3gt18

19 ltpgtAs this is the underlying function for command buttons basic usage20 is very similar but fully scriptableltpgt21

22 ltpgt23 ltbutton type=button class=btn btn-default onclick=loadcmd(boot status

rarr˓out1)gt24 Show boot status25 ltbuttongt26 ltpgt27 ltpre id=out1 gt28

29 ltpgtAs with command buttons you can append the output by prefixing the target30 selector with + You can omit the output by passing null as the target If

rarr˓target31 is a DOM element loadcmd automatically sets the ltcodegtloadingltcodegt class on

rarr˓the32 target while the command is processedltpgt33

34 ltpgtThe target elements min-height is automatically fixed to the current height35 of the target before the output is set This avoids page layout jumps when36 reusing a target for commandsltpgt37

38 ltpgtIf the target is scrollable and the content exceeds the visible area the39 element is automatically scrolled to show the new content unless the user has40 done a manual scrolling on the elementltpgt41

42 ltpgtIf the command output stops for ltcodegttimeoutltcodegt seconds the request is43 aborted and a timeout error is shown Default timeout is 20 seconds for standard44 commands 300 seconds for known long running commandsltpgt45

46

47 lth3gtEvaluate Javascript Codelth3gt48

(continues on next page)

282 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

49 ltpgtTo execute Javascript either pass an object instead of the ltcodegtcommandltrarr˓codegt string

50 containing the command as property command and a second property type with51 value js or simply use the wrapper call ltcodegtloadjs()ltcodegt Exampleltpgt52

53 ltpgt54 ltbutton type=button class=btn btn-default55 onclick=loadjs(print(OvmsVehicleType()) out1js)gt56 Show vehicle type57 ltbuttongt58 ltpgt59 ltpre id=out1js gt60

61 ltpgtJavascript evaluation is not limited to a single command or line Hint torarr˓avoid

62 encoding complex JS code in the onclick attribute store the code in some hidden63 DOM element and read it via ltcodegt$()text()ltcodegtltpgt64

65

66 lth3gtOutput Encoding ampamp Binary Streamslth3gt67

68 ltpgtTo allow binary data to be sent by a command and to enable processing of the69 result by Javascript on the browser without character encoding issues the

rarr˓command70 API supports output binary modeltpgt71

72 ltpgtPrimary application for this is exchanging CBOR encoded objects between the73 module and the web frontend To fully support this the OVMS web frontent

rarr˓includes74 the CBOR library by Patrick Gansterer Example useltpgt75

76 ltpregt77 loadjs( command auxbatmondump(CBOR) output binary )done((data) =gt 78 history = CBORdecode(data)79 )80 ltpregt81

82 ltpgtSee the AuxBatMon and PwrMon OVMS plugins for full examplesltpgt83

84 ltpgtltcodegtoutputltcodegt modes supported by the command API areltpgt85

86 ltulgt87 ltligtltcodegttextltcodegt rarr Content-Type textplain charset=utf-8ltligt88 ltligtltcodegtjsonltcodegt rarr Content-Type applicationjson charset=utf-8ltligt89 ltligtltcodegtbinaryltcodegt rarr Content-Type applicationoctet-stream charset=x-

rarr˓user-definedltligt90 ltligtdefaultother rarr Content-Type applicationoctet-stream charset=utf-8ltligt91 ltulgt92

93

94 lth3gtjqXHR Objectlth3gt95

96 ltpgtltcodegtloadcmd()ltcodegt returns the jqXHR (XMLHttpRequest) object in charge for97 the asynchronous execution of the request This can be used to track the results98 of the execution check for errors or to abort the commandltpgt99

100 ltpgt(continues on next page)

331 TLDR Examples 283

Open Vehicles

(continued from previous page)

101 ltbutton type=button class=btn btn-default id=startcggtStart chargenltrarr˓buttongt

102 ltbutton type=button class=btn btn-default id=abortcg disabledgtAbortrarr˓chargenltbuttongt

103 ltpgt104 ltpre id=out2 style=max-height200px overflowauto gt105

106 ltpgtThe jQuery XHR object is also a thenable so actions to be performed after107 the command execution can simply be chained to the object Exampleltpgt108

109 ltpgtltbutton type=button class=btn btn-default id=showstatgtShow statltbuttongtrarr˓ltpgt

110

111 ltpgtSee lta target=_blank href=httpapijquerycomjQueryajaxjqXHRgtjQuery112 documentationltagt for full details and optionsltpgt113

114

115 lth3gtFilter Process Outputlth3gt116

117 ltpgtSupply a filter function to hook into the asynchronous output stream Userarr˓filters

118 to filter (ahem) preprocess reformat the command output scan the streamrarr˓for some

119 info youd like to know as soon as possible or completely take over the output120 processingltpgt121

122 ltpgtThe filter function is called when a new chunk of output has arrived or when123 a stream error has occurred The function gets a message object containing124 the ltcodegtrequestltcodegt object and either a ltcodegttextltcodegt for normal

rarr˓outputs125 or an ltcodegterrorltcodegt which is a preformatted error output you can use or126 ignoreltpgt127

128 ltpgtIf the filter function returns a string that will be added to the outputrarr˓target

129 If it returns ltcodegtnullltcodegt the target will remain untouchedltpgt130

131 ltpgtHint if you just want to scan the text for some info you can pass on therarr˓message

132 after your scan to the default ltcodegtstandardTextFilter()ltcodegtltpgt133

134 ltpgtExample lets reformat a ltcodegtcan statusltcodegt dump into a nice Bootstraprarr˓tableltpgt

135

136 ltpgtltbutton type=button class=btn btn-default id=canstatusgtCAN1 statusltrarr˓buttongtltpgt

137

138 lttable class=table table-condensed table-border table-striped table-hover id=rarr˓canoutgt

139 lttheadgt140 lttrgtltth class=col-xs-6gtKeyltthgtltth class=col-xs-6gtValueltthgtlttrgt141 lttheadgt142 lttbodygt143 lttablegt144

145 ltdivgt146 ltdivgt

(continues on next page)

284 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

147

148 ltscriptgt149 (function()150

151 Show page source 152 var pagesrc = $(main)html()153 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +154 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)155 $(action-showsrc)on(click function() 156 $(ltdivgt)dialog(157 title Source Code158 body ltpre style=font-size85 heightcalc(100vh - 230px)gt159 + encode_html(pagesrc) + ltpregt160 size lg161 )162 )163

164 Example jqXHRabort() 165 var xhr166 $(startcg)on(click function() 167 xhr = loadcmd(test chargen 20 600 out2)168 $(abortcg)prop(disabled false)169 )170 $(abortcg)on(click function() 171 xhrabort()172 )173

174 Example jqXHRthen() 175 $(showstat)on(click function() 176 loadcmd(stat)then(function(output) 177 confirmdialog(STAT result ltsampgt + output + ltsampgt [Close])178 )179 )180

181 Example filter output processor 182 $(canstatus)on(click function() 183 var $table = $(canout gt tbody)184 var buf = 185 $tableempty()186 loadcmd(can can1 status function(msg) 187 if (msgerror) 188 Render error into table row189 $(lttr class=dangergtlttd colspan=2gt + msgerror + lttdgtlttrgt)appendTo(

rarr˓$table)190 191 else if (msgtext) 192 As this is a stream the text chunks received need not be single or

rarr˓complete lines193 Were interested in lines here so we buffer the chunks and split the

rarr˓buffer at n194 buf += msgtext195 var lines = bufsplit(n)196 if (lineslength gt 1) 197 buf = lines[lineslength-1]198 for (var i = 0 i lt lineslength-1 i++) 199 Skip empty lines

(continues on next page)

331 TLDR Examples 285

Open Vehicles

(continued from previous page)

200 if (lines[i] == ) continue201 Split line into columns202 var col = lines[i]split( +)203 Create table row amp append to table add some color on error counters204 if (col[0]match([Ee]rr))205 $(lttr class=warninggtltthgt + col[0] + ltthgtlttdgt + col[1] + lttdgtlt

rarr˓trgt)appendTo($table)206 else207 $(lttrgtltthgt + col[0] + ltthgtlttdgt + col[1] + lttdgtlttrgt)appendTo(

rarr˓$table)208 209 210 211 Filter has handled everything212 return null213 )214 )215

216 )()217 ltscriptgt

3317 File API

The file API enables web clients to read and write files at arbitrary VFS locations

bull API URL apifile

bull Methods

ndash GET ndash read file

ndash POST ndash write file

bull Parameters

ndash path ndash the full path to the file

ndash content ndash the new file content on POST

bull Output

ndash HTTP status 200 (OK) or 400 (Error)

ndash HTTP body file content on GET or error message

On writing missing directories along the path will be created automatically

Usage Example

The API can be accessed easily in the web frontend with the jQuery AJAX methods

Write object JSON encoded into filevar json = JSONstringify(object)$post(apifile path sdmystorefile1 content json )

done(function() confirmdialog(Saved ltpgtFile has been savedltpgt [OK] 2)

)fail(function(jqXHR)

(continues on next page)

286 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

confirmdialog(Save failed jqXHRresponseText [OK]))

Read JSON encoded object from file$get(apifile path sdmystorefile1 )

done(function(responseText) var object = JSONparse(responseText) process object

)fail(function(jqXHR) confirmdialog(Load failed jqXHRresponseText [OK])

)

External Access

From external clients the API can be used by either registering a session cookie or by supplying the apikey param-eter (as explained in the general authorization overview)

Read example

curl http19216841apifileapikey=passwordamppath=sdmystorefile1

Write example

curl http19216841apifile -d apikey=password -d path=sdmystorefile1 --data-urlencode contentlocalfile

3318 Longtouch Buttons

btn-longtouchhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web dir eg scp testpagehtm test1localsddev5 - open in framework by eg httptest1localdevtestpagehtm6 --gt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtLongtouch Buttonsltdivgt

10 ltdiv class=panel-bodygt11

12 ltpgtNote open this test page with a mobile touch screen device or simulate13 a mobile device using the web debugger of your browserltpgt14

15 ltpgtThe buttons below should work normally on a non-touch deviceltpgt16

17 ltpgtOn a touch screen device touching the buttons starts a countdown18 of 15 seconds showing an overlay with a progress bar and giving vibration19 signals (on devices supporting this) The button action is triggered only20 after the countdown has finished while holding the touchltpgt21

22 ltpgtThis feature is meant to a) secure certain buttons against unintentionalrarr˓activation

(continues on next page)

331 TLDR Examples 287

Open Vehicles

(continued from previous page)

23 and to b) allow secure usage of these buttons while driving ie when the mobilerarr˓phone

24 tablet is mounted to a car holderltpgt25

26 ltpgtStandard candidates for this are buttons triggering deep modifications ie27 changing the car tuning or drive modeltpgt28

29 ltpgtTo activate the feature on a button simply add the class ltcodegtbtn-longtouchltrarr˓codegt to the button

30 To activate it on a group of buttons add the class to the container of therarr˓buttonsltpgt

31

32 ltpgtThe progress overlay shows the button title if set (HTML supported) else therarr˓button textltpgt

33

34 ltform action=gt35 ltdiv class=btn-group btn-group-justified btn-longtouchgt36 ltdiv class=btn-group btn-group-lggt37 ltbutton type=submit name=load value=0 id=prof-0 class=btn btn-

rarr˓defaultgtltstronggtSTDltstronggtltbuttongt38 ltdivgt39 ltdiv class=btn-group btn-group-lggt40 ltbutton type=submit name=load value=1 id=prof-1 class=btn btn-

rarr˓default title=Power ModegtltstronggtPWRltstronggtltbuttongt41 ltdivgt42 ltdiv class=btn-group btn-group-lggt43 ltbutton type=submit name=load value=2 id=prof-2 class=btn btn-

rarr˓successgtltstronggtECOltstronggtltbuttongt44 ltdivgt45 ltdiv class=btn-group btn-group-lggt46 ltbutton type=submit name=load value=3 id=prof-3 class=btn btn-

rarr˓default title=Winter ModegtltstronggtICEltstronggtltbuttongt47 ltdivgt48 ltdivgt49 ltformgt50

51 ltdivgt52 ltdivgt

3319 Basic Dialogs

dialogtesthtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web dir eg scp testpagehtm test1localsddev5 - open in framework by eg httptest1localdevtestpagehtm6 --gt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtDialog TestDemoltdivgt

10 ltdiv class=panel-bodygt11 lth4gtCore Widgetlth4gt12 ltbutton class=btn btn-default id=action-loadgtDialog 1ltbuttongt

(continues on next page)

288 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

13 ltbutton class=btn btn-default id=action-savegtDialog 2ltbuttongt14 ltbutton class=btn btn-default id=action-bothgtBoth togetherltbuttongt15 ltbutton class=btn btn-default id=action-dyngtDynamic customltbuttongt16 lthr gt17 lth4gtUtility Wrapperslth4gt18 ltbutton class=btn btn-default id=action-infogtAlertltbuttongt19 ltbutton class=btn btn-default id=action-confirmgtConfirmltbuttongt20 ltbutton class=btn btn-default id=action-choicegtChoiceltbuttongt21 ltbutton class=btn btn-default id=action-promptgtPromptltbuttongt22 ltbutton class=btn btn-default id=action-passwordgtPasswordltbuttongt23 lthr gt24 lth4gtLoglth4gt25 ltpre id=log gt26 ltdivgt27 ltdivgt28

29 ltdiv id=dialog1 gt30 ltdiv id=dialog2 gt31 ltdiv id=dialog3 gt32

33 ltscriptgt34

35 rarr˓=======================================================================================

36 Dialog core widget37 options 38 title 39 body 40 show false true = open directly on init41 remote false42 backdrop true background overlay43 keyboard true ESC = close44 transition fade 45 size sm lg46 contentClass added to modal-content47 onShown null function(input)48 onHidden null function(input)49 onShow null function(input)50 onHide null function(input)51 onUpdate null function(input)52 buttons [] see example53 timeout 0 in seconds54 input null predefinedshared input object to use55 56

57 Note use static dialogs (attached to the document) for speed and to store reusable58 input eg for a promptdialog59

60 The default dialog will contain just a Close button61 $(dialog1)dialog(62 title Please note63 body ltpgtThis is just a testltpgt64 )65 $(dialog2)dialog(66 title Alert67 body ltpgtDanger Will Robinson dangerltpgt68 contentClass alert-danger note looks strange just an example -- dont use

(continues on next page)

331 TLDR Examples 289

Open Vehicles

(continued from previous page)

69 )70

71 You can simply open preconfigured dialogs like this72 $(action-load)on(click function()73 $(dialog1)dialog(show)74 )75 $(action-save)on(click function()76 $(dialog2)dialog(show)77 )78

79 or you can reconfigure dialogs on the fly like this80 Note the new configuration is stored in the dialog81 $(action-both)on(click function()82 $(dialog1)dialog(show body ltpgtThis is now another testltpgt )83 This example also opens a second dialog on top of the first84 $(dialog2)dialog(show body ltpgtThis is a second layer dialogltpgt )85 )86

87 Use dynamic dialogs for single shot purposes88 $(action-dyn)on(click function()89 $(log)text()90 $(ltdiv gt)dialog(91 title Dynamic92 body ltpgtdialog with custom buttonsltpgt93 buttons [94 Buttons default to auto hiding the dialog95 label Nope 96 You can get the button clicked in the onHidden callback or you can97 add specific action callbacks to each button98 label Maybe btnClass warning autoHide false action

rarr˓function(input) 99 input is the data container of the widget with only predefined

100 member being button = the button clicked (or null)101 You can use this container for custom extensions102 inputclicked_maybe = true103 $(this)find(modal-body)append(ltpgtYoure now a maybe personltpgt)104 105 autoHide callbacks are called on the hidden event so a fade out106 is guaranteed to be finished in the callback107 label Done btnClass primary action function(input) 108 $(log)text(JSONstringify(input null 2))109 110 ]111 )112 )113

114

115 rarr˓=======================================================================================

116 Dialog utility wrappers117 confirmdialog(title body buttons [callback] timeout)118 promptdialog(type title body buttons callback)119 Both can be used plugin style or standalone for dynamic dialogs120

121 Dynamic alert() style dialog with 5 seconds timeout122 $(action-info)on(click function()123 confirmdialog(Sorry Im afraid I cant do that Dave [OK] 5)

(continues on next page)

290 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

124 Note you can also add a callback here to know when the dialog is dismissed125 )126

127 Dynamic confirm() style dialog128 $(action-confirm)on(click function()129 $(log)text()130 confirmdialog(Load file Discard unsaved changes [No Yes]

rarr˓function(confirmed)131 if (confirmed)132 $(log)text(Loading now)133 else134 $(log)text(Load aborted)135 )136 )137

138 The callback argument is the index of the button clicked (or null) so139 simple choice dialogs can be done like this140 $(action-choice)on(click function()141 $(log)text()142 confirmdialog(Select Please select the slot to use [1 2 3 4]

rarr˓function(button)143 if (button = null)144 $(log)text(Using slot + (button+1))145 else146 $(log)text(Abort)147 )148 )149

150 Static prompt() style text input dialog (with dialog3 keeping the dialog)151 $(action-prompt)on(click function()152 $(log)text()153 $(dialog3)promptdialog(text Save data Please enter file name [Cancel

rarr˓ Save] function(button input)154 if (button ampamp input)155 $(log)text(Saving to file + input)156 else157 $(log)text(Save aborted)158 )159 )160

161 All single field HTML5 input types can be used162 $(action-password)on(click function()163 $(log)text()164 promptdialog(password Authentication Please enter PIN [Cancel Continue

rarr˓] function(button input)165 if (button ampamp input)166 $(log)text(PIN entered + input)167 else168 $(log)text(Auth aborted)169 )170 )171

172 ltscriptgt

331 TLDR Examples 291

Open Vehicles

33110 File Dialogs

filedialoghtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web file path eg sddevfiledialoghtm5 - open in framework by eg httptest1localdevfiledialoghtm6 --gt7

8 ltdiv class=filedialog id=fileselectgt9

10 ltdiv class=panel panel-primarygt11 ltdiv class=panel-headinggtFileDialog Testltdivgt12 ltdiv class=panel-bodygt13

14 lth2gtDynamic APIlth2gt15

16 ltpgt17 ltbutton class=btn btn-default id=action-loadgtLoadltbuttongt18 ltbutton class=btn btn-default id=action-savegtSaveltbuttongt19 ltpgt20 ltpre id=loggt21

22 lth2gtData APIlth2gt23

24 ltdiv class=input-groupgt25 ltinput type=text class=form-control font-monospace placeholder=Enter file

rarr˓name26 name=filename id=input-filename value= autocapitalize=none

rarr˓autocorrect=off27 autocomplete=section-demo spellcheck=falsegt28 ltdiv class=input-group-btngt29 lt-- use data-toggle=filedialog data-target amp data-input on the button --gt30 ltbutton type=button class=btn btn-default data-toggle=filedialog data-

rarr˓target=fd-api data-input=input-filenamegtSelectltbuttongt31 ltdivgt32 ltdivgt33

34 lt-- This is the file dialog triggered by the button --gt35 ltdiv class=filedialog id=fd-api data-options=36 title This is a data API dialog37 path sdfoo38 quicknav [sd sdfoo sdbar]39 gt40 lt-- thats it no JS code necessary41 Note JSON syntax needs to be strict here see JS console for errors42 --gt43

44 ltdivgt45 ltdivgt46

47 ltscriptgt48

49 rarr˓=======================================================================================

50 FileDialog is a Dialog with an embedded FileBrowser

(continues on next page)

292 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

51 52 The input object combines the dialog button and the file browser data53 54 Options55 title Select file -- dialog title56 submit Select -- label of submit button57 select f -- f = only files selectable (default) d

rarr˓ = only directories58 onSubmit null -- callback function(input)59 onCancel null -- callback function(input)60 61 inherited from FileBrowser62 path 63 quicknav [sd store]64 filter null65 sortBy null66 sortDir 167 68 inherited from Dialog69 backdrop true70 keyboard true71 transition fade72 size lg73 onUpdate null74 75

76 Init dialog77 $(fileselect)filedialog(78 path storescripts79 quicknav [storescripts storeevents storeobd2ecu]80 )81

82 $(action-load)on(click function()83 $(log)empty()84 $(fileselect)filedialog(show 85 title Load Script86 submit Load87 onSubmit function(input) 88 This is called when the user doubleclicks an entry or presses Enter in a

rarr˓directory89 Note you need to check if inputfile is valid (empty = directory selected)90 if (inputfile)91 $(log)text(Loading + inputpath + n)92 else93 $(log)text(Directory selection + inputpath + n)94 95 onCancel function(input) 96 This is called when the user cancels or closes the dialog97 $(log)text(Load cancelledn)98 99 )

100 )101

102 $(action-save)on(click function()103 $(log)empty()104 $(fileselect)filedialog(show 105 title Save Script

(continues on next page)

331 TLDR Examples 293

Open Vehicles

(continued from previous page)

106 submit Save107 onSubmit function(input) 108 if (inputfile)109 $(log)text(Saving + inputpath + n)110 else111 $(log)text(Directory selection + inputpath + n)112 113 onCancel function(input) 114 $(log)text(Save cancelledn)115 116 )117 )118

119 ltscriptgt

33111 File Browser Widget

filebrowserhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web file path eg sddevfilebrowserhtm5 - open in framework by eg httptest1localdevfilebrowserhtm6 --gt7

8 ltstylegt9 Note set height or min-height on the filebrowser tbody

10 Default height by class filebrowser is 310px (each file row has a height of 31pxrarr˓with the default font size)

11 myfilebrowser tbody 12 height 35vh13 14 ltstylegt15

16 ltdiv class=panel panel-primarygt17 ltdiv class=panel-headinggtFileBrowser TestDemoltdivgt18 ltdiv class=panel-bodygt19

20 ltdiv class=filebrowser id=myfilebrowser gt21

22 lthrgt23 ltpre id=loggt24 ltbutton type=button class=btn btn-default id=action-setpathgtSet path to sd

rarr˓logslogltbuttongt25 ltbutton type=button class=btn btn-default id=action-stoploadgtStop loading

rarr˓dirltbuttongt26 ltbutton type=button class=btn btn-default id=action-filterongtFilter ziplt

rarr˓buttongt27 ltbutton type=button class=btn btn-default id=action-filteroffgtFilter offlt

rarr˓buttongt28 ltbutton type=button class=btn btn-default id=action-sortoffgtSort offlt

rarr˓buttongt29 ltpgtNote the test widget is configured to stopinhibit loading on selection of a

rarr˓txt file or a directory matching DCIMltpgt(continues on next page)

294 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

30 ltdivgt31 ltdivgt32

33 ltscriptgt34

35 rarr˓=======================================================================================

36 FileBrowser Widget37 38 Testdemo of init with all options39 Note you can init a filebrowser without any options40 Defaults are path amp quicknav as shown below no sorting no callbacks41 42 The input object passed to all callbacks contains these fields43 - path -- the full path (dir + + file)44 - file -- the file part of the currently selected path45 - dir -- the directory part of the currently selected path46 - noload -- set to true to inhibit directory loading (see onPathChange)47 48 Note path file amp dir are unvalidated user input49 50 Note on sorting disabling initial sorting improves user interaction while loading

rarr˓the51 directory ie to select filesdirs while the loader is running This may52 be an option especially for large directories The user can still sort manually53 54 Methods55 - getInput() -- retrieve input object56 - setPath(newpath reload) -- add trailing slash to enter dir wo file

rarr˓selection57 - sortList(by dir) -- sort file list58 - loadDir() -- trigger directory reload59 - stopLoad() -- abort directory loading60 - newDir() -- open create directory sub dialog61 62

63 $(myfilebrowser)filebrowser(64 path sd65 quicknav [sd store]66 filter null see Filter examples below67 sortBy name or size or date or null (disable)68 sortDir 1 or -1 for reverse69 onUpdate function(input) 70 This is called after any widget configuration update use for custom

rarr˓extensions71 $(log)append(onUpdate + JSONstringify(input) + n)72 73 onPathChange function(input) 74 Called whenever the path changes75 $(log)append(onPathChange + JSONstringify(input) + n)76 To inhibit loading the directory for the new path set inputnoload to true77 if (inputdirindexOf(DCIM) gt= 0 || inputfileindexOf(txt) gt= 0) 78 $(log)append(inhibiting directory loadingn)79 inputnoload = true80 81 82 onAction function(input)

(continues on next page)

331 TLDR Examples 295

Open Vehicles

(continued from previous page)

83 This is called when the user doubleclicks an entry or presses Enter in ararr˓directory

84 $(log)append(onAction + JSONstringify(input) + n)85 86 )87

88 $(action-setpath)on(click function(ev) 89 $(myfilebrowser)filebrowser(setPath sdlogslog true)90 )91 $(action-stopload)on(click function(ev) 92 $(myfilebrowser)filebrowser(stopLoad)93 )94 $(action-sortoff)on(click function(ev) 95 $(myfilebrowser)filebrowser(sortList )96 )97

98 Filter example99 $(action-filteron)on(click function(ev)

100 $(myfilebrowser)filebrowser(101 The list filter may be given as a string (regular expression applied to file

rarr˓name)102 filter zip$103 A string filter always lists directories104

105 For advanced usage you may alternatively specify a filter callback like this106 filter function(f) return fisdir || fnamematch(zip$) 107 The function is called per list entry object with108 - isdir true = is sub directory109 - name the name part (file or directory dir with trailing )110 - path the full path of this entry111 - size formatted size (68k)112 - date formatted date (23-Nov-2018 1742)113 - bytes size in bytes -1 for directories114 - isodate ISO style date YYYY-mm-dd HHMM115 - class can be used to add a custom row class116 Return true to allow the entry to be added to the list117

118 Note list filters do not restrict the allowed path input To do so119 register onPathChange or onAction and check the input in your callback120 See FileDialog widget select option handling for an example121 )122 )123 $(action-filteroff)on(click function(ev) 124 $(myfilebrowser)filebrowser(125 filter null126 )127 )128

129 ltscriptgt

33112 Slider Widget

input-sliderhtm (hint right click save as)

296 Chapter 33 Web Framework amp Plugins

Open Vehicles

1 ltstylegt2 Align multiple slider inputs by suitably fixing their value width 3 form-inline form-controlslider-value 4 width 80px5 6 ltstylegt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtSlider Widgetltdivgt

10 ltdiv class=panel-bodygt11

12 lth3gtStandard Numerical Inputslth3gt13

14 ltpgtThe number input is just the bootstrap defaultltpgt15

16 ltinput class=form-control type=number id=input-num1 name=num1 value=80rarr˓min=0 max=100 step=1gt

17 ltbrgt18

19 ltpgtThe range input has some styling optimization for touch devicesltpgt20

21 ltinput class=form-control type=range id=input-rng1 name=rng1 value=80rarr˓min=0 max=100 step=1gt

22 ltbrgt23

24 lth3gtSlider Widgetlth3gt25

26 ltpgt27 In many cases youd like to give especially the touchscreen user a combination

rarr˓of these input28 elements and as sliding may be too imprecise you also need large buttons for

rarr˓single step changes29 Thats what the slider widget does It also adds the option of a checkbox and a

rarr˓default value to30 reflect if the user control shall be applied31 ltpgt32

33 ltdiv class=rowgt34 ltdiv class=col-md-9gt35

36 ltpgtSliders can easily be created from minimal markup using the ltcodegtslider()rarr˓ltcodegt plugin

37 with configuration given by data attributes andor dynamic optionsltpgt38

39 ltdiv class=form-control slider id=sld1 data-min=-5 data-max=50 data-rarr˓step=05

40 data-default=40 data-unit= data-disabled=false data-checked=truerarr˓data-value=10 gt

41 ltbrgt42

43 ltdiv class=form-control slider id=sld2 gt44 ltbrgt45

46 ltpgtand slider state limits and value can be controlled using the samerarr˓methodltbrgt

47 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(rarr˓value42 )gt

(continues on next page)

331 TLDR Examples 297

Open Vehicles

(continued from previous page)

48 Set sld1 value to 4249 ltbuttongt50 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(

rarr˓checkedtrue )gt51 Check sld152 ltbuttongt53 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(

rarr˓disabledtrue )gt54 Disable sld155 ltbuttongt56 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(

rarr˓disabledfalse )gt57 Enable sld158 ltbuttongt59 ltpgt60 ltbrgt61

62 ltpgtIf you need even more control you can create the slider markup yourselfrarr˓as wellltpgt

63

64 ltdiv class=form-control slider id=sld3 data-default=50 data-reset=falserarr˓

65 data-value=80 data-min=-10 data-max=100 data-step=1gt66 ltdiv class=slider-control form-inlinegt67 ltinput class=slider-enable type=checkbox checkedgt68 ltinput class=form-control slider-value type=number id=input-sld3

rarr˓name=sld3gt69 ltspan class=slider-unitgtltspangt70 ltinput class=btn btn-default slider-down type=button value=gt71 ltinput class=btn btn-default slider-set type=button value=Lo data-

rarr˓set=25gt72 ltinput class=btn btn-default slider-set type=button value=Hi data-

rarr˓set=75gt73 ltinput class=btn btn-default slider-up type=button value=gt74 ltdivgt75 ltinput class=slider-input type=rangegt76 ltdivgt77 ltbrgt78

79 ltdivgt80 ltdiv class=col-md-3gt81

82 ltpgtltugtEvents ampamp valuesltugtltpgt83 ltpre id=show-sldevgtltpregt84

85 ltdivgt86 ltdivgt87

88 ltbrgt89

90 ltpgt91 Checkbox buttons and unit are optional You can reduce the widget to just a

rarr˓number or92 just a range input the input then needs to have the ltcodegtslider-inputltcodegt

rarr˓class93 ltpgt94

(continues on next page)

298 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

95 ltpgt96 The checkbox element defines the default value to be set on unchecking in97 ltcodegtdata-defaultltcodegt By default the checkbox will restore the previous

rarr˓user98 value when re-checked to disable this set ltcodegtdata-resetltcodegt to true99 To reset the value to the default from a script call the ltcodegtslider()ltcodegt

100 method with ltcodegtvalue nullltcodegt (this resets both the actual and the stored101 user value)102 ltpgt103

104 ltpgt105 Values and checkbox status need to be consistent on init or be set by your

rarr˓script106 To hook into value changes attach event handlers to events ltcodegtinputltcodegt107 andor ltcodegtchangeltcodegt as usual Read the ltcodegtcheckedltcodegt property to

rarr˓get the108 checkbox state109 ltpgt110

111 ltdivgt112 ltdivgt113

114 ltscriptgt115 (function()116

117 Show page source 118 var pagesrc = $(main)html()119 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +120 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)121 $(action-showsrc)on(click function() 122 $(ltdivgt)dialog(123 title Source Code124 body ltpre style=font-size85 heightcalc(100vh - 230px)gt125 + encode_html(pagesrc) + ltpregt126 size lg127 )128 )129

130 Init sliders 131 $(slider)slider()132 $(sld2)slider( min-10 max10 step01 default25 unitkW

rarr˓checkedfalse value-38 )133

134 Show slider events amp values 135 var sldev = 136 $(input-sld1 input-sld2 input-sld3)on(input change function(ev) 137 sldev[thisname] = $extend(sldev[thisname] checked thischecked )138 Note thisvalue is unvalidated here for a direct entry but the validation is

rarr˓simple139 sldev[thisname][evtype] = Mathmax(thismin Mathmin(thismax 1thisvalue))140 $(show-sldev)text(JSONstringify(sldev null 2))141 )142

143 )()144 ltscriptgt

331 TLDR Examples 299

Open Vehicles

33113 Regen Brake Monitor

This plugin defines a page including an acceleration level gauge chart number metrics for the acceleration speed andbattery power and two large indicators for the regen brake light and the brake pedal state

Itrsquos useful to fine tune the regen brake settings as you can monitor the actual deceleration levels while driving andcheck the smoothing level

Install add the source as a page plugin eg devregenmon

regenmonhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltstylegt6 indicator gt label 7 font-size 1508 line-height 2009 margin 10px

10 padding 10px11 display block12 border-radius 50px13 14 metricnumber label 15 min-width 8em16

(continues on next page)

300 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

17 metricnumber 18 display block19 float none20 text-align center21 22 ltstylegt23

24 ltdiv class=panel panel-primarygt25 ltdiv class=panel-headinggtRegen Brake Monitorltdivgt26 ltdiv class=panel-bodygt27

28 ltdiv class=receiver id=regenmon-receivergt29

30 ltdiv class=rowgt31 ltdiv class=col-sm-6gt32 ltdiv class=metric chart data-metric=vpacceleration style=height300px

rarr˓gt33 ltdiv class=chart-box gaugechart id=accel-gaugegt34 ltdivgt35 ltdiv class=metric number data-metric=vpacceleration data-prec=2gt36 ltspan class=labelgtAccelerationltspangt37 ltspan class=valuegtltspangt38 ltspan class=unitgtms2ltspangt39 ltdivgt40 ltdiv class=metric number data-metric=vpspeed data-prec=1gt41 ltspan class=labelgtSpeedltspangt42 ltspan class=valuegtltspangt43 ltspan class=unitgtkphltspangt44 ltdivgt45 ltdiv class=metric number data-metric=vbpower data-prec=1gt46 ltspan class=labelgtBattery powerltspangt47 ltspan class=valuegtltspangt48 ltspan class=unitgtkWltspangt49 ltdivgt50 ltbr class=clearfixgt51 ltdivgt52 ltdiv class=col-sm-6gt53 ltdiv class=indicator data-metric=veregenbrakegt54 ltspan class=label label-defaultgtREGENltspangt55 ltdivgt56 ltdiv class=indicator data-metric=vefootbrakegt57 ltspan class=label label-defaultgtFOOTltspangt58 ltdivgt59 ltdivgt60 ltdivgt61

62 ltdivgt63

64 ltdivgt65 ltdivgt66

67 ltscriptgt68 (function()69

70 Init acceleration gauge 71 $(accel-gauge)chart(72 chart

(continues on next page)

331 TLDR Examples 301

Open Vehicles

(continued from previous page)

73 type gauge74 spacing [0 0 0 0]75 margin [0 0 0 0]76 animation duration 250 easing easeOutExpo 77 78 title text Acceleration verticalAlign middle y 75 79 credits enabled false 80 tooltip enabled false 81 plotOptions 82 gauge dataLabels enabled false overshoot 5 83 84 pane [85 startAngle -120 endAngle 120 size 100 center [50 60]86 ]87 yAxis [88 title text ms2 89 className accel90 reversed false91 min -2 max 292 minorTickInterval 01 minorTickLength 5 minorTickPosition inside93 tickInterval 05 tickPosition inside tickLength 1394 labels step 1 distance -28 x 0 y 5 zIndex 2 95 ]96 series [97 name Acceleration data [0]98 className accel99 animation duration 0

100 pivot radius 10 101 dial radius 88 topWidth 1 baseLength 20 baseWidth 10

rarr˓rearLength 20 102 ]103 Update method 104 onUpdate function(update) 105 Create gauge data set from metric106 var data = [ metrics[vpacceleration] ]107 Update chart108 thisseries[0]setData(data)109 110 )111

112 Init indicators 113 $(regenmon-receiver)on(msgmetrics function(e update) 114 $(this)find(indicator)each(function() 115 var $el = $(this) metric = $eldata(metric) val = update[metric]116 if (val == null)117 return118 else if (val = 0)119 $elchildren()removeClass(label-default)addClass(label-danger)120 else if (val == 0)121 $elchildren()removeClass(label-danger)addClass(label-default)122 )123 )124

125 )()126 ltscriptgt

302 Chapter 33 Web Framework amp Plugins

Open Vehicles

33114 Dashboard

A refined and configurable version of this plugin has been added to the standard OVMS web UI and gets automaticallyconfigured by the vehicle modules with their respective vehicle parameters

Itrsquos a good example of the Highcharts gauge chart options and shows how to combine multiple gauge charts into asingle container (div gaugeset1) and how to style the charts using CSS

It also includes a simple test data generator so can be tested without actual vehicle data

To add a new vehicle parameter set for the standard dashboard simply override the GetDashboardConfig()method in your vehicle class Have a look at the existing overrides (for example Twizy Kia Soul Smart ED )

Install not necessary for the standard dashboard If yoursquore going to build your own dashboard from this install it asa page type plugin

dashboardhtm (hint right click save as)

1 lt-- Main --gt2

3 ltstylegt4 media (max-width 767px) 5 panel-single panel-body 6 padding 2px7 8 9 dashboard highcharts-data-label text

10 font-size 2em11 12 dashboard overlay 13 position absolute14 z-index 1015 top 6216 text-align center17 left 018 right 019 20 dashboard overlay value 21 color 04282b22 background 97b59723 padding 2px 5px

(continues on next page)

331 TLDR Examples 303

Open Vehicles

(continued from previous page)

24 margin-right 02em25 text-align center26 border 1px inset c3c3c38027 font-family Monaco Menlo Consolas QuickType Mono Lucida Console

rarr˓Roboto Mono Ubuntu Mono DejaVu Sans Mono Droid Sans Mono monospace28 display inline-block29 30 night dashboard overlay value 31 color fff32 background 25252533 34 dashboard overlay unit 35 color 66636 font-size 12px37 38 dashboard overlay range-value value 39 margin-left 10px40 width 100px41 42 dashboard overlay energy-value 43 margin-top 4px44 45 dashboard overlay energy-value value 46 margin-left 18px47 width 100px48 font-size 12px49 50 ltstylegt51

52 ltdiv class=panel panel-primary id=panel-dashboardgt53 ltdiv class=panel-headinggtDashboardltdivgt54 ltdiv class=panel-bodygt55

56 ltdiv class=receiver get-window-resize id=livestatusgt57 ltdiv class=dashboard style=position relative width 100 height 300px

rarr˓margin 0 autogt58 ltdiv class=overlaygt59 ltdiv class=range-valuegtltspan class=valuegt0 0ltspangtltspan class=unitgtkm

rarr˓ltspangtltdivgt60 ltdiv class=energy-valuegtltspan class=valuegt00 00ltspangtltspan class=

rarr˓unitgtkWhltspangtltdivgt61 ltdivgt62 ltdiv id=gaugeset1 style=width 100 height 100gtltdivgt63 ltdivgt64 ltdivgt65

66 ltdivgt67 ltdivgt68

69

70 lt-- Chart --gt71

72 ltstylegt73 highcharts-plot-band highcharts-pane 74 fill-opacity 075 76 highcharts-plot-bandborder

(continues on next page)

304 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

77 stroke 66666678 stroke-width 1px79 80

81 green-band 82 fill 55BF3B83 fill-opacity 0484 85 yellow-band 86 fill DDDF0D87 fill-opacity 0588 89 red-band 90 fill DF535391 fill-opacity 0692 93 violet-band 94 fill 9622ff95 fill-opacity 0696 97 night violet-band 98 fill 9622ff99 fill-opacity 08

100 101

102 highcharts-gauge-series highcharts-pivot 103 stroke-width 1px104 stroke 757575105 fill-opacity 1106 fill black107 108 highcharts-gauge-seriesauxgauge highcharts-pivot 109 fill-opacity 1110 fill fff111 stroke-width 0112 113 night highcharts-gauge-seriesauxgauge highcharts-pivot 114 fill 000115 116 highcharts-gauge-series highcharts-dial 117 fill d80000118 stroke 000119 stroke-width 05px120 121 highcharts-yaxis-grid highcharts-grid-line122 highcharts-yaxis-grid highcharts-minor-grid-line 123 display none124 125 highcharts-yaxis highcharts-tick 126 stroke-width 2px127 stroke 666666128 129 night highcharts-yaxis highcharts-tick 130 stroke e0e0e0131 132 highcharts-yaxis highcharts-minor-tick 133 stroke-width 18px

(continues on next page)

331 TLDR Examples 305

Open Vehicles

(continued from previous page)

134 stroke 00000085135 stroke-dasharray 6136 stroke-dashoffset -48137 stroke-linecap round138 139 night highcharts-yaxis highcharts-minor-tick 140 stroke ffffff85141 142 highcharts-axis-labels 143 fill 000144 font-weight bold145 font-size 09em146 147 night highcharts-axis-labels 148 fill ddd149 150 highcharts-data-label text 151 fill 333333152 153 night highcharts-data-label text 154 fill fff155 156

157 highcharts-axis-labelsspeed 158 font-size 12em159 160 ltstylegt161

162 ltscript type=textjavascriptgt163

164 Vehicle specific configuration165

166 var vehicle_config_twizy = 167 yAxis [168 Speed169 min 0 max 120170 plotBands [171 from 0 to 70 className green-band 172 from 70 to 100 className yellow-band 173 from 100 to 120 className red-band ]174 175 Voltage176 min 45 max 60177 plotBands [178 from 45 to 475 className red-band 179 from 475 to 50 className yellow-band 180 from 50 to 60 className green-band ]181 182 SOC183 min 0 max 100184 plotBands [185 from 0 to 125 className red-band 186 from 125 to 25 className yellow-band 187 from 25 to 100 className green-band ]188 189 Efficiency190 min 0 max 300

(continues on next page)

306 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

191 plotBands [192 from 0 to 150 className green-band 193 from 150 to 250 className yellow-band 194 from 250 to 300 className red-band ]195 196 Power197 min -10 max 30198 plotBands [199 from -10 to 0 className violet-band 200 from 0 to 15 className green-band 201 from 15 to 25 className yellow-band 202 from 25 to 30 className red-band ]203 204 Charger temperature205 min 20 max 80 tickInterval 20206 plotBands [207 from 20 to 65 className normal-band border 208 from 65 to 80 className red-band border ]209 210 Battery temperature211 min -15 max 65 tickInterval 25212 plotBands [213 from -15 to 0 className red-band border 214 from 0 to 50 className normal-band border 215 from 50 to 65 className red-band border ]216 217 Inverter temperature218 min 20 max 80 tickInterval 20219 plotBands [220 from 20 to 70 className normal-band border 221 from 70 to 80 className red-band border ]222 223 Motor temperature224 min 50 max 125 tickInterval 25225 plotBands [226 from 50 to 110 className normal-band border 227 from 110 to 125 className red-band border ]228 ]229 230

231 var vehicle_config_default = 232 yAxis [233 Speed234 min 0 max 120235 plotBands [236 from 0 to 70 className green-band 237 from 70 to 100 className yellow-band 238 from 100 to 120 className red-band ]239 240 Voltage241 min 310 max 410242 plotBands [243 from 310 to 325 className red-band 244 from 325 to 340 className yellow-band 245 from 340 to 410 className green-band ]246 247 SOC

(continues on next page)

331 TLDR Examples 307

Open Vehicles

(continued from previous page)

248 min 0 max 100249 plotBands [250 from 0 to 125 className red-band 251 from 125 to 25 className yellow-band 252 from 25 to 100 className green-band ]253 254 Efficiency255 min 0 max 400256 plotBands [257 from 0 to 200 className green-band 258 from 200 to 300 className yellow-band 259 from 300 to 400 className red-band ]260 261 Power262 min -50 max 200263 plotBands [264 from -50 to 0 className violet-band 265 from 0 to 100 className green-band 266 from 100 to 150 className yellow-band 267 from 150 to 200 className red-band ]268 269 Charger temperature270 min 20 max 80 tickInterval 20271 plotBands [272 from 20 to 65 className normal-band border 273 from 65 to 80 className red-band border ]274 275 Battery temperature276 min -15 max 65 tickInterval 25277 plotBands [278 from -15 to 0 className red-band border 279 from 0 to 50 className normal-band border 280 from 50 to 65 className red-band border ]281 282 Inverter temperature283 min 20 max 80 tickInterval 20284 plotBands [285 from 20 to 70 className normal-band border 286 from 70 to 80 className red-band border ]287 288 Motor temperature289 min 50 max 125 tickInterval 25290 plotBands [291 from 50 to 110 className normal-band border 292 from 110 to 125 className red-band border ]293 ]294 295

296 var vehicle_config = vehicle_config_twizy297

298 var gaugeset1299

300 function get_dashboard_data() 301 var rmin = metrics[vbrangeest]||0 rmax = metrics[vbrangeideal]||0302 var euse = metrics[vbenergyused]||0 erec = metrics[vbenergyrecd]||0303 if (rmin gt rmax) var x = rmin rmin = rmax rmax = x 304 var md =

(continues on next page)

308 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

305 range value + rmaxtoFixed(0) + + rmintoFixed(0) 306 energy value + eusetoFixed(1) + + erectoFixed(1) 307 series [308 data [metrics[vpspeed]] 309 data [metrics[vbvoltage]] 310 data [metrics[vbsoc]] 311 data [metrics[vbconsumption]] 312 data [metrics[vbpower]] 313 data [metrics[vctemp]] 314 data [metrics[vbtemp]] 315 data [metrics[vitemp]] 316 data [metrics[vmtemp]] ]317 318 return md319 320

321 function update_dashboard() 322 var md = get_dashboard_data()323 $(range-value value)text(mdrangevalue)324 $(energy-value value)text(mdenergyvalue)325 gaugeset1update( series mdseries )326 327

328 function init_gaugeset1() 329 var chart_config = 330 chart 331 type gauge332 spacing [0 0 0 0]333 margin [0 0 0 0]334 animation duration 0 easing swing 335 336 title text null 337 credits enabled false 338 tooltip enabled false 339

340 pane [341 startAngle -125 endAngle 125 center [50 45] size 80

rarr˓Speed342 startAngle 70 endAngle 110 center [-20 20] size 100

rarr˓Voltage343 startAngle 70 endAngle 110 center [-20 60] size 100 SOC344 startAngle -110 endAngle -70 center [120 20] size 100

rarr˓Efficiency345 startAngle -110 endAngle -70 center [120 60] size 100

rarr˓Power346 startAngle -45 endAngle 45 center [20 100] size 30

rarr˓Charger temperature347 startAngle -45 endAngle 45 center [40 100] size 30

rarr˓Battery temperature348 startAngle -45 endAngle 45 center [60 100] size 30

rarr˓Inverter temperature349 startAngle -45 endAngle 45 center [80 100] size 30 ]

rarr˓Motor temperature350

351 responsive 352 rules [353 condition minWidth 0 maxWidth 400

(continues on next page)

331 TLDR Examples 309

Open Vehicles

(continued from previous page)

354 chartOptions 355 pane [356 size 60 Speed357 center [-20 20] Voltage358 center [-20 60] SOC359 center [120 20] Efficiency360 center [120 60] Power361 center [15 100] size 25 Charger temperature362 center [3833 100] size 25 Battery temperature363 center [6166 100] size 25 Inverter temperature364 center [85 100] size 25 ] Motor temperature365 yAxis [ labels step 1 ] Speed366 367 368 condition minWidth 401 maxWidth 450 369 chartOptions 370 pane [371 size 70 Speed372 center [-15 20] Voltage373 center [-15 60] SOC374 center [115 20] Efficiency375 center [115 60] Power376 center [15 100] size 275 Charger temperature377 center [3833 100] size 275 Battery temperature378 center [6166 100] size 275 Inverter temperature379 center [85 100] size 275 ] Motor temperature380 381 382 condition minWidth 451 maxWidth 600 383 chartOptions 384 pane [385 size 80 Speed386 center [-10 20] Voltage387 center [-10 60] SOC388 center [110 20] Efficiency389 center [110 60] ] Power390 391 392 condition minWidth 601 393 chartOptions 394 pane [395 size 85 Speed396 center [0 20] Voltage397 center [0 60] SOC398 center [100 20] Efficiency399 center [100 60] ] Power400 401 ]402 403

404 yAxis [405 Speed axis406 pane 0 className speed title text kmh 407 reversed false408 minorTickInterval auto minorTickLength 5 minorTickPosition inside409 tickPixelInterval 30 tickPosition inside tickLength 13410 labels step 2 distance -28 x 0 y 5 zIndex 2

(continues on next page)

310 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

411 412 Voltage axis413 pane 1 className voltage title text Volt align low x 90 y

rarr˓35 414 reversed true415 minorTickInterval auto minorTickLength 5 minorTickPosition inside416 tickPixelInterval 30 tickPosition inside tickLength 13417 labels step 1 distance -25 x 0 y 5 zIndex 2 418 419 SOC axis420 pane 2 className soc title text SOC align low x 85 y 35 421 reversed true422 minorTickInterval auto minorTickLength 5 minorTickPosition inside423 tickPixelInterval 30 tickPosition inside tickLength 13424 labels step 1 distance -25 x 0 y 5 zIndex 2 425 426 Efficiency axis427 pane 3 className efficiency title text Whkm align low x -125

rarr˓ y 35 428 reversed false429 minorTickInterval auto minorTickLength 5 minorTickPosition inside430 tickPixelInterval 30 tickPosition inside tickLength 13431 labels step 1 distance -25 x 0 y 5 zIndex 2 432 433 Power axis434 pane 4 className power title text kW align low x -115 y 35

rarr˓435 reversed false436 minorTickInterval auto minorTickLength 5 minorTickPosition inside437 tickPixelInterval 30 tickPosition inside tickLength 13438 labels step 1 distance -25 x 0 y 5 zIndex 2 439 440 Charger temperature axis441 pane 5 className temp-charger title text CHG degC y 10 442 tickPosition inside tickLength 10 minorTickInterval null443 labels step 1 distance 3 x 0 y 0 zIndex 2 444 445 Battery temperature axis446 pane 6 className temp-battery title text BAT degC y 10 447 tickPosition inside tickLength 10 minorTickInterval null448 labels step 1 distance 3 x 0 y 0 zIndex 2 449 450 Inverter temperature axis451 pane 7 className temp-inverter title text PEM degC y 10 452 tickPosition inside tickLength 10 minorTickInterval null453 labels step 1 distance 3 x 0 y 0 zIndex 2 454 455 Motor temperature axis456 pane 8 className temp-motor title text MOT degC y 10 457 tickPosition inside tickLength 10 minorTickInterval null458 labels step 1 distance 3 x 0 y 0 zIndex 2 459 ]460

461 plotOptions 462 gauge 463 dataLabels enabled false 464 overshoot 1

(continues on next page)

331 TLDR Examples 311

Open Vehicles

(continued from previous page)

465 466 467 series [468 Speed value469 yAxis 0 name Speed className speed fullgauge data [0]470 pivot radius 10 471 dial radius 88 topWidth 1 baseLength 20 baseWidth 10

rarr˓rearLength 20 472 473 Voltage value474 yAxis 1 name Voltage className voltage auxgauge data [0]475 pivot radius 85 476 dial radius 95 baseWidth 5 baseLength 90 477 478 SOC value479 yAxis 2 name SOC className soc auxgauge data [0]480 pivot radius 85 481 dial radius 95 baseWidth 5 baseLength 90 482 483 Efficiency value484 yAxis 3 name Efficiency className efficiency auxgauge data [0]485 pivot radius 85 486 dial radius 95 baseWidth 5 baseLength 90 487 488 Power value489 yAxis 4 name Power className power auxgauge data [0]490 pivot radius 85 491 dial radius 95 baseWidth 5 baseLength 90 492 493 Charger temperature value494 yAxis 5 name Charger temperature className temp-charger tempgauge

rarr˓data [0]495 dial radius 90 baseWidth 3 baseLength 90 496 497 Battery temperature value498 yAxis 6 name Battery temperature className temp-battery tempgauge

rarr˓data [0]499 dial radius 90 baseWidth 3 baseLength 90 500 501 Inverter temperature value502 yAxis 7 name Inverter temperature className temp-inverter tempgauge

rarr˓data [0]503 dial radius 90 baseWidth 3 baseLength 90 504 505 Motor temperature value506 yAxis 8 name Motor temperature className temp-motor tempgauge data

rarr˓[0]507 dial radius 90 baseWidth 3 baseLength 90 508 ]509 510

511 Inject vehicle config512 for (var i = 0 i lt chart_configyAxislength i++) 513 $extend(chart_configyAxis[i] vehicle_configyAxis[i])514 515

516 gaugeset1 = Highchartschart(gaugeset1 chart_config(continues on next page)

312 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

517 function (chart) 518 chartupdate( chart animation duration 1000 easing swing )519 $(livestatus)on(msgmetrics function(e update)520 update_dashboard()521 )on(window-resize function(e)522 chartreflow()523 )524 525 )526 527

528 function init_charts() 529 init_gaugeset1()530 531

532 if (windowHighcharts) 533 init_charts()534 else 535 $ajax(536 url windowassetscharts_js537 dataType script538 cache true539 success function() init_charts() 540 )541 542

543 ltscriptgt544

545

546

547 lt-- TESTDATENGENERATOR --gt548 ltbr class=clearfixgt549 ltdiv id=viewportinfogtWxHltdivgt550 ltdiv id=debugfsgtltdivgt551 ltbutton class=btn btn-info id=mkmetricsgtMake test metricsltbuttongt552 ltbr class=clearfixgt553 ltscript type=textjavascriptgt554 $(mkmetrics)on(click function()555 var msg = 556 metrics 557 vbrangeest Mathrandom()80558 vbrangeideal Mathrandom()80559 vbenergyused Mathrandom()20560 vbenergyrecd Mathrandom()20561 vpspeed Mathrandom()120562 vbvoltage 45 + Mathrandom()15563 vbsoc Mathrandom()100564 vbconsumption Mathrandom()300565 vbpower Mathrandom()40 - 10566 vctemp Mathrandom()80567 vbtemp Mathrandom()80568 vitemp Mathrandom()80569 vmtemp Mathrandom()80570 571 572 $extend(metrics msgmetrics)573 $(receiver)trigger(msgmetrics msgmetrics)

(continues on next page)

331 TLDR Examples 313

Open Vehicles

(continued from previous page)

574 )575 $(window)on(resize function()576 $(viewportinfo)text($(window)width() + x + $(window)height())577 )trigger(resize)578 ltscriptgt

33115 Twizy Dashboard Tuning Plugin

This plugin adds two sliders to adjust neutral and braking recuperation levels to the dashboard

The sliders listen to driving profile changes and update accordingly

If not yet logged in the sliders are disabled

Install add the plugin as a hook type to page dashboard hook bodypre

dashboard-tunesliderhtm (hint right click save as)

1 lt--2 Hook plugin for dashboardbodypre or bodypost3 - add sliders to adjust recuperation power levels

(continues on next page)

314 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

4 --gt5

6 ltstylegt7 tuneslider 8 margin 10px 8px 09

10 form-inline form-controlslider-value 11 width 80px12 13 ltstylegt14

15 ltdiv class=receiver id=tuneslider style=displaynonegt16 ltdiv class=form-groupgt17 ltlabel class=control-label for=input-neutralgtNeutral recuperationltlabelgt18 ltdiv class=form-control slider id=neutral gt19 ltdivgt20 ltdiv class=form-groupgt21 ltlabel class=control-label for=input-brakegtBrake recuperationltlabelgt22 ltdiv class=form-control slider id=brake gt23 ltdivgt24 ltdivgt25

26 ltscriptgt27 (function()28

29 Init sliders30 $(neutral)slider( min0 max100 step1 unit default18 value18

rarr˓checkedfalse )31 $(brake)slider( min0 max100 step1 unit default18 value18

rarr˓checkedfalse )32

33 Update sliders on profile changes34 var profile35 $(tuneslider)on(msgmetrics function(ev update) 36 if (update[xrtcfgprofile] = null) 37 profile = update[xrtcfgprofile]38 var neutral = profile[7] brake = profile[8] see cfgconvc tagnames for

rarr˓profile structure39 $(neutral)slider( checked (neutral=-1) value (neutral=-1) neutral

rarr˓null )40 $(brake)slider( checked (brake=-1) value (brake=-1) brake null )41 42 )43

44 Update profile on slider changes45 $(tuneslider slider-value)on(change function(ev) 46 var neutral = $(input-neutral)prop(checked) $(input-neutral)val() -

rarr˓147 brake = $(input-brake)prop(checked) $(input-brake)val() -148 autorecup_minprc = profile[43] autorecup_ref = profile[44]49 var cmd = xrt cfg recup + neutral + + brake + + autorecup_ref + +

rarr˓autorecup_minprc50 loadcmd(cmd loadres)51 )52

53 Install into panel54 $(main)one(load function(ev)

(continues on next page)

331 TLDR Examples 315

Open Vehicles

(continued from previous page)

55 if (loggedin) 56 $(tuneslider slider)slider( disabled true )57 58 $(tuneslider)appendTo(panel-dashboard panel-body)show()59 )60

61 )()62 ltscriptgt

33116 Twizy Tuning Profile Editor

This plugin has been added to the Twizy code Itrsquos used here as a more complex example of what can be done byplugins

Itrsquos a full featured SEVCON tuning profile editor including dialogs to load amp save profiles from the OVMS configura-tion and to create amp read base64 profile codes

See Twizy documentation for details on tuning profiles and capabilities

Install not necessary if vehicle Twizy is configured (see ldquoTwizyrdquo menu) If yoursquod like to test this for another vehicleadd as a page plugin eg testprofed

profile-editorhtm (hint right click save as)

1 lt--2 Twizy page plugin Tuning Profile Editor3 Note included in firmware v32

(continues on next page)

316 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

4 --gt5

6 ltstylegt7 form-inline form-controlslider-value 8 width 70px9

10 radio-list 11 height 313px12 overflow-y auto13 overflow-x hidden14 padding-right 15px15 16 radio-list radio 17 overflow hidden18 19 radio-list key 20 min-width 20px21 display inline-block22 text-align center23 margin 0 10px24 25 radio-list kbd 26 min-width 60px27 display inline-block28 text-align center29 margin 0 20px 0 10px30 31 radio-list radio label 32 width 10033 text-align left34 padding 8px 30px35 36 radio-list radio labelactive 37 background-color 337ab738 color fff39 outline none40 41 radio-list radio labelactive input 42 outline none43 44 night radio-list radio labelhover 45 color fff46 47 ltstylegt48

49 ltdiv class=panel panel-primarygt50 ltdiv class=panel-headinggtTuning Profile ltspan id=headkeygtEditorltspangtltdivgt51 ltdiv class=panel-bodygt52 ltform action=gt53

54 ltdiv class=form-groupgt55 ltdiv class=flex-groupgt56 ltbutton type=button class=btn btn-default action-newgtNewltbuttongt57 ltbutton type=button class=btn btn-default action-loadgtLoadltbuttongt58 ltinput type=hidden id=input-key name=key value=gt59 ltinput type=hidden id=input-base64-reset name=base64-reset value=gt60 ltinput type=text class=form-control font-monospace placeholder=Base64

rarr˓profile code (continues on next page)

331 TLDR Examples 317

Open Vehicles

(continued from previous page)

61 name=base64 id=input-base64 value= autocapitalize=none autocorrect=rarr˓off

62 autocomplete=off spellcheck=falsegt63 ltdivgt64 ltdivgt65

66 ltul class=nav nav-tabsgt67 ltli class=activegtlta data-toggle=tab href=tab-drive aria-expanded=truegt

rarr˓Driveltagtltligt68 ltli class=gtlta data-toggle=tab href=tab-recup aria-expanded=falsegtRecup

rarr˓ltagtltligt69 ltli class=gtlta data-toggle=tab href=tab-ramps aria-expanded=falsegtRamps

rarr˓ltagtltligt70 ltulgt71 ltdiv class=tab-contentgt72

73 ltdiv id=tab-drive class=tab-pane section-drive active ingt74

75 ltfieldset id=part-speedgt76 ltlegendgtSpeedltlegendgt77 ltdiv class=form-horizontalgt78 ltdiv class=form-groupgt79 ltlabel class=control-label col-sm-2 for=input-speedgtMax speedlt

rarr˓labelgt80 ltdiv class=col-sm-10gtltdiv class=form-control slider id=speed gtlt

rarr˓divgt81 ltdivgt82 ltdiv class=form-groupgt83 ltlabel class=control-label col-sm-2 for=input-warngtWarn speedlt

rarr˓labelgt84 ltdiv class=col-sm-10gtltdiv class=form-control slider id=warn gtlt

rarr˓divgt85 ltdivgt86 ltdivgt87 ltfieldsetgt88

89 ltfieldset id=part-powergt90 ltlegendgtPowerltlegendgt91 ltdiv class=form-horizontalgt92 ltdiv class=form-groupgt93 ltlabel class=control-label col-sm-2 for=input-currentgtCurrentlt

rarr˓labelgt94 ltdiv class=col-sm-10gtltdiv class=form-control slider id=current gt

rarr˓ltdivgt95 ltdivgt96 ltdiv class=form-groupgt97 ltlabel class=control-label col-sm-2 for=input-torquegtTorqueltlabelgt98 ltdiv class=col-sm-10gtltdiv class=form-control slider id=torque gtlt

rarr˓divgt99 ltdivgt

100 ltdiv class=form-groupgt101 ltlabel class=control-label col-sm-2 for=input-power_lowgtPower lowlt

rarr˓labelgt102 ltdiv class=col-sm-10gtltdiv class=form-control slider id=power_low

rarr˓gtltdivgt103 ltdivgt104 ltdiv class=form-groupgt

(continues on next page)

318 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

105 ltlabel class=control-label col-sm-2 for=input-power_highgtPower highrarr˓ltlabelgt

106 ltdiv class=col-sm-10gtltdiv class=form-control slider id=power_highrarr˓gtltdivgt

107 ltdivgt108 ltdivgt109 ltfieldsetgt110

111 ltfieldset id=part-drivegt112 ltlegendgtDriveltlegendgt113 ltdiv class=form-horizontalgt114 ltdiv class=form-groupgt115 ltlabel class=control-label col-sm-2 for=input-drivegtDrive levellt

rarr˓labelgt116 ltdiv class=col-sm-10gtltdiv class=form-control slider id=drive gtlt

rarr˓divgt117 ltdivgt118 ltdiv class=form-groupgt119 ltlabel class=control-label col-sm-2 for=input-autodrive_refgtAuto 100

rarr˓ refltlabelgt120 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autodrive_

rarr˓ref gtltdivgt121 ltdivgt122 ltdiv class=form-groupgt123 ltlabel class=control-label col-sm-2 for=input-autodrive_minprcgtAuto

rarr˓min levelltlabelgt124 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autodrive_

rarr˓minprc gtltdivgt125 ltdivgt126 ltdivgt127 ltfieldsetgt128

129 ltfieldset id=part-tsmapdgt130 ltlegendgtTorqueSpeed-Map Driveltlegendgt131 ltdiv class=form-horizontalgt132 ltdiv class=form-groupgt133 ltlabel class=control-label col-sm-2 for=input-tsd_prc1gtTrq level 1

rarr˓ltlabelgt134 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc1 gt

rarr˓ltdivgt135 ltdivgt136 ltdiv class=form-groupgt137 ltlabel class=control-label col-sm-2 for=input-tsd_spd1gtat speed

rarr˓ltlabelgt138 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd1 gt

rarr˓ltdivgt139 ltdivgt140 ltdiv class=form-groupgt141 ltlabel class=control-label col-sm-2 for=input-tsd_prc2gtTrq level 2

rarr˓ltlabelgt142 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc2 gt

rarr˓ltdivgt143 ltdivgt144 ltdiv class=form-groupgt145 ltlabel class=control-label col-sm-2 for=input-tsd_spd2gtat speed

rarr˓ltlabelgt146 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd2 gt

rarr˓ltdivgt (continues on next page)

331 TLDR Examples 319

Open Vehicles

(continued from previous page)

147 ltdivgt148 ltdiv class=form-groupgt149 ltlabel class=control-label col-sm-2 for=input-tsd_prc3gtTrq level 3

rarr˓ltlabelgt150 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc3 gt

rarr˓ltdivgt151 ltdivgt152 ltdiv class=form-groupgt153 ltlabel class=control-label col-sm-2 for=input-tsd_spd3gtat speed

rarr˓ltlabelgt154 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd3 gt

rarr˓ltdivgt155 ltdivgt156 ltdiv class=form-groupgt157 ltlabel class=control-label col-sm-2 for=input-tsd_prc4gtTrq level 4

rarr˓ltlabelgt158 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc4 gt

rarr˓ltdivgt159 ltdivgt160 ltdiv class=form-groupgt161 ltlabel class=control-label col-sm-2 for=input-tsd_spd4gtat speed

rarr˓ltlabelgt162 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd4 gt

rarr˓ltdivgt163 ltdivgt164 ltdivgt165 ltfieldsetgt166

167 ltdivgt168

169 ltdiv id=tab-recup class=tab-pane section-recupgt170

171 ltfieldset id=part-recupgt172 ltlegendgtRecupltlegendgt173 ltdiv class=form-horizontalgt174 ltdiv class=form-groupgt175 ltlabel class=control-label col-sm-2 for=input-neutralgtNeutral level

rarr˓ltlabelgt176 ltdiv class=col-sm-10gtltdiv class=form-control slider id=neutral gt

rarr˓ltdivgt177 ltdivgt178 ltdiv class=form-groupgt179 ltlabel class=control-label col-sm-2 for=input-brakegtBrake levellt

rarr˓labelgt180 ltdiv class=col-sm-10gtltdiv class=form-control slider id=brake gtlt

rarr˓divgt181 ltdivgt182 ltdiv class=form-groupgt183 ltlabel class=control-label col-sm-2 for=input-autorecup_refgtAuto 100

rarr˓ refltlabelgt184 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autorecup_

rarr˓ref gtltdivgt185 ltdivgt186 ltdiv class=form-groupgt187 ltlabel class=control-label col-sm-2 for=input-autorecup_minprcgtAuto

rarr˓min levelltlabelgt188 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autorecup_

rarr˓minprc gtltdivgt (continues on next page)

320 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

189 ltdivgt190 ltdivgt191 ltfieldsetgt192

193 ltfieldset id=part-tsmapngt194 ltlegendgtTorqueSpeed-Map Neutralltlegendgt195 ltdiv class=form-horizontalgt196 ltdiv class=form-groupgt197 ltlabel class=control-label col-sm-2 for=input-tsn_prc1gtTrq level 1

rarr˓ltlabelgt198 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc1 gt

rarr˓ltdivgt199 ltdivgt200 ltdiv class=form-groupgt201 ltlabel class=control-label col-sm-2 for=input-tsn_spd1gtat speed

rarr˓ltlabelgt202 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd1 gt

rarr˓ltdivgt203 ltdivgt204 ltdiv class=form-groupgt205 ltlabel class=control-label col-sm-2 for=input-tsn_prc2gtTrq level 2

rarr˓ltlabelgt206 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc2 gt

rarr˓ltdivgt207 ltdivgt208 ltdiv class=form-groupgt209 ltlabel class=control-label col-sm-2 for=input-tsn_spd2gtat speed

rarr˓ltlabelgt210 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd2 gt

rarr˓ltdivgt211 ltdivgt212 ltdiv class=form-groupgt213 ltlabel class=control-label col-sm-2 for=input-tsn_prc3gtTrq level 3

rarr˓ltlabelgt214 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc3 gt

rarr˓ltdivgt215 ltdivgt216 ltdiv class=form-groupgt217 ltlabel class=control-label col-sm-2 for=input-tsn_spd3gtat speed

rarr˓ltlabelgt218 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd3 gt

rarr˓ltdivgt219 ltdivgt220 ltdiv class=form-groupgt221 ltlabel class=control-label col-sm-2 for=input-tsn_prc4gtTrq level 4

rarr˓ltlabelgt222 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc4 gt

rarr˓ltdivgt223 ltdivgt224 ltdiv class=form-groupgt225 ltlabel class=control-label col-sm-2 for=input-tsn_spd4gtat speed

rarr˓ltlabelgt226 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd4 gt

rarr˓ltdivgt227 ltdivgt228 ltdivgt229 ltfieldsetgt

(continues on next page)

331 TLDR Examples 321

Open Vehicles

(continued from previous page)

230

231 ltfieldset id=part-tsmapbgt232 ltlegendgtTorqueSpeed-Map Brakeltlegendgt233 ltdiv class=form-horizontalgt234 ltdiv class=form-groupgt235 ltlabel class=control-label col-sm-2 for=input-tsb_prc1gtTrq level 1

rarr˓ltlabelgt236 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc1 gt

rarr˓ltdivgt237 ltdivgt238 ltdiv class=form-groupgt239 ltlabel class=control-label col-sm-2 for=input-tsb_spd1gtat speed

rarr˓ltlabelgt240 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd1 gt

rarr˓ltdivgt241 ltdivgt242 ltdiv class=form-groupgt243 ltlabel class=control-label col-sm-2 for=input-tsb_prc2gtTrq level 2

rarr˓ltlabelgt244 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc2 gt

rarr˓ltdivgt245 ltdivgt246 ltdiv class=form-groupgt247 ltlabel class=control-label col-sm-2 for=input-tsb_spd2gtat speed

rarr˓ltlabelgt248 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd2 gt

rarr˓ltdivgt249 ltdivgt250 ltdiv class=form-groupgt251 ltlabel class=control-label col-sm-2 for=input-tsb_prc3gtTrq level 3

rarr˓ltlabelgt252 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc3 gt

rarr˓ltdivgt253 ltdivgt254 ltdiv class=form-groupgt255 ltlabel class=control-label col-sm-2 for=input-tsb_spd3gtat speed

rarr˓ltlabelgt256 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd3 gt

rarr˓ltdivgt257 ltdivgt258 ltdiv class=form-groupgt259 ltlabel class=control-label col-sm-2 for=input-tsb_prc4gtTrq level 4

rarr˓ltlabelgt260 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc4 gt

rarr˓ltdivgt261 ltdivgt262 ltdiv class=form-groupgt263 ltlabel class=control-label col-sm-2 for=input-tsb_spd4gtat speed

rarr˓ltlabelgt264 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd4 gt

rarr˓ltdivgt265 ltdivgt266 ltdivgt267 ltfieldsetgt268

269 ltdivgt270

(continues on next page)

322 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

271 ltdiv id=tab-ramps class=tab-pane section-rampsgt272

273 ltfieldset id=part-rampsglobalgt274 ltlegendgtGeneralltlegendgt275 ltdiv class=form-horizontalgt276 ltdiv class=form-groupgt277 ltlabel class=control-label col-sm-2 for=input-ramplimit_accelgtLimit

rarr˓upltlabelgt278 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramplimit_

rarr˓accel gtltdivgt279 ltdivgt280 ltdiv class=form-groupgt281 ltlabel class=control-label col-sm-2 for=input-ramplimit_decelgtLimit

rarr˓downltlabelgt282 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramplimit_

rarr˓decel gtltdivgt283 ltdivgt284 ltdiv class=form-groupgt285 ltlabel class=control-label col-sm-2 for=input-smoothgtSmoothinglt

rarr˓labelgt286 ltdiv class=col-sm-10gtltdiv class=form-control slider id=smooth gtlt

rarr˓divgt287 ltdivgt288 ltdivgt289 ltfieldsetgt290

291 ltfieldset id=part-rampsgt292 ltlegendgtRamp Speedsltlegendgt293 ltdiv class=form-horizontalgt294 ltdiv class=form-groupgt295 ltlabel class=control-label col-sm-2 for=input-ramp_startgtStart

rarr˓reverseltlabelgt296 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_start

rarr˓gtltdivgt297 ltdivgt298 ltdiv class=form-groupgt299 ltlabel class=control-label col-sm-2 for=input-ramp_accelgtAccelerate

rarr˓ltlabelgt300 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_accel

rarr˓gtltdivgt301 ltdivgt302 ltdiv class=form-groupgt303 ltlabel class=control-label col-sm-2 for=input-ramp_decelgtDecelerate

rarr˓ltlabelgt304 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_decel

rarr˓gtltdivgt305 ltdivgt306 ltdiv class=form-groupgt307 ltlabel class=control-label col-sm-2 for=input-ramp_neutralgtNeutral

rarr˓ltlabelgt308 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_neutral

rarr˓ gtltdivgt309 ltdivgt310 ltdiv class=form-groupgt311 ltlabel class=control-label col-sm-2 for=input-ramp_brakegtBrakelt

rarr˓labelgt312 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_brake

rarr˓gtltdivgt (continues on next page)

331 TLDR Examples 323

Open Vehicles

(continued from previous page)

313 ltdivgt314 ltdivgt315 ltfieldsetgt316

317 ltdivgt318

319 ltdivgt320

321 ltbrgt322 ltdiv class=form-horizontalgt323 ltdiv class=form-groupgt324 ltlabel class=control-label col-sm-2 for=input-labelgtLabelltlabelgt325 ltdiv class=col-sm-10gt326 ltinput type=text class=form-control placeholder=Short button label327 name=label id=input-label value= autocapitalize=none autocorrect=

rarr˓off328 autocomplete=off spellcheck=falsegt329 ltdivgt330 ltdivgt331 ltdiv class=form-groupgt332 ltlabel class=control-label col-sm-2 for=input-titlegtTitleltlabelgt333 ltdiv class=col-sm-10gt334 ltinput type=text class=form-control placeholder=optional titlename335 name=title id=input-title value= autocapitalize=none autocorrect=

rarr˓off336 autocomplete=off spellcheck=falsegt337 ltdivgt338 ltdivgt339 ltdivgt340

341 ltbrgt342 ltdiv class=text-centergt343 ltbutton type=button class=btn btn-default action-resetgtResetltbuttongt344 ltbutton type=button class=btn btn-default action-saveasgtSave asltbuttongt345 ltbutton type=button class=btn btn-primary action-savegtSaveltbuttongt346 ltdivgt347

348 ltformgt349 ltdivgt350 ltdivgt351

352 ltdiv id=key-dialog gt353

354 ltscriptgt355 (function()356

357 init sliders358

359 $(speed)slider( unitkph min6 max120 default80 value80rarr˓checkedfalse )

360 $(warn)slider( unitkph min6 max120 default89 value89 checkedfalserarr˓)

361

362 $(current)slider( unit min10 max123 default100 value100rarr˓checkedfalse )

363 $(torque)slider( unit min10 max130 default100 value100rarr˓checkedfalse )

(continues on next page)

324 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

364 $(power_low)slider( unit min10 max139 default100 value100rarr˓checkedfalse )

365 $(power_high)slider( unit min10 max130 default100 value100rarr˓checkedfalse )

366

367 $(drive)slider( unit min10 max100 default100 value100rarr˓checkedfalse )

368 $(autodrive_ref)slider( unitkW min0 max25 step01 default0 value0rarr˓ checkedfalse )

369 $(autodrive_minprc)slider( unit min0 max100 default0 value0rarr˓checkedfalse )

370

371 $(tsd_prc1)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

372 $(tsd_spd1)slider( unitkph min0 max120 default33 value33rarr˓checkedfalse )

373 $(tsd_prc2)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

374 $(tsd_spd2)slider( unitkph min0 max120 default39 value39rarr˓checkedfalse )

375 $(tsd_prc3)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

376 $(tsd_spd3)slider( unitkph min0 max120 default50 value50rarr˓checkedfalse )

377 $(tsd_prc4)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

378 $(tsd_spd4)slider( unitkph min0 max120 default66 value66rarr˓checkedfalse )

379

380 $(neutral)slider( unit min0 max100 default18 value18rarr˓checkedfalse )

381 $(brake)slider( unit min0 max100 default18 value18 checkedfalse rarr˓)

382 $(autorecup_ref)slider( unitkW min0 max25 step01 default0 value0rarr˓ checkedfalse )

383 $(autorecup_minprc)slider( unit min0 max100 default0 value0rarr˓checkedfalse )

384

385 $(tsn_prc1)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

386 $(tsn_spd1)slider( unitkph min0 max120 default33 value33rarr˓checkedfalse )

387 $(tsn_prc2)slider( unit min0 max100 default80 value80rarr˓checkedfalse )

388 $(tsn_spd2)slider( unitkph min0 max120 default39 value39rarr˓checkedfalse )

389 $(tsn_prc3)slider( unit min0 max100 default50 value50rarr˓checkedfalse )

390 $(tsn_spd3)slider( unitkph min0 max120 default50 value50rarr˓checkedfalse )

391 $(tsn_prc4)slider( unit min0 max100 default20 value20rarr˓checkedfalse )

392 $(tsn_spd4)slider( unitkph min0 max120 default66 value66rarr˓checkedfalse )

393

394 $(tsb_prc1)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

(continues on next page)

331 TLDR Examples 325

Open Vehicles

(continued from previous page)

395 $(tsb_spd1)slider( unitkph min0 max120 default33 value33rarr˓checkedfalse )

396 $(tsb_prc2)slider( unit min0 max100 default80 value80rarr˓checkedfalse )

397 $(tsb_spd2)slider( unitkph min0 max120 default39 value39rarr˓checkedfalse )

398 $(tsb_prc3)slider( unit min0 max100 default50 value50rarr˓checkedfalse )

399 $(tsb_spd3)slider( unitkph min0 max120 default50 value50rarr˓checkedfalse )

400 $(tsb_prc4)slider( unit min0 max100 default20 value20rarr˓checkedfalse )

401 $(tsb_spd4)slider( unitkph min0 max120 default66 value66rarr˓checkedfalse )

402

403

404 $(ramplimit_accel)slider( unit min1 max100 default30 value30rarr˓checkedfalse )

405 $(ramplimit_decel)slider( unit min0 max100 default30 value30rarr˓checkedfalse )

406 $(smooth)slider( unit min0 max100 default70 value70 checkedfalserarr˓)

407

408 $(ramp_start)slider( unitpermil min1 max250 default40 value40rarr˓checkedfalse )

409 $(ramp_accel)slider( unit min1 max100 default25 value25rarr˓checkedfalse )

410 $(ramp_decel)slider( unit min0 max100 default20 value20rarr˓checkedfalse )

411 $(ramp_neutral)slider( unit min0 max100 default40 value40rarr˓checkedfalse )

412 $(ramp_brake)slider( unit min0 max100 default40 value40rarr˓checkedfalse )

413

414 profile handling415

416 const keys = [417 checksum418 speed419 warn420 torque421 power_low422 power_high423 drive424 neutral425 brake426 tsd_spd1427 tsd_spd2428 tsd_spd3429 tsd_spd4430 tsd_prc1431 tsd_prc2432 tsd_prc3433 tsd_prc4434 tsn_spd1435 tsn_spd2436 tsn_spd3

(continues on next page)

326 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

437 tsn_spd4438 tsn_prc1439 tsn_prc2440 tsn_prc3441 tsn_prc4442 tsb_spd1443 tsb_spd2444 tsb_spd3445 tsb_spd4446 tsb_prc1447 tsb_prc2448 tsb_prc3449 tsb_prc4450 ramp_start451 ramp_accel452 ramp_decel453 ramp_neutral454 ramp_brake455 smooth456 brakelight_on457 brakelight_off458 ramplimit_accel459 ramplimit_decel460 autorecup_minprc461 autorecup_ref462 autodrive_minprc463 autodrive_ref464 current465 ]466

467 const scale = 468 autodrive_ref 01469 autorecup_ref 01470 471

472 var profile = 473

474 var plist = [475 label - title Working Set 476 label PWR title Power 477 label ECO title Economy 478 label ICE title Winter 479 ]480

481 load profile list482 var plistloader = loadcmd(config list xrt)then(function(data) 483 var lines = datasplit(n) line i key484 for (i = 0 i lt lineslength i++) 485 line = lines[i]match(profile([0-9]2)([^]) ())486 if (line ampamp linelength == 4) 487 key = Number(line[1])488 if (key lt 1 || key gt 99) continue489 if (plist[key]) plist[key] = 490 plist[key][line[2]||profile] = line[3]491 492 493 )

(continues on next page)

331 TLDR Examples 327

Open Vehicles

(continued from previous page)

494

495 current control rarr power ranges496 function currentControl(on trigger) 497 if (on) 498 $(input-torque input-power_low input-power_high)

rarr˓slider( max 254 )499 else 500 $(input-torque input-power_high)slider( max 130 )501 $(input-power_low)slider( max 139 )502 503 504 $(input-current)on(change function(ev) 505 currentControl(thischecked)506 $(input-torque input-power_low input-power_high)trigger(change)507 )508

509 load profile into sliders510 function loadProfile() 511 currentControl(profile[current] gt= 0)512 $map(profile function(val key) 513 $(input-+key)slider( value (val gt= 0) (val (scale[key]||1)) null

rarr˓checked (val gt= 0) )514 )515 516

517 calculate profile checksum518 function calcChecksum() 519 var checksum i520 checksum = 0x0101521 for (i=1 iltkeyslength i++)522 checksum += profile[keys[i]] + 1523 if ((checksum amp 0x0ff) == 0)524 checksum gtgt= 8525 return (checksum amp 0x0ff) - 1526 527

528 load a base64 string into profile529 function loadBase64(base64) 530 var bin = atob(base64)531 $map(keys function(key i) profile[key] = (bincharCodeAt(i)||0) - 1 )532 if (profile[checksum] == calcChecksum()) 533 loadProfile()534 return true535 else 536 confirmdialog(Profile Error Invalid base64 code (checksum mismatch) [

rarr˓Close])537 return false538 539 540

541 make a base64 string from profile542 function makeBase64() 543 profile[checksum] = calcChecksum()544 var u8 = new Uint8Array(keyslength)545 $map(keys function(key i) u8[i] = profile[key] + 1 )546 return btoa(StringfromCharCodeapply(null u8))547

(continues on next page)

328 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

548

549 load a profile550 function loadKey(key) 551 if (key lt 0 || key gt 99) return552 plistloaderthen(function() 553 $(input-label)val(plist[key] ampamp plist[key][label] || )554 $(input-title)val(plist[key] ampamp plist[key][title] || )555 loadcmd(xrt cfg get + key)fail(function(request textStatus errorThrown) 556 confirmdialog(Load Profile xhrErrorInfo(request textStatus errorThrown)

rarr˓[Close])557 )done(function(res) 558 var base64559 if (resmatch(errori))560 base64 = AQ561 else562 base64 = ressubstr(reslastIndexOf( )+1)563 if (loadBase64(base64)) 564 $(input-key)val(key)565 $(input-base64 input-base64-reset)val(base64)566 $(headkey)text( + key)567 568 )569 )570 571

572 save profile573 function saveKey(key) 574 if (key lt 0 || key gt 99) return575 var base64 = $(input-base64)val()576 label = $(input-label)val()replace(g )577 title = $(input-title)val()replace(g )578 ckey = profile + ((keylt10)0) + key579 var cmd = xrt cfg set + key + + base64 + + label + + title +

rarr˓580 loadcmd(cmd)fail(function(request textStatus errorThrown) 581 confirmdialog(Save Profile xhrErrorInfo(request textStatus errorThrown) [

rarr˓Close])582 )done(function(res) 583 confirmdialog(Save Profile res [Close])584 if (resmatch(errori)) 585 if (key gt 0) 586 if (plist[key]) plist[key] = 587 plist[key][label] = label588 plist[key][title] = title589 590 $(input-key)val(key)591 $(input-base64-reset)val(base64)592 $(headkey)text( + key)593 594 )595 596

597 base64 input598 $(input-base64)on(change function(ev) 599 var base64 = $(this)val() || AQ600 if (loadBase64(base64))601 $(input-base64-reset)val(base64)

(continues on next page)

331 TLDR Examples 329

Open Vehicles

(continued from previous page)

602 )603

604 update profile amp base64 on slider changes605 $(slider-value)on(change function(ev) 606 var key = thisname607 var val = Mathmax(thismin Mathmin(thismax 1thisvalue))608 profile[key] = thischecked (val (scale[key]||1)) -1609 var base64 = makeBase64()610 $(input-base64)val(base64)611 )612

613 prep key dialog614 $(key-dialog)dialog(615 show false616 onShow function(input) 617 var $this = $(this)618 $thisaddClass(loading)619 plistloaderthen(function(data) 620 var curkey = $(input-key)val() || 0 i label title621 $plist = $(ltdiv class=radio-list data-toggle=buttons gt)622 for (i = 0 i lt= Mathmin(99 plistlength + 2) i++) 623 if (plist[i] ampamp (i==0 || plist[i]profile)) 624 label = plist[i]label || -625 title = plist[i]title || (plist[i]profilesubstr(0 10) + )626 else 627 label = -628 title = -new-629 630 $plistappend(ltdiv class=radiogtltlabel class=btngt +631 ltinput type=radio name=key value= + i + gtltspan class=keygt +632 ((i==0) WS ( + ((ilt10)0) + i)) + ltspangt ltkbdgt +633 encode_html(label) + ltkbdgt + encode_html(title) + ltlabelgtltdivgt)634 635 $thisfind(modal-body)append($plist)find(input[value=+curkey+])636 prop(checked true)parent()addClass(active)637 $plist638 on(dblclick labelbtn function(ev) $thisdialog(triggerButton

rarr˓1) )639 on(keypress function(ev) if (evwhich==13) $thisdialog(triggerButton

rarr˓ 1) )640 $thisremoveClass(loading)641 )642 643 onShown function(input) 644 $(this)find(btnactive)focus()645 646 onHide function(input) 647 var $this = $(this) dlg = $thisdata(dialog)648 var key = $thisfind(input[name=key]checked)val()649 if (key == undefined ampamp inputbutton ampamp inputbuttonindex)650 dlgoptionsonActioncall(this key)651 652 )653

654 buttons655 $(action-new)on(click function(ev) 656 $(slider)slider( value null )

(continues on next page)

330 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

657 $(headkey)text(Editor)658 $(input-base64 input-label input-title)val()trigger(change)659 )660 $(action-reset)on(click function(ev) 661 $(input-base64)val($(input-base64-reset)val())trigger(change)662 )663 $(action-load)on(click function(ev) 664 $(key-dialog)dialog(665 show true title Load Profile body 666 buttons [ label Cancel btnClass default label Load btnClass

rarr˓primary ]667 onAction function(key) loadKey(key) 668 )669 )670 $(action-saveas)on(click function(ev) 671 $(key-dialog)dialog(672 show true title Save Profile body 673 buttons [ label Cancel btnClass default label Save btnClass

rarr˓primary ]674 onAction function(key) saveKey(key) 675 )676 )677 $(action-save)on(click function(ev) 678 var key = $(input-key)val()679 if (key === )680 $(action-saveas)trigger(click)681 else682 saveKey(key)683 )684

685 start load profile open load dialog686 if (pageparams[key] == undefined)687 loadKey(pageparams[key])688 else689 $(action-load)trigger(click)690

691 )()692 ltscriptgt

331 TLDR Examples 331

Open Vehicles

33117 Twizy Drivemode Button Editor

This plugin has been added to the Twizy code Itrsquos used here as a more complex example of what can be done byplugins

Itrsquos an editor for the drivemode buttons the Twizy adds to the dashboard for quick tuning profile changes The editorallows to change the layout (number and order of buttons) and the profiles to use

It includes a profile selector built with the dialog widget that retrieves the available profiles from the OVMS configstore

Install not necessary if vehicle Twizy is configured (see ldquoTwizyrdquo menu) If yoursquod like to test this for another vehicleadd as a page plugin eg testdmconfig

drivemode-confightm (hint right click save as)

1 lt--2 Twizy page plugin Drivemode Button Configuration3 Note included in firmware v324 --gt5

6 ltstylegt7 fullscreened panel-single panel-body 8 padding 10px9

10

11 btn-group-lggtbtn12 btn-lg 13 padding 10px 3px14 overflow hidden15 16 loadmenu btn 17 font-weight bold18 19 btn-groupbtn-group-lgexchange 20 width 221

(continues on next page)

332 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

22 editor btnhover 23 background-color e6e6e624 25 editor btn-group-lggtbtn26 editor btn-lg 27 padding 10px 0px28 font-size 15px29 30 editor exchange btn 31 font-weight bold32 33 night editor btn 34 color 00035 background 88836 37 night editor btnfocus38 night editor btnfocus39 night editor btnhover 40 background-color e0e0e041 42

43 radio-list 44 height 313px45 overflow-y auto46 overflow-x hidden47 padding-right 15px48 49 radio-list radio 50 overflow hidden51 52 radio-list key 53 min-width 20px54 display inline-block55 text-align center56 margin 0 10px57 58 radio-list kbd 59 min-width 60px60 display inline-block61 text-align center62 margin 0 20px 0 10px63 64 radio-list radio label 65 width 10066 text-align left67 padding 8px 30px68 69 radio-list radio labelactive 70 background-color 337ab771 color fff72 outline none73 74 radio-list radio labelactive input 75 outline none76 77 night radio-list radio labelhover 78 color fff

(continues on next page)

331 TLDR Examples 333

Open Vehicles

(continued from previous page)

79 80 ltstylegt81

82 ltdiv class=panel panel-primarygt83 ltdiv class=panel-headinggtDrivemode Button Configurationltdivgt84 ltdiv class=panel-bodygt85 ltform action=gt86

87 ltp id=infogtLoading button configurationltpgt88

89 ltdiv id=loadmenu class=btn-group btn-group-justifiedgtltdivgt90 ltdiv id=editor class=btn-group btn-group-justifiedgt91 ltdiv class=btn-group btn-group-lg add backgt92 ltbutton type=button class=btn title=Add buttongtltbuttongt93 ltdivgt94 ltdivgt95

96 ltbrgt97 ltbrgt98 ltdiv class=text-centergt99 ltbutton type=button class=btn btn-default onclick=reloadpage()gtResetlt

rarr˓buttongt100 ltbutton type=button class=btn btn-primary action-savegtSaveltbuttongt101 ltdivgt102

103 ltformgt104 ltdivgt105 ltdiv class=panel-footergt106 lta class=btn btn-sm btn-default target=main href=dashboardgtDashboardltagt107 lta class=btn btn-sm btn-default target=main href=xrtdrivemodegtDrivemodelt

rarr˓agt108 ltdivgt109 ltdivgt110

111 ltdiv id=key-dialog gt112

113 ltscriptgt114 (function()115

116 var $menu = $(loadmenu) $edit = $(editor) $back = $editfind(back)117

118 var pbuttons = [0123]119 var plist = [120 label STD title Standard 121 label PWR title Power 122 label ECO title Economy 123 label ICE title Winter 124 ]125

126 load profile list amp button config127 $(panel)addClass(loading)128 var plistloader = loadcmd(config list xrt)then(function(data) 129 var lines = datasplit(n) line i key130 for (i = 0 i lt lineslength i++) 131 line = lines[i]match(profile([0-9]2)([^]) ())132 if (line ampamp linelength == 4) 133 key = Number(line[1])

(continues on next page)

334 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

134 if (key lt 1 || key gt 99) continue135 if (plist[key]) plist[key] = 136 plist[key][line[2]||profile] = line[3]137 continue138 139 line = lines[i]match(profile_buttons ())140 if (line ampamp linelength == 2) 141 try 142 pbuttons = JSONparse([ + line[1] + ])143 catch (e) 144 consoleerror(e)145 146 147 148 )149

150 prep key dialog151 $(key-dialog)dialog(152 show false153 title Select Profile154 buttons [ label Cancel btnClass default label Select btnClass

rarr˓primary ]155 onShow function(input) 156 var $this = $(this) dlg = $thisdata(dialog)157 $thisaddClass(loading)158 plistloaderthen(function(data) 159 var curkey = dlgoptionskey || 0 i label title160 $plist = $(ltdiv class=radio-list data-toggle=buttons gt)161 for (i = 0 i lt= Mathmin(99 plistlength-1) i++) 162 if (plist[i] ampamp (i==0 || plist[i]profile)) 163 label = plist[i]label || -164 title = plist[i]title || (plist[i]profilesubstr(0 10) + )165 else 166 label = -167 title = -new-168 169 $plistappend(ltdiv class=radiogtltlabel class=btngt +170 ltinput type=radio name=key value= + i + gtltspan class=keygt +171 ((i==0) STD ( + ((ilt10)0) + i)) + ltspangt ltkbdgt +172 encode_html(label) + ltkbdgt + encode_html(title) + ltlabelgtltdivgt)173 174 $thisfind(modal-body)html($plist)find(input[value=+curkey+])175 prop(checked true)parent()addClass(active)176 $plist177 on(dblclick labelbtn function(ev) $thisdialog(triggerButton

rarr˓1) )178 on(keypress function(ev) if (evwhich==13) $thisdialog(triggerButton

rarr˓ 1) )179 $thisremoveClass(loading)180 )181 182 onShown function(input) 183 $(this)find(btnactive)focus()184 185 onHide function(input) 186 var $this = $(this) dlg = $thisdata(dialog)187 var key = $thisfind(input[name=key]checked)val()

(continues on next page)

331 TLDR Examples 335

Open Vehicles

(continued from previous page)

188 if (key == undefined ampamp inputbutton ampamp inputbuttonindex)189 dlgoptionsonActioncall(this key)190 191 )192

193 profile selection194 $(loadmenu)on(click button function(ev) 195 var $this = $(this)196 $(key-dialog)dialog(197 show true198 key $thisval()199 onAction function(key) 200 var prof = plist[key] || 201 $thisval(key)202 $thisattr(title proftitle || )203 $thistext(proflabel || (+((keylt10)0)+key))204 205 )206 )207

208 create buttons209

210 function addButton(key front) 211 var prof = plist[key] || 212 if ($menu[0]childElementCount == 0) 213 $backbefore(214 ltdiv class=btn-group btn-group-lg add frontgt215 ltbutton type=button class=btn title=Add buttongtltbuttongt216 ltdivgt217 ltdiv class=btn-group btn-group-lg removegt218 ltbutton type=button class=btn title=Remove buttongtltbuttongt219 ltdivgt)220 else 221 $backbefore(222 ltdiv class=btn-group btn-group-lg exchangegt223 ltbutton type=button class=btn title=Exchange buttonsgtltbuttongt224 ltdivgt225 ltdiv class=btn-group btn-group-lg removegt226 ltbutton type=button class=btn title=Remove buttongtltbuttongt227 ltdivgt)228 229 var $btn = $(230 ltdiv class=btn-group btn-group-lggt231 ltbutton type=button value=key class=btn btn-default title=titlegt

rarr˓labelltbuttongt232 ltdivgt233 replace(key key)234 replace(title encode_html(proftitle || ))235 replace(label encode_html(proflabel || +((keylt10)0)+key)))236 if (front)237 $menuprepend($btn)238 else239 $menuappend($btn)240 241

242 plistloaderthen(function() 243 var key prof

(continues on next page)

336 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

244 for (var i = 0 i lt pbuttonslength i++) 245 addButton(pbuttons[i])246 247 $(panel)removeClass(loading)248 $(info)text(Click button to select profile)249 )250

251 editor buttons252 $(editor)on(click add btn function(ev) 253 addButton(0 $(this)parent()hasClass(front))254 )on(click remove btn function(ev) 255 var $this = $(this) pos = $editfind(btn)index(this) gtgt 1256 $($menuchildren()get(pos))detach()257 if (pos gt 0 || $menu[0]childElementCount == 0)258 $thisparent()prev()detach()259 else if ($menu[0]childElementCount = 0)260 $thisparent()next()detach()261 $thisparent()detach()262 )on(click exchange btn function(ev) 263 var pos = $editfind(btn)index(this) gtgt 1264 if (pos gt 0) $($menuchildren()get(pos))insertBefore($($menuchildren()get(pos-

rarr˓1)))265 )266

267 save268 $(action-save)on(click function(ev) 269 pbuttons = []270 $menufind(btn)each(function() pbuttonspush(thisvalue) )271 loadcmd(config set xrt profile_buttons + pbuttonstoString())272 fail(function(request textStatus errorThrown) 273 confirmdialog(Save Configuration xhrErrorInfo(request textStatus

rarr˓errorThrown) [Close])274 )275 done(function(res) 276 confirmdialog(Save Configuration res [Close])277 )278 )279

280 )()281 ltscriptgt

332 Installing Plugins

The framework supports installing user content as pages or extensions to pages To install an example

1 Menu Config rarr Web Plugins

2 Add plugin type ldquoPagerdquo name eg ldquodevmetricsrdquo (used as the file name in storeplugin)

3 Save rarr Edit

4 Set page to eg ldquousrdevmetricsrdquo label to eg ldquoDev Metricsrdquo

5 Set the menu to eg ldquoToolsrdquo and auth to eg ldquoNonerdquo

6 Paste the page source into the content area

332 Installing Plugins 337

Open Vehicles

7 Save rarr the page is now accessible in the ldquoToolsrdquo menu

Hint use the standard editor (tools menu) in a second session to edit a plugin repeatedly during test development

333 Basics

The OVMS web framework is based on HTML 5 Bootstrap 3 and jQuery 3 Plenty documentation and guides onthese basic web technologies is available on the web a very good resource is w3schoolscom

For charts the framework includes Highcharts 6 Info and documentation on this is available on Highchartscom

The framework is ldquoAJAXrdquo based The index page loads the framework assets and defines a default container structureincluding a menu and a main container Content pages are loaded into the main container The window URLincludes the page URL after the hash mark

bull httpovmslocalstatus ndash this loads page status into main

bull httpovmslocaldashboardnm=1 ndash this loads the dashboard and activates night mode

Links and forms having id targets are automatically converted to AJAX by the framework

bull lta href=editpath=sdindextxt target=maingtEdit indextxtltagt ndash loadthe editor

Pages can be loaded outside the framework as well (eg httpovmslocalstatus) See index source onframework scripts and styles to include if yoursquod like to design standalone pages using the framework methods

If file system access is enabled all URLs not handled by the system or a user plugin (see below) are mapped onto thefile system under the configured web root Of course files can be loaded into the framework as well For example ifthe web root is sd (default)

bull httpovmslocalmypagehtm ndash load file sdmypagehtm into main

bull httptest1locallogs ndash load directory listing sdlogs into main

Important Note the framework has a global shared context (ie the window object) To avoid polluting the globalcontext with local variables good practice is to wrap your local scripts into closures Pattern

ltscriptgt(function()

insert your code here )()ltscriptgt

334 Authorization

Page access can be restricted to authorized users either session based or per access File access can be restricted usingdigest authentication

The module password is used for all authorizations A user account or API key administration is not yet included themain username is admin

To create a session call the login page and store the resulting cookie

1 curl -c auth -b auth http19216841login -d username=admin -dpassword=

2 curl -c auth -b auth http19216841apiexecutecommand=xrt+cfg+info

338 Chapter 33 Web Framework amp Plugins

Open Vehicles

To issue a single call eg to execute a command from a Wifi button supply the password as apikey

bull curl http19216841apiexecuteapikey=passwordampcommand=xrt+cfg+info

bull curl http19216841apiexecuteapikey=passwordamptype=jsampcommand=print(Duktapeversion)

335 Web UI Development Framework

To simplify and speed up UI and plugin development you can simply run a local web server from the dev directoryof the ovms_webserver component source

Preparation create your local git clone if you donrsquot have one already

gt cd ~gt git clone httpsgithubcomopenvehiclesOpen-Vehicle-Monitoring-System-3git

Local web server options List of static web servers

Example

gt cd ~Open-Vehicle-Monitoring-System-3vehicleOVMSV3componentsovms_webserverdevgt python3 -m httpserver 8000Serving HTTP on 0000 port 8000 (http00008000)

Now open the development framework in your browser at URI httplocalhost8000 If that doesnrsquot workcheck your firewall settings for port 8000 on localhost

You should see the examples home Edit indexhtm to add custom menus edit homehtm to add custom homebuttons

Hint to test your plugin for mobile devices use the mobile emulation mode of your browserrsquos development toolkitMobile mode allows to test small screen resolutions rotation and touch events

A static local HTTP server allows to use all frontend features but cannot emulate the backend API (commandscriptexecution) If using a CGI capable HTTP server you can also add a proxy handler for apiexecute that forwardsthe requests to your module by HTTP or SSH

If you want to add your results to a C++ module use the tools mksrc and mksrcf to convert your HTML files intoC++ compatible strings mksrc is meant for static strings mksrcf for strings with printf style placeholders

335 Web UI Development Framework 339

Open Vehicles

340 Chapter 33 Web Framework amp Plugins

CHAPTER 34

Scripting

341 Example Foglight

This is an example for combining a script module implementing some functional extension with a web plugin toprovide a user interface

The plugin realizes a fog light with automatic speed adaption ie the light will be turned off above a configurablespeed and on again when the vehicle slows down again It also switches off automatically when the vehicle is parked

The plugin shows how to

bull read custom config variables

bull use module state variables

341

Open Vehicles

bull react to events

bull send custom events

bull read metrics

bull execute system commands

bull provide new commands

bull provide a web UI

3411 Installation

bull Save foglightjs as storescriptslibfoglightjs (add the lib directory as necessary)

bull Add foglighthtm as a web hook type plugin at page dashboard hook bodypre

bull Execute script eval foglight = require(libfoglight)

Optionally

bull To test the module execute script eval foglightinfo() ndash it should print config and state

bull To automatically load the module on boot add the line foglight = require(libfoglight) tostorescriptsovmsmainjs

3412 Commands Functions

The module provides two public API functions

Function Descriptionfoglightset(onoff) switch fog light on (1) off (0)foglightinfo() output config amp state in JSON format

To call these from a shell use script eval Example

bull script eval foglightset(1)

3413 Configuration

Wersquoll add the configuration for this to the vehicle section

Config Default Descriptionfoglightport 1 EGPIO output port numberfoglightauto no yes = speed automationfoglightspeedon 45 auto turn on below this speedfoglightspeedoff 55 auto turn off above this speed

Note You can add arbitrary config instances to defined sections simply by setting them config set vehiclefoglightauto yes

342 Chapter 34 Scripting

Open Vehicles

Update Beginning with firmware release 32009 a general configuration section usr is provided for plugins Werecommend using this for all custom parameters now Keep in mind to prefix all instances introduced by the pluginname so your plugin can nicely coexist with others

To store the config for simple amp quick script access and implement the defaults we introduce an internal modulemember object cfg

Listing 1 Module Plugin

28 var cfg = 29 foglightport 130 foglightauto no31 foglightspeedon 4532 foglightspeedoff 5533

By foglight = require() the module is added to the global name space as a javascript object This objectcan contain any internal standard javascript variables and functions Internal members are hidden by default if youwould like to expose the cfg object you would simply add a reference to it to the exports object as is done belowfor the API methods

Reading OVMS config variables from a script currently needs to be done by executing config list and parsingthe output This is done by the readconfig() function

42 function readconfig() 43 var cmdres lines cols i44 cmdres = OvmsCommandExec(config list vehicle)45 lines = cmdressplit(n)46 for (i=0 iltlineslength i++) 47 if (lines[i]indexOf(foglight) gt= 0) 48 cols = lines[i]substr(2)split( )49 cfg[cols[0]] = cols[1]50 51

Update OVMS release 32009 adds the OvmsConfigGetValues() API To use this we would now omit theldquofoglightrdquo prefix from our cfg properties Reading the foglight configuration can then be reduced to a single line

Objectassign(cfg OvmsConfigGetValues(vehicle foglight))

3414 Listen to Events

The module needs to listen to three events

bull configchanged triggers reloading the configuration

bull ticker1 is used to check the speed once per second

bull vehicleoff automatically also turns off the fog light

The per second ticker is only necessary when the speed adaption is enabled so we can use this to show how todynamically add and remove event handlers through the PubSub API

341 Example Foglight 343

Open Vehicles

Listing 2 Module Plugin

52 update ticker subscription53 if (cfg[foglightauto] == yes ampamp stateticker) 54 stateticker = PubSubsubscribe(ticker1 checkspeed)55 else if (cfg[foglightauto] = yes ampamp stateticker) 56 PubSubunsubscribe(stateticker)57 stateticker = false58

state is another internal object for our state variables

3415 Send Events

Sending custom events is a lightweight method to inform the web UI (or other plugins) about simple state changes Inthis case wersquod like to inform listeners when the fog light actually physically is switched on or off so the web UI cangive visual feedback to the driver on this

Beginning with firmware release 32006 there is a native API OvmsEventsRaise() available to send events

Before 32006 we simply use the standard command event raise

Listing 3 Module Plugin

61 EGPIO port control62 function toggle(onoff) 63 if (stateport = onoff) 64 OvmsCommandExec(egpio output + cfg[foglightport] + + onoff)65 stateport = onoff66 OvmsCommandExec(event raise usrfoglight + (onoff on off))67 68

The web plugin subscribes to the foglight events just as to any system event

Listing 4 Web Plugin

64 Listen to foglight events65 $(foglight)on(msgevent function(e event) 66 if (event == usrfoglighton)67 update( state port 1 )68 else if (event == usrfoglightoff)69 update( state port 0 )70 else if (event == vehicleoff) 71 update( state on 0 )72 $(action-foglight-output)empty()73 74 )

Note You can raise any event you like but you shouldnrsquot raise system events without good knowledge of theireffects Event codes are simply strings so yoursquore free to extend them Use the prefix usr for custom events to avoidpotential conflicts with future system event additions

344 Chapter 34 Scripting

Open Vehicles

3416 Read Metrics

Reading metrics is straight forward through the OvmsMetrics API

Listing 5 Module Plugin

74 var speed = OvmsMetricsAsFloat(vpspeed)

Use Value() instead of AsFloat() for non-numerical metrics

Note You cannot subscribe to metrics changes directly (yet) Metrics can change thousands of times per secondwhich would overload the scripting capabilities To periodically check a metric register for a ticker event (as shownhere)

3417 Provide Commands

To add commands simply expose their handler functions through the exports object By this users will be able tocall these functions using the script eval command from any shell or from any script by referencing them viathe global module variable foglight in our case

Listing 6 Module Plugin

99 API method foglightinfo()100 exportsinfo = function() 101 JSONprint( cfg cfg state state )102

JSONprint() is a convenient way to communicate with a web plugin as that wonrsquot need to parse some potentiallyambigous textual output but can simply use JSONparse() to read it into a variable

Listing 7 Web Plugin

82 Init amp install83 $(main)one(load function(ev) 84 loadcmd(script eval foglightinfo())then(function(output) 85 update(JSONparse(output))

Note Keep in mind commands should always output some textual response indicating their action and result If acommand does nothing it should tell the user so If a command is not intended for shell use it should still providesome clue about this when called from the shell

3418 Module Plugin

foglightjs (hint right click save as)

1 2 storescriptslibfoglightjs3 4 Module plugin5 Foglight control with speed adaption and auto off on vehicle off

(continues on next page)

341 Example Foglight 345

Open Vehicles

(continued from previous page)

6 7 Version 10 Michael Balzer ltdexterdexters-webdegt8 9 Enable

10 - install at above path11 - add to storescriptsovmsmainjs12 foglight = require(libfoglight)13 - script reload14 15 Config16 - vehicle foglightport EGPIO output port number17 - vehicle foglightauto yes = speed automation18 - vehicle foglightspeedon auto turn on below this speed19 - vehicle foglightspeedoff auto turn off above this speed20 21 Usage22 - script eval foglightset(1) toggle foglight on23 - script eval foglightset(0) toggle foglight off24 - script eval foglightinfo() show config amp state (JSON)25 26 27

28 var cfg = 29 foglightport 130 foglightauto no31 foglightspeedon 4532 foglightspeedoff 5533 34

35 var state = 36 on 0 foglight onoff37 port 0 current port output state38 ticker false ticker subscription39 40

41 Read config42 function readconfig() 43 var cmdres lines cols i44 cmdres = OvmsCommandExec(config list vehicle)45 lines = cmdressplit(n)46 for (i=0 iltlineslength i++) 47 if (lines[i]indexOf(foglight) gt= 0) 48 cols = lines[i]substr(2)split( )49 cfg[cols[0]] = cols[1]50 51 52 update ticker subscription53 if (cfg[foglightauto] == yes ampamp stateticker) 54 stateticker = PubSubsubscribe(ticker1 checkspeed)55 else if (cfg[foglightauto] = yes ampamp stateticker) 56 PubSubunsubscribe(stateticker)57 stateticker = false58 59 60

61 EGPIO port control62 function toggle(onoff)

(continues on next page)

346 Chapter 34 Scripting

Open Vehicles

(continued from previous page)

63 if (stateport = onoff) 64 OvmsCommandExec(egpio output + cfg[foglightport] + + onoff)65 stateport = onoff66 OvmsCommandExec(event raise usrfoglight + (onoff on off))67 68 69

70 Check speed71 function checkspeed() 72 if (stateon)73 return74 var speed = OvmsMetricsAsFloat(vpspeed)75 if (speed lt= cfg[foglightspeedon])76 toggle(1)77 else if (speed gt= cfg[foglightspeedoff])78 toggle(0)79 80

81 API method foglightset(onoff)82 exportsset = function(onoff) 83 if (onoff) 84 stateon = 185 if (cfg[foglightauto] == yes) 86 checkspeed()87 print(Foglight AUTO moden)88 else 89 toggle(1)90 print(Foglight ONn)91 92 else 93 stateon = 094 toggle(0)95 print(Foglight OFFn)96 97 98

99 API method foglightinfo()100 exportsinfo = function() 101 JSONprint( cfg cfg state state )102 103

104 Init105 readconfig()106 PubSubsubscribe(configchanged readconfig)107 PubSubsubscribe(vehicleoff function() exportsset(0) )

3419 Web Plugin

foglighthtm (hint right click save as)

1 lt--2 foglighthtm Web plugin for hook dashboardbodypre3 - add button to activatedeactivate foglight4 - add indicator to show current foglight state5

(continues on next page)

341 Example Foglight 347

Open Vehicles

(continued from previous page)

6 Requires module plugin foglightjs7

8 Version 10 Michael Balzer ltdexterdexters-webdegt9 --gt

10

11 ltstylegt12 foglight 13 margin 10px 8px 014 15 foglight indicator gt label 16 font-size 13017 line-height 16018 margin 0px19 padding 10px20 display block21 border-radius 50px22 23 ltstylegt24

25 ltdiv class=receiver id=foglight style=displaynonegt26 ltformgt27 ltdiv class=form-groupgt28 ltdiv class=col-xs-6gt29 ltdiv class=indicator indicator-foglightgt30 ltspan class=label label-defaultgtFOGLIGHTltspangt31 ltdivgt32 ltdivgt33 ltdiv class=col-xs-6gt34 ltdiv class=btn-group btn-group-justified action-foglight-set data-toggle=

rarr˓buttonsgt35 ltlabel class=btn btn-default action-foglight-0gtltinput type=radio name=

rarr˓foglight value=0gtOFFltlabelgt36 ltlabel class=btn btn-default action-foglight-1gtltinput type=radio name=

rarr˓foglight value=1gtONAUTOltlabelgt37 ltdivgt38 ltsamp id=action-foglight-output class=text-centergtltsampgt39 ltdivgt40 ltdivgt41 ltformgt42 ltdivgt43

44 ltscriptgt45 (function()46

47 var foglight = cfg state on 0 port 0 48 var $indicator = $(foglight indicator-foglight gt label)49 var $actionset = $(foglight action-foglight-set gt label)50

51 State amp UI update52 function update(data) 53 $extend(true foglight data)54 update indicator55 if (foglightstateport)56 $indicatorremoveClass(label-default)addClass(label-danger)57 else58 $indicatorremoveClass(label-danger)addClass(label-default)59 update buttons

(continues on next page)

348 Chapter 34 Scripting

Open Vehicles

(continued from previous page)

60 $actionsetremoveClass(active)61 $actionsetfind(input[value=+foglightstateon+])prop(checked true)

rarr˓parent()addClass(active)62 63

64 Listen to foglight events65 $(foglight)on(msgevent function(e event) 66 if (event == usrfoglighton)67 update( state port 1 )68 else if (event == usrfoglightoff)69 update( state port 0 )70 else if (event == vehicleoff) 71 update( state on 0 )72 $(action-foglight-output)empty()73 74 )75

76 Button action77 $(foglight action-foglight-set input)on(change function(e) 78 foglightstateon = $(this)val()79 loadcmd(script eval foglightset(+foglightstateon+) action-foglight-

rarr˓output)80 )81

82 Init amp install83 $(main)one(load function(ev) 84 loadcmd(script eval foglightinfo())then(function(output) 85 update(JSONparse(output))86 $(foglight)appendTo(panel-dashboard panel-body)show()87 )88 )89

90 )()91 ltscriptgt

341 Example Foglight 349

Open Vehicles

350 Chapter 34 Scripting

CHAPTER 35

CANopen

351 CANopen Basics

3511 Communication Objects

A CANopen network consists of ldquomastersrdquo and ldquoslavesrdquo masters are clients slaves are servers At most one mastermay be active at a time

CANopen supports addressing of up to 127 slaves on a bus using node IDs 1-127 Node address 0 is used for broadcaststo all nodes Node addressing is simply mapped onto CAN IDs by adding the node id to a base ID

The CANopen protocol mainly consists of

bull PDO (process data objects)

bull SDO (service data objects)

bull NMT (network management)

bull SYNC (synchronisation)

bull EMCY (emergency events)

PDO are regular normally periodical status update frames for example sensor data You can log them using theCAN monitor (can log start monitor ) PDOs can be sent at any CAN ID except those reserved forother CANopen services

SDO are memory registers of nodes that can be read and written by masters on request SDO requests are normally sentat ID 0x600 + nodeid responses at ID 0x580 + nodeid SDOs are addressed by a 16 bit index + 8 bit subindex Reg-isters and data types for a given device are documented by the device specific object dictionary normally representedas an EDS (electronic data sheet) file

NMT are short datagrams to control node startup shutdown Therersquos a special node state ldquopre-operationalrdquo allowingaccess to all operation and communication parameters of a node in a standardized way NMT requests are sent at ID0x000 responses and unsolicited updates (aka heartbeats) are sent at ID 0x700 + nodeid with length 1

SYNC messages are datagrams of length 0 normally sent at ID 0x080

351

Open Vehicles

EMCY messages are sent if a node encounters some kind of alert or warning condition they are normally sent at ID0x080 + nodeid with a length of 8 bytes

CAN IDs Communication objects0x000 NMT requests0x080 SYNC0x081 - 0x0FF EMCY0x581 - 0x5FF SDO responses0x601 - 0x67F SDO requests0x701 - 0x77F NMT responses heartbeats

So if any of these IDs look familiar to you chances are yoursquove got a CANopen network

Note CANopen coexists nicely with OBD-II and often does in a vehicle (ie Renault Twizy) OBD-II devicesnormally are addressed at IDs gt 0x780 so are outside the CANopen ID range Even if they use non-standard IDs thedevices normally will detect and ignore frames not matching their protocol

3512 SDO Addresses

The SDO address space layout is standardized

Index (hex) Object0000 not used0001-001F Static Data Types0020-003F Complex Data Types0040-005F Manufacturer Specific Complex Data Types0060-007F Device Profile Specific Static Data Types0080-009F Device Profile Specific Complex Data Types00A0-0FFF Reserved for further use1000-1FFF Communication Profile Area2000-5FFF Manufacturer Specific Profile Area6000-9FFF Standardised Device Profile AreaA000-BFFF Standardised Interface Profile AreaC000-FFFF Reserved for further use

See CiA DS301 for details on standard SDOs

For example a device shall tell about the PDOs it transmits or listens to their IDs update frequency and contentstructure at SDO registers 1400-1BFF This is mandatory in theory but real devices may not fully comply to that rule

CANopen compliant standard device types like motor controllers need to implement some standard profile registersSee CiA DS401 for the generic IO device class definition and CiA DS402 for motor controllers

Most devices will require some kind of login before allowing you to change operational parameters This is also doneusing SDO writes but there is no standard for this so yoursquoll need to dig into the device documentation

Of course therersquos a lot more on CANopen but this should get you going

3513 CAN in Automation

More info on the standard and specific device profiles can be found on the CiA website

352 Chapter 35 CANopen

Open Vehicles

httpswwwcan-ciaorg

CAN in Automation (CiA) is the international usersrsquo and manufacturersrsquo group for the CAN network (Controller AreaNetwork) internationally standardized in the ISO 11898 series The nonprofit association was established in 1992The aim is to provide an unbiased platform for future developments of the CAN protocol and to promote the image ofthe CAN technology

352 How to detect and identify CANopen nodes

So yoursquove got a CAN bus with some devices but you donrsquot know which of them speaks ldquoCANopenrdquo if any TheOVMS v3 will help you to detect them and open their CANs )

3521 Before you begin

you need to activate the CAN bus(es) yoursquore going to use As a CANopen master needs to write to the networkyou need to start the interfaces in active mode ie

OVMS can can1 start active 500000OVMS can can2 start active 125000

and then start the CANopen master for the bus(es) ie

OVMS copen can1 startOVMS copen can2 start

3522 Detecting CANopen nodes

The ldquoopenrdquo in ldquoCANopenrdquo means any implementation can decide how much of the standard it implements There aresome few mandatory features though a CANopen slave has to implement if it wants to comply with the standard

The mandatory features helping to detect and identify CANopen nodes on a CAN bus are

bull NMT (network management) especially RESET and PREOP

bull NMT bootup event messages

bull Standard SDO access in pre-operational mode

If yoursquove got CANopen nodes on a bus even silent ones issuing copen nmt reset will tell all of them toreboot and as bootup messages are mandatory you will see them in the OVMS log output like this

I (162904) canopen can1 node 1 new state Booting

The OVMS CANopen master continously monitors the network for NMT and EMCY messages After bootup of allnodes you can get a list of all nodes that have been detected by issuing metrics list co

OVMS metrics list cococan1nd1emcycodecocan1nd1emcytypecocan1nd1state Operational

Note if you request a reset nodes may decide to boot into pre-operational state That may produce some errormessages Donrsquot worry you can resolve this anytime by issuing copen nmt start

352 How to detect and identify CANopen nodes 353

Open Vehicles

3523 Identifying CANopen nodes

In pre-operational state a CANopen node must be accessible at the CANopen default IDs That means if the nodesupports SDO access we can query some standard attributes from it

Thatrsquos what copen info and copen scan do

bull copen info queries the standard device attributes from a specific node

bull copen scan queries all 127 node IDs

Caution There may be non-CANopen devices on the bus producing regular data frames at CANopen responseIDs andor reading and possibly misinterpreting CANopen requests sent to node IDs not planned by the manufac-turer Chances are low this triggers problems but you should be ready to switch off the vehicle when doing a scanndash just in case

A complete scan takes about 20 seconds A typical scan could look like this

OVMS level debug canopenOVMS copen can1 scanScan 1-127Node 1

Device type 0x00000000Error state 0x00Vendor ID 0x0000001eProduct 0x0712302dRevision 0x00010019SN 0x47c5Device name Gen4 (Renault Twizy)11 November 2011 12HW version 0x00000003SW version 07120001

Node 23 SDO access failedNode 25 SDO access failedNode 27 SDO access failedNode 30 SDO access failedNode 87 SDO access failedDoneD (227994) canopen ReadSDO 23 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (228194) canopen ReadSDO 25 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (228444) canopen ReadSDO 27 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (228844) canopen ReadSDO 30 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (238384) canopen ReadSDO 87 0x100000 InitUpload failed CANopen error coderarr˓0xffffffff

This means one CANopen node was found and some non-CANopen frames were received on IDs 0x580 +23 +25+27 +30 and +87

3524 Great What now

As you now know therersquos a CANopen node you can look for documentation on it You can also try to access moredefault SDOs to see if you can control and configure the node

354 Chapter 35 CANopen

Open Vehicles

bull If yoursquore lucky the device will provide its own EDS file at SDO 102100 You can check that by issuing

OVMS copen ltbusgt readsdo ltnodeidgt 1021 0

bull Check out the CiA specifications for CANopen standards for example

ndash DS301 for details on general standard SDOs

ndash DS401 for the generic IO device class definition

ndash DS402 for motor controller SDOs

bull Look up the manufacturer of your device by itrsquos vendor ID

httpswwwcan-ciaorgservicescanopen-vendor-id

bull Contact the manufacturer of your device for specific documentation and EDS files

353 CANopen Shell Commands

Show status report

copen status

Start stop workers

copen ltbusgt startcopen ltbusgt stop

bull stop will fail if clients are still running

Send NMT commands

copen ltbusgt nmt ltstart|stop|preop|reset|commresetgt [id=0] [timeout_ms=0]

bull id 0 = broadcast

bull timeout gt 0 wait for state change (heartbeat) 3 tries Note state change response is not a mandatoryCANopen feature

Read SDO

copen ltbusgt readsdo ltidgt ltindex_hexgt ltsubindex_hexgt [timeout_ms=50]

bull index amp subindex hexadecimal without ldquo0xrdquo or ldquohrdquo

bull defaults to 3 tries on timeout

Write SDO

copen ltbusgt writesdo ltidgt ltindex_hexgt ltsubindex_hexgt ltvaluegt [timeout_ms=50]

bull index amp subindex hexadecimal without ldquo0xrdquo or ldquohrdquo

bull value prefix ldquo0xrdquo = hex else decimal string if no decimal

bull defaults to 3 tries on timeout

Show node core attributes

353 CANopen Shell Commands 355

Open Vehicles

copen ltbusgt info ltidgt [timeout_ms=50]

bull prints device type error register device name etc

bull Note some attributes read are optional and may be emptyzero

Scan bus for nodes

copen ltbusgt scan [[startid=1][-][endid=127]] [timeout_ms=50]

bull loops ldquoinfordquo over multiple node ids (default all)

bull Note a full scan with default timeout takes ~20 seconds

354 CANopen API Usage

3541 Synchronous API

The synchronous use is very simple all you need is a CANopenClient instance

On creation the client automatically connects to the active CANopen worker or starts a new worker instance if neces-sary

The CANopenClient methods will block until the job is done (or has failed) Job results andor error details arereturned in the caller provided job

Caution Do not make synchronous calls from code that may run in a restricted context eg within a metricupdate handler Avoid using synchronous calls from time critical code eg a CAN or event handler

Example

include canopenh

find CAN interfacecanbus bus = (canbus) MyPcpAppFindDeviceByName(can1) or simply use m_can1 if youre a vehicle subclass

create CANopen clientCANopenClient client(bus)

a CANopen job holds request and response dataCANopenJob job

read value from node 1 SDO 0x100800uint32_t valueif (clientReadSDO(ampjob 1 0x1008 0x00 (uint8_t)ampvalue sizeof(value)) == COR_OK) read result is now in value

start node 2 wait for presenceif (clientSendNMT(ampjob 2 CONC_Start true) == COR_OK)

node 2 is now started

(continues on next page)

356 Chapter 35 CANopen

Open Vehicles

(continued from previous page)

write value into node 3 SDO 0x234518if (clientWriteSDO(ampjob 3 0x2345 0x18 (uint8_t)ampvalue 0) == COR_OK)

value has now been written into register 0x234518

Main API methods

SendNMT send NMT request and optionally wait for NMT state change

aka heartbeat message

Note NMT responses are not a part of the CANopen NMT protocol and

sending heartbeat NMT state updates is optional for CANopen nodes

If the node sends no state info waiting for it will result in timeout

even though the state has in fact changed -- theres no way to know

if the node doesnt tell

CANopenResult_t SendNMT(CANopenJobamp job

uint8_t nodeid CANopenNMTCommand_t commandbool wait_for_state=false int resp_timeout_ms=1000 int max_tries=3)

ReceiveHB wait for next heartbeat message of a node

return state received

Use this to read the current state or synchronize to the heartbeat

Note heartbeats are optional in CANopen

CANopenResult_t ReceiveHB(CANopenJobamp job

uint8_t nodeid CANopenNMTState_t statebuf=NULLint recv_timeout_ms=1000 int max_tries=1)

ReadSDO read bytes from SDO server into buffer

- reads data into buf (up to bufsize bytes)

- returns data length read in jobsdoxfersize

- and data length available in jobsdocontsize (if known)

- remaining buffer space will be zeroed

- on result COR_ERR_BufferTooSmall the buffer has been filled up to bufsize

- on abort the CANopen error code can be retrieved from jobsdoerror

Note result interpretation is up to caller (check device object dictionary

for data types amp sizes) As CANopen is little endian as ESP32 we dont

need to check lengths on numerical results ie anything from int8_t to

uint32_t can simply be read into a uint32_t buffer

CANopenResult_t ReadSDO(CANopenJobamp job

uint8_t nodeid uint16_t index uint8_t subindex uint8_t buf size_t bufsizeint resp_timeout_ms=50 int max_tries=3)

WriteSDO write bytes from buffer into SDO server

- sends bufsize bytes from buf

- or 4 bytes from buf if bufsize is 0 (use for integer SDOs of unknown type)(continues on next page)

354 CANopen API Usage 357

Open Vehicles

(continued from previous page)

- returns data length sent in jobsdoxfersize

- on abort the CANopen error code can be retrieved from jobsdoerror

Note the caller needs to know data type amp size of the SDO register (check

device object dictionary) As CANopen servers normally are intelligent

anything from int8_t to uint32_t can simply be sent as a uint32_t with

bufsize=0 the server will know how to convert it

CANopenResult_t WriteSDO(CANopenJobamp job

uint8_t nodeid uint16_t index uint8_t subindex uint8_t buf size_t bufsizeint resp_timeout_ms=50 int max_tries=3)

If you want to create custom jobs use the low level method ExecuteJob() to execute them

3542 Asynchronous API

The CANopenAsyncClient class provides the asynchronous interface and the response queue

To use the asynchronous API you need to handle asynchronous responses which normally means adding a dedicatedtask for this A minimal handling would be to simply discard the responses (just empty the queue) if you donrsquot needto care about the results

Example

Instantiate the async client for a CAN bus and a queue size like this

CANopenAsyncClient m_async(m_can1 50)

Example response handler task

void MyAsyncTask()

CANopenJob jobwhile (true) if (m_asyncReceiveDone(job portMAX_DELAY) = COR_ERR_QueueEmpty)

process job results

Sending requests is following the same scheme as with the synchronous API Standard result code is COR_WAIT anerror may occur if the queue is full

if (m_asyncWriteSDO(m_nodeid index subindex (uint8_t)value 0) = COR_WAIT) handle error

Main API methods

The API methods are similar to the synchronous methods (see above)

358 Chapter 35 CANopen

Open Vehicles

CANopenResult_t SendNMT(uint8_t nodeid CANopenNMTCommand_t commandbool wait_for_state=false int resp_timeout_ms=1000 int max_tries=3)

CANopenResult_t ReceiveHB(uint8_t nodeid CANopenNMTState_t statebuf=NULLint recv_timeout_ms=1000 int max_tries=1)

CANopenResult_t ReadSDO(uint8_t nodeid uint16_t index uint8_t subindexuint8_t buf size_t bufsizeint resp_timeout_ms=100 int max_tries=3)

CANopenResult_t WriteSDO(uint8_t nodeid uint16_t index uint8_t subindexuint8_t buf size_t bufsizeint resp_timeout_ms=100 int max_tries=3)

CANopenJob objects are created automatically by these methods Jobs done need to be fetched by loopingReceiveDone() until it returns COR_ERR_QueueEmpty

If you want to create custom jobs use the low level method SubmitJob() to add them to the worker queue

3543 Error Handling

If an error occurs it will be given as a CANopenResult_t other than COR_OK or COR_WAIT either by a methodresult or by the CANopenJobresult field

Result codes are

COR_OK = 0

API levelCOR_WAIT job waiting to be processedCOR_ERR_UnknownJobTypeCOR_ERR_QueueFullCOR_ERR_QueueEmptyCOR_ERR_NoCANWriteCOR_ERR_ParamRangeCOR_ERR_BufferTooSmall

Protocol levelCOR_ERR_TimeoutCOR_ERR_SDO_AccessCOR_ERR_SDO_SegMismatch

General purpose application levelCOR_ERR_DeviceOffline = 0x80COR_ERR_UnknownDeviceCOR_ERR_LoginFailedCOR_ERR_StateChangeFailed

Additionally if an SDO readwrite error occurs an abortion error code may be given by the slave These codes followthe CANopen standard and may be extended by device specific codes

To translate a CANopenResult_t andor a known SDO abort code into a string use the CANopen class utilitymethods

stdstring GetAbortCodeName(const uint32_t abortcode)stdstring GetResultString(const CANopenResult_t result)

(continues on next page)

354 CANopen API Usage 359

Open Vehicles

(continued from previous page)

stdstring GetResultString(const CANopenResult_t result const uint32_t abortcode)stdstring GetResultString(const CANopenJobamp job)

Example

if (jobresult = COR_OK) ESP_LOGE(TAG Result for s sCANopenGetJobName(job)c_str()CANopenGetResultString(job)c_str())

3544 Custom Address Schemes

The standard clients use the CiA DS301 default IDs for node addressing ie

NMT request rarr 0x000NMT response rarr 0x700 + nodeidSDO request rarr 0x600 + nodeidSDO response rarr 0x580 + nodeid

If you need another address scheme create a sub class of CANopenAsyncClient or CANopenClient and over-ride the Init() methods as necessary

3545 More Code Examples

bull See shell commands in canopen_shellcpp

bull See classes SevconClient and SevconJob in the Twizy SEVCON module

360 Chapter 35 CANopen

CHAPTER 36

OVMS Server

361 Welcome

The OVMS (Open Vehicle Monitoring System) team is a group of enthusiasts who are developing a means to remotelycommunicate with our cars and are having fun while doing it

The OVMS module is a low-cost hardware device that you install in your car simply by installing a SIM card con-necting the module to your carrsquos Diagnostic port connector and positioning a cellular antenna Once connected theOVMS module enables remote control and monitoring of your car

This guide documents the installation and operation of an OVMS server

You should however start by asking yourself the question lsquodo I need thisrsquo You donrsquot need to run your own OVMSserver as you can just use one of the public Open Vehicles OVMS servers The choice is yours

362 Installation

3621 Prerequisites

Yoursquoll need a Linux OSX BSD or other flavour of Unix server with a public IP address and a shell account able tosetup a daemon listening on a port Yoursquoll need a modern version of perl running on that server and a bunch of perlmodules (from cpan)

Yoursquoll need a MYSQL server running on the same machine or another machine and credentials to be able to create adatabase and accounts

This could possibly run on a windows server but you are on your own -) [ let us know instructions if you manage toget it running ]

3622 Clone from GitHub

Start the installation with a clone from GitHub

361

Open Vehicles

git clone httpsgithubcomopenvehiclesOpen-Vehicle-Servergit

You can then change into the v3server directory and start the installation process

3623 Perl Module Installation

You will need at a minimum the following modules from CPAN (or from your distributionrsquos package manager)

bull ConfigIniFiles

bull DigestMD5

bull DigestHMAC

bull CryptRC4XS

bull MIMEBase64

bull DBI

bull DBDmysql

bull EV

bull AnyEvent

bull AnyEventHTTP

bull AnyEventHTTPD

bull HTTPParserXS

bull DataUUID

bull EmailMIME

bull EmailSenderSimple

bull NetSSLeay

bull JSONXS

bull ProtocolWebSocket

bull TimePiece

3624 MySQL Setup

Create a mysql database ldquoopenvehiclesrdquo and use the ovms_serversql script to create the necessary ovms_ tablesCreate a mysql username and password with access to the database

Insert a record into the ovms_cars table to give you access to your own car

vehicleid DEMOowner 1carpass DEMOuserpass DEMOcryptscheme 0v_ptokenv_lastupdate 0000-00-00 000000

362 Chapter 36 OVMS Server

Open Vehicles

Obviously change the vehicleid carpass and userpass as necessary The only required fields are vehicleid and carpass

If you are upgrading from server v2 to v3 you can instead source the ovms_server_v2_to_v3sql code to migrate yourdatabase schema

3625 OVMS Server Configuration

Copy confovms_serverconfdefault to confovms_serverconf to provide a template for your configuration Thenmodify the configuration as appropriate

3626 OVMS Server Access to MySQL

In the configovms_serverconf file define the access to the mysql database

[db]path=DBImysqldatabase=openvehicleshost=127001user=ltmysqlusernamegtpass=ltmysqlpasswordgt

If the host is remote change the host= parameter to be the remote IP address Use 127001 for local

Test the connection with

$ mysql -h 127001 -u ltmysqlusernamegt -pEnter password ltmysqlpasswordgtWelcome to the MySQL monitor Commands end with or g

If you get ldquoERROR 1044 (42000) Access deniedrdquo fix it before proceeding The most likely cause is a mistake inyour mysql user grant rights

3627 Enable SSL (optional)

If you want to support SSL connections to your server (port 6869 for the REST API port 6870 for OVMS MP) youneed to supply a certificate You can create a self-signed certificate or get a certificate signed by some root CA foryour server

In both cases you need to merge the private key PEM and the chain PEM into the file ldquoovms_serverpemrdquo located inthe same directory as the ldquoovms_serverplrdquo Also take care to secure the file as it now contains your private key

To create a self-signed certificate do

$ openssl req -sha256 -newkey rsa4096 -nodes -keyout privkeypem -x509 -days 365 -rarr˓out fullchainpem$ cat privkeypem fullchainpem gtconfovms_serverpem$ chmod 0600 confovms_serverpem

Or if you want to reuse eg your Letrsquos Encrypt server certificate do this as root

cat etcletsencryptliveyourhostprivkeypem etcletsencryptliveyourhostrarr˓fullchainpem gtconfovms_serverpem chmod 0600 confvms_serverpem chown youruid confovms_serverpem

and add a cron job or certbot hook to check for renewals and redo these steps as necessary

362 Installation 363

Open Vehicles

3628 Configure the Plugins

The OVMS Server v3 is based on a pluggable architecture The plugins themselves are stored in pluginssystem andpluginslocal directories You must configure (in confovms_serverconf) the plugins that you require

We recommend the following

[plugins]load=ltltEOTVECEDbDBIAuthDrupalApiV2PushPushAPNSPushGCMPushMAILApiHttpApiHttpCoreApiHttpMqapiEOT

3629 Run The Server

You can run the server manually with

$ ovms_serverpl

If your linux host is running systemd you can also look at supportovms_serverservice and supportovmslogrotate asexamples for how you can run this as a background daemon

7 ENJOY

Any questionscomments please let us know

Mark Webb-Johnson March 2020

363 Plugins

3631 ApiHttp

This plugin provides an HTTP (and optional HTTPS) server and is used by subsequent API plugins to provide HTTPservices The HTTP server is on port tcp6868 If you provide a confovms_serverpem file it will also use that tolaunch a HTTPS server on port tcp6869

3632 ApiHttpCore

This plugin provides support for the HTTP API in OVMS Server v3 It supports the api HTTP endpoint

If you want to use this plugin you need to also include lsquoApiHttprsquo before loading this

364 Chapter 36 OVMS Server

Open Vehicles

3633 ApiHttpFile

This plugin provides support serving static files from the httpfiles directory It supports the file HTTP endpoint

If you want to use this plugin you need to also include lsquoApiHttprsquo before loading this

3634 ApiHttpMqapi

This plugin provides support for Mosquitto API functions for authentication and ACL access control It supports themqapi HTTP endpoint

If you want to use this plugin you need to also include lsquoApiHttprsquo before loading this

You will also need to configure your mosquittoconf to include

auth_opt_superusers ltyour-superuser-usernamegtauth_opt_acl_cacheseconds 300auth_opt_auth_cacheseconds 300auth_opt_backends httpauth_opt_http_ip 127001auth_opt_http_port 6868auth_opt_http_getuser_uri mqapiauthauth_opt_http_superuser_uri mqapisuperuserauth_opt_http_aclcheck_uri mqapiacl

3635 ApiV2

This plugin provides support for the v2 OVMS protocol including crypto protocols 0x30 and 0x31 It provides a rawv2 protocol server on tcp6867 If you provide a confovms_serverpem file it will also launch an SSL enabled v2protocol server on tcp6870

3636 AuthDrupal

This plugin provides support for authentication via the Drupal database It also provides a facility to periodicallysynchronise drupal users to OVMS owner table records

Note that only one Auth plugin should be enabled

3637 AuthNone

This is a stub authentication plugin It will always fail authentication and is only provided as an example (or for usein systems where user authentication is not required)

Note that only one Auth plugin should be enabled

3638 DbDBI

This is the core database plugin for perl DBI style SQL databases It is used for example to provide access to MySQLdatabases

363 Plugins 365

Open Vehicles

3639 Push

This provides the core support for Push Notifications The actual notifications themselves are issued by sub-pluginswhich register with this

36310 PushAPNS

This plugin supports the lsquoapnsrsquo notification type for push notifications to Apple devices (iPhones iPadsetc) It requires apple certificates in PEM format to be placed in confovms_apns_sandboxpem andconfovms_apns_productionpem

36311 PushGCM

This plugin supports the lsquogcmrsquo notification type for push notifications to Android devices It requires a google APIkey to be placed in the confovms_serverconf file under [gcm] section parameter lsquoapikeyrsquo You can obtain that keyby

Log in to your Google account Open httpsdevelopersgooglecommobileadd Select platform ldquoAndroidrdquo Enter an arbitrary project name eg ldquoMyOvmsServerrdquo Package name should be ldquocomopenvehiclesOVMSrdquo Activate ldquoCloud Messagingrdquo and generate the key Note the API key and project number (= GCM sender ID)

36312 PushMAIL

This plugin supports the lsquomailrsquo notification type for push notifications by eMail It simply requires a sendmail stylemailer installed on the server

You can configure confovms_serverconf [mail] section parameter lsquosenderrsquo as the sender address to be used (otherwisedefaulting to lsquonotificationsopenvehiclescomrsquo

36313 VECE

This plugin extends the notification system to translate error codes into textual error messgaes It uses files in the vecedirectory named ltvehicletypegtvece (for example trvece vavece etc)

The vece files themselves are ini style files

366 Chapter 36 OVMS Server

CHAPTER 37

OVMS Protocol v2

371 Welcome

The OVMS (Open Vehicle Monitoring System) team is a group of enthusiasts who are developing a means to remotelycommunicate with our cars and are having fun while doing it

The OVMS module is a low-cost hardware device that you install in your car simply by installing a SIM card con-necting the module to your carrsquos Diagnostic port connector and positioning a cellular antenna Once connected theOVMS module enables remote control and monitoring of your car

This developerrsquos guide documents version 2 of the OVMS protocol

372 Terms

Server The OVMS server

Car The OVMS car module

App An OVMS client application one of

bull Active client interactive user applications ie mobile App (Note the car module will raise the updatefrequency when active clients are connected)

bull Batch client a non-interactive application ie shell script

373 Startup

On startup there is no bannerwelcome message from the server The caller initiates the protocol by sending a welcomemessage to the server

1 For cars

MP-C ltprotection schemegt lttokengt ltdigestgt ltcar idgt

367

Open Vehicles

2 For interactive user apps

MP-A ltprotection schemegt lttokengt ltdigestgt ltcar idgt

3 For noninteractive batch apps

MP-B ltprotection schemegt lttokengt ltdigestgt ltcar idgt

4 For servers

MP-S ltprotection schemegt lttokengt ltdigestgt ltcar idgt

The server responds with a welcome message to the caller

MP-S ltprotection schemegt lttokengt ltdigestgt

374 Encryption Scheme 0x30

This scheme is based on using shared secrets hmac digest for authentication and encryption key negotiation withRC4 stream cipher and base64 encoding

Upon startup both the server and callers generate random tokens (encoded as textual characters) Each party thenhmac-md5s the token with the shared secret to create a digest base64 encoded

Note that the server will only issue itrsquos welcome message after receiving and validating the callerrsquos welcome message

Validation of the welcome message is performed by

1 Checking the received token to ensure that it is different from its own token and aborting the connection if thesame

2 Hmac-md5s the received token with the shared secret and comparing the result to the received digest

3 If the digest match then the partner had authenticated itself (proven it knows the shared secret or has listenedto a previous conversation)

4 If the digests donrsquot match then abort the connection as the partner doesnrsquot agree with the shared secret

Once the partner has been authenticated

1 Create a new hmac-md5 based on the client and server tokens concatenated with the shared secret

2 Use the new hmac digest as the key for symmetric rc4 encryption

3 Generate and discard 1024 bytes of cipher text

From this point on messages are rc4 encrypted and base64 encoded before transmission Lines are terminated withCR+LF

375 Encryption Scheme 0x31

This scheme is based on server authentication and is supported in OVMS server v3 and later Typically serversprovide two methods of authentication

bull Username + Password The usual username and associated password as used when registering on the server

bull Username + ApiToken An API token based authentication scheme where each user may maintain one or moreaccess tokens (which can be created or revoked at will)

The arguments to the MP- startup command are

bull ltprotection schemegt Must be set to lsquo1rsquo (0x31)

368 Chapter 37 OVMS Protocol v2

Open Vehicles

bull lttokengt Must be the username pre-registered with the server

bull ltdigestgt Must be the password or api token for that user

bull ltcar idgt Must be the vehicle ID to connect to or the special value lsquorsquo to request connection to the first vehicleon that userrsquos account

Once the partner has been authenticated a response lsquoMP-S 1 ltusergt ltvehicleidgt ltlist-of-all-other-vehiclesgtrsquo will besent from the server to indicate a successful authentication

From then onwards the messages are in plaintext with no further encryption or encoding Lines are terminated withCR+LF

Note that this scheme is intended to be used with external encryption schemes such as SSLTLS

376 Auto Provisioning

A caller can perform auto-provisioning at any time (authenticated or not) However only one auto-provision can beperformed for each connection

Auto-Provisioning relies on two secrets known both to the server and client The first is usually the VIN of the vehicleand the second is usually the ICCID of the SIM card in the vehicle module The reason these two are chosen is thatthey can be auto-determined by the vehicle module but also clearly seen by the user (for entry into the server)

The mechanism works by the client module first determining its VIN and ICCID secrets then connecting to the serverand sending a AP-C message to the server proving its VIN The server will then lookup the auto-provisioning recordand reply with that to the client (via a AP-S or AP-X message)

The auto-provisioning record itself is platform dependent but will typically be an ordered space separated list ofparameter values For OVMS hardware and OVMSX PIC firmware these are merely parameters 0 1 2 etc tobe stored in the car module

3761 Auto Provisioning Protection Scheme 0x30

1 For cars

AP-C ltprotection schemegt ltapkeygt

2 For servers

AP-S ltprotection schemegt ltserver tokengt ltserver digestgt ltprovisioninggt

AP-X

When the provisioning record is created at the server a random token is generated (encoded as textual characters) Theserver then hmac-md5s this token with the shared secret (usually the ICCID known by the server) to create a digestbase64 encoded Using this hmac digest the server generates and discards 1024 bytes of cipher text The serverthen rc4 encrypts and base64 encodes the provisioning information and stores its token digest and encoded provisionrecord ready for the client to request

The car knows its VIN and ICCID With this information it makes a connection to the OVMS service on the serverand provides the VIN as the ltapkeygt in a AP-C message to the server

The server will ensure that it only responds to one AP-C message for any one connection Once responded allsubsequent AP-C requests will always be replied with a AP-X message

Upon receiving the AP-C message the server looks up any provisioning records it has for the given ltapkeygt If it hasnone it replies with an AP-X message

376 Auto Provisioning 369

Open Vehicles

If the server does find a matching provisioning record it replies with an AP-S message sending the previously savedserver token digest and encoded provisioning record to the car

If the car receives an AP-X message it knows that auto-provisioning was not successful

If the car receives an AP-S message it can first validate the server authenticity By producing its own hmac-md5 ofthe server token and secret ICCID the car can validate the server-provided digest is as expected If this validation stepdoes not succeed the car should abort the auto-provisioning

If acceptable the car can decrypt the provisioning record by first generating and discarding 1024 bytes of cipher textthen decoding the provisioning record provided by the server

377 Backwards Compatibility

Typically comma-separated lists are used to transmit parameters Applications Servers and the Car firmware shouldin general ignore extra parameters not expected In this way the protocol messages can be extended by adding extraparameters without breaking old AppsCars that donrsquot expect the new parameters

Similarly unrecognized messages should due ignored Unrecognised commands in the ldquoCrdquo (command) messageshould be responded to with a generic ldquounrecognizedrdquo response (in the ldquocrdquo (command response) messages)

378 Messages

3781 Car lt-gt Server lt-gt App

After discarding CR+LF line termination and base64 decoding the following protocol messages are defined

ltmessagegt = ltmagicgt ltversiongt ltspacegt ltprotmsggt

ltmagicgt = MP-

ltversiongt = 1 byte version number - this protocol is 0x30

ltspacegt = lsquo lsquo (ascii 0x20)

ltprotmsggt = ltservertocargt | ltcartoservergt | ltservertoappgt | ltapptoservergt

ltservertocargt - ldquoSrdquo ltpayloadgt

ltcartoservergt = ldquoCrdquo ltpayloadgt

ltservertoappgt = ldquosrdquo ltpayloadgt

ltapptoservergt = ldquocrdquo ltpayloadgt

ltpayloadgt = ltcodegt ltdatagt

ltcodegt = 1 byte instruction code

ltdatagt = N bytes data (dependent on instruction code)

3782 Ping message 0x41 ldquoArdquo

This message may be sent by any party to test the link The expected response is a 0x61 ping acknowledgementThere is no expected payload to this message an any given can be discarded

370 Chapter 37 OVMS Protocol v2

Open Vehicles

3783 Ping Acknowledgement message 0x61 ldquoardquo

This message is sent in response to a 0x41 ping message There is no expected payload to this message an any givencan be discarded

3784 Command message 0x43 ldquoCrdquo

This message is sent ltapptoservergt then ltservertocargt and carries a command to be executed on the car The messagewould normally be paranoid-encrypted

ltdatagt is a comma-separated list of

bull command (a command code 065535)

bull parameters (dependent on the command code)

For further information on command codes and parameters see the command section below

3785 Command response 0x63 ldquocrdquo

This message is sent ltcartoservergt then ltservertoappgt and carries the response to a command executed on the carThe message would normally be paranoid-encrypted

ltdatagt is a comma-separated list of

bull command (a command code 065535)

bull result (0=ok 1=failed 2=unsupported 3=unimplemented)

bull parameters (dependent on the command code and result)

For result=0 the parameters depend on the command being responded to (see the command section below for furtherinformation)

For result=1 the parameter is a textual string describing the fault

For result=2 or 3 the parameter is not used

3786 Car Environment message 0x44 ldquoDrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the environment settings of the vehicle

ltdatagt is comma-separated list of

Door state 1

bull bit0 = Left Door (open=1closed=0)

bull bit1 = Right Door (open=1closed=0)

bull bit2 = Charge port (open=1closed=0)

bull bit3 = Pilot present (true=1false=0) (always 1 on my 25)

bull bit4 = Charging (true=1false=0)

bull bit5 = always 1

bull bit6 = Hand brake applied (true=1false=0)

bull bit7 = Car ON (ldquoignitionrdquo) (true=1false=0)

378 Messages 371

Open Vehicles

Door state 2

bull bit3 = Car Locked (locked=1unlocked=0)

bull bit4 = Valet Mode (active=1inactive=0)

bull bit6 = Bonnet (open=1closed=0)

bull bit7 = Trunk (open=1closed=0)

LockUnlock state

bull 4 = car is locked

bull 5 = car is unlocked

Temperature of the PEM (celcius)

Temperature of the Motor (celcius)

Temperature of the Battery (celcius)

Car trip meter (in 110th of a distance unit)

Car odometer (in 110th of a distance unit)

Car speed (in distance units per hour)

Car parking timer (0 for not parked or number of seconds car parked for)

Ambient Temperature (in Celcius)

Door state 3

bull bit0 = Car awake (turned on=1 off=0)

bull bit1 = Cooling pump (on=1off=0)

bull bit6 = 1=Logged into motor controller

bull bit7 = 1=Motor controller in configuration mode

Stale PEMMotorBattery temps indicator (-1=none 0=stale gt0 ok)

Stale ambient temp indicator (-1=none 0=stale gt0 ok)

Vehicle 12V line voltage

Door State 4

bull bit2 = alarm sounds (on=1off=0)

Reference voltage for 12v power

Door State 5

bull bit0 = Rear left door (open=1closed=0)

bull bit1 = Rear right door (open=1closed=0)

bull bit2 = Frunk (open=1closed=0)

bull bit4 = 12V battery charging

bull bit5 = Auxiliary 12V systems online

bull bit7 = HVAC running

372 Chapter 37 OVMS Protocol v2

Open Vehicles

Temperature of the Charger (celsius)

Vehicle 12V current (ie DC converter output)

Cabin temperature (celsius)

3787 Paranoid-mode encrypted message 0x45 ldquoErdquo

This message is sent for any of the four message ltprotmsggt types and represents an encrypted transmission that theserver should just relay (or is relaying) without being able to interpret it The encryption is based on a shared secretbetween the car and the apps to which the server is not privy

ltdatagt is

bull ltparanoidtokengt | ltparanoidcodegt

bull ltparanoidtokengt = ldquoTrdquo ltptokengt

bull ltparanoidcodegt = ldquoMrdquo ltcodegt ltdatagt

In the case of ltparanoidtokengt the ltptokengt is a random token that represent the encryption key It can only besent ltcartoservergt or ltservertoappgt Upon receiving this token the server discards all previously stored paranoidmessages sends it on to all connected apps and then stores the token Every time an app connects the server alsosends this token to the app

In the case of ltparanoidcodegt the ltcodegt is a sub-message code and can be any of the codes listed in this document(except for ldquoArdquo ldquoardquo and ldquoErdquo) The ltdatagt is the corresponding encrypted payload message The encryption isperformed on the ltdatagt by

bull Create a new hmac-md5 based on the ltptokengt with the shared secret

bull Use the new hmac digest as the key for symmetric rc4 encryption

bull Generate and discard 1024 bytes of cipher text

and the data is base64 encoded Upon receiving a paranoid message from the car the server forwards it on the allconnected apps and then stores the message Every time an app connects the server sends all such stored messagesUpon receiving a paranoid message from an app if the car is connected the server merely forwards it on to the carotherwise discarding it

3788 Car firmware message 0x46 ldquoFrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the firmware versions of the vehicle

ltdatagt is comma-separated list of

bull OVMS firmware version

bull VIN (vehicle identification number)

bull Current network signal quality (Wifi GSM in SQ units)

bull Write-enabled firmware (0=read-only 1=write-enabled)

bull Vehicle type code (eg TR = Tesla Roadster see command output vehicle list)

bull Current network name (Wifi SSID GSM provider)

bull Distance to next scheduled maintenanceservice [km]

bull Time to next scheduled maintenanceservice [seconds]

bull OVMS hardware version

378 Messages 373

Open Vehicles

3789 Server firmware message 0x66 ldquofrdquo

This message is sent ltservertocargt ldquoSrdquo or ltservertoappgt ldquosrdquo and transmits the firmware versions of the server

ltdatagt is comma-separated list of

bull Server firmware version

37810 Car group subscription message 0x47 ldquoGrdquo

This message is sent ltapptoservergt ldquoArdquo and requests subscription to the specified group

ltdatagt is comma-separated list of

bull Group name

37811 Car group update message 0x67 ldquogrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits a group location message for the vehicle

ltdatagt is comma-separated list of

bull Vehicle ID (only ltservertoappgt not sent ltcartoservergt)

bull Group name

bull Car SOC

bull Car Speed

bull Car direction

bull Car altitude

bull Car GPS lock (0=nogps 1=goodgps)

bull Stale GPS indicator (-1=none 0=stale gt0 ok)

bull Car latitude

bull Car longitude

37812 Historical Data update message 0x48 ldquoHrdquo

This message is sent ltcartoservergt ldquoC and transmits a historical data message for storage on the server

ltdatagt is comma-separated list of

bull type (unique storage class identification type)

bull recordnumber (integer record number)

bull lifetime (in seconds)

bull data (a blob of data to be dealt with as the application requires)

The lifetime is specified in seconds and indicates to the server the minimum time the vehicle expects the server toretain the historical data for Consideration should be made as to server storage and bandwidth requirements

The type is composed of ltvehicletypegt - ltclassgt - ltpropertygt

ltVehicletypegt is the usual vehicle type or lsquorsquo to indicate generic storage suitable for all vehicles

374 Chapter 37 OVMS Protocol v2

Open Vehicles

ltClassgt is one of

bull PWR (power)

bull ENG (engine)

bull TRX (transmission)

bull CHS (chassis)

bull BDY (body)

bull ELC (electrics)

bull SAF (safety)

bull SEC (security)

bull CMF (comfort)

bull ENT (entertainment)

bull COM (communications)

bull X (unclassified and experimental with replaced with 2 digits code)

ltPropertygt is a property code which the vehicle decides

The server will timestamp the incoming historical records and will set an expiry date of timestamp + ltlifetimegtseconds The server will endeavor to retain the records for that time period but may expend data earlier if necessary

37813 Historical Data update+ack message 0x68 ldquohrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltsevertocargt ldquocrdquo and transmitsacknowledges historical data message forstorage on the server

For ltcartoservergt the ltdatagt is comma-separated list of

bull ackcode (an acknowledgement code)

bull timediff (in seconds)

bull type (unique storage class identification type)

bull recordnumber (integer record number)

bull lifetime (in seconds)

bull data (a blob of data to be dealt with as the application requires)

The ackcode is a numeric acknowledgement code - if the server successfully receives the message it will reply withldquohrdquo and this ackcode to acknowledge reception

The timediff is the time difference in seconds to use when storing the record (eg -3600 would indicate the recorddata is from one hour ago)

The lifetime is specified in seconds and indicates to the server the minimum time the vehicle expects the server toretain the historical data for Consideration should be made as to server storage and bandwidth requirements

For ltservertocargt the ltdatagt is

bull ackcode (an acknowledgement code)

The ltcartoservergt message sends the data to the server The ltservertocargt message acknowledges the data

378 Messages 375

Open Vehicles

37814 Push notification message 0x50 ldquoPrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo When used by the car it requests the server to send atextual push notification alert message to all apps registered for this car The ltdatagt is 1 byte alert type followed by Nbytes of textual message The server will use this message to send the notification to any connected apps and can alsosend via external mobile frameworks for unconnected apps

37815 Push notification subscription 0x70 ldquoprdquo

This message is sent ltapptoservergt Ardquo It is used by app to register for push notifications and is normally at the startof a connection The ltdatagt is made up of

ltappidgtltpushtypegtltpushkeytypegtltvehicleidgtltnetpassgtltpushkeyvaluegt

The server will verify the credentials for each vehicle and store the required notification information

Note As of June 2020 only one vehicleid can be subscribed at a time If multiple vehicles are required then theyshould each be subscribed in individual messages

37816 Server -gt Server Record message 0x52 ldquoRrdquo

This message is sent ltservertoservergt ldquoSrdquo and transmits an update to synchronized database table records

Sub-type RV (Vehicle record) ltdatagt is comma-separated list of

bull Vehicleid

bull Owner

bull Carpass

bull v_server

bull deleted

bull changed

Sub-type RO (Owner record) ltdatagt is comma-separated list of

bull Ownerid

bull OwnerName

bull OwnerMail

bull PasswordHash

bull OwnerStatus

bull deleted

bull changed

37817 Server -gt Server Message Replication message 0x72 ldquorrdquo

This message is sent ltservertoservergt ldquoSrdquo and replicates a message for a particular car

ltdatagt is comma-separated list of

bull vehicleid

bull message code

376 Chapter 37 OVMS Protocol v2

Open Vehicles

bull message data

37818 Car state message 0x53 ldquoSrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the last known status of the vehicle

ltdatagt is comma-separated list of

bull SOC

bull Units (ldquoMrdquo for miles ldquoKrdquo for kilometers)

bull Line voltage

bull Charge current (amps)

bull Charge state (charging topoff done prepare heating stopped)

bull Charge mode (standard storage range performance)

bull Ideal range

bull Estimated range

bull Charge limit (amps)

bull Charge duration (minutes)

bull Charger B4 byte (tba)

bull Charge energy consumed (110 kWh)

bull Charge sub-state

bull Charge state (as a number)

bull Charge mode (as a number)

bull Charge Timer mode (0=onplugin 1=timer)

bull Charge Timer start time

bull Charge timer stale (-1=none 0=stale gt0 ok)

bull Vehicle CAC100 value (calculated amp hour capacity in Ah)

bull ACC Mins remaining until car will be full

bull ACC Mins remaining until car reaches charge limit

bull ACC Configured range limit

bull ACC Configured SOC limit

bull Cooldown Car is cooling down (0=no 1=yes)

bull Cooldown Lower limit for battery temperature

bull Cooldown Time limit (minutes) for cooldown

bull ACC charge time estimation for current charger capabilities (min)

bull Charge ETR for range limit (min)

bull Charge ETR for SOC limit (min)

bull Max ideal range

378 Messages 377

Open Vehicles

bull Chargeplug type ID according to OpenChargeMapsorg connectiontypes (see httpapiopenchargemapiov2referencedata)

bull Charge power output (kW)

bull Battery voltage (V)

bull Battery SOH (state of health) ()

bull Charge power input (kW)

bull Charger efficiency ()

bull Battery current (A)

bull Battery ideal range gainloss speed (mphkph gain=positive)

37819 Car update time message 0x53 ldquoTrdquo

This message is sent ltservertoappgt ldquosrdquo and transmits the last known update time of the vehicle

ltdatagt is the number of seconds since the car last sent an update message

37820 Car location message 0x4C ldquoLrdquo

This message is sent ltcartoservergt ldquoCrdquo and transmits the last known location of the vehicle

ltdatagt is comma-separated list of

bull Latitude

bull Longitude

bull Car direction

bull Car altitude

bull Car GPS lock (0=nogps 1=goodgps)

bull Stale GPS indicator (-1=none 0=stale gt0 ok)

bull Car speed (in distance units per hour)

bull Car trip meter (in 110th of a distance unit)

bull Drive mode (car specific encoding of current drive mode)

bull Battery power level (in kW negative = charging)

bull Energy used (in Wh)

bull Energy recovered (in Wh)

bull Inverter motor power (kW) (positive = output)

bull Inverter efficiency ()

bull GPS mode indicator (see below)

bull GPS satellite count

bull GPS HDOP (see below)

bull GPS speed (in distance units per hour)

378 Chapter 37 OVMS Protocol v2

Open Vehicles

GPS mode indicator this shows the NMEA receiver mode If using the SIM5360 modem for GPS this is a twocharacter string The first character represents the GPS receiver mode the second the GLONASS receiver mode Eachmode character may be one of

bull N = No fix Satellite system not used in position fix or fix not valid

bull A = Autonomous Satellite system used in non-differential mode in position fix

bull D = Differential (including all OmniSTAR services) Satellite system used in differential mode in position fix

bull P = Precise Satellite system used in precision mode Precision mode is defined as no deliberate degradation(such as Selective Availability) and higher resolution code (P-code) is used to compute position fix

bull R = Real Time Kinematic Satellite system used in RTK mode with fixed integers

bull F = Float RTK Satellite system used in real time kinematic mode with floating integers

bull E = Estimated (dead reckoning) Mode

bull M = Manual Input Mode

bull S = Simulator Mode

GPS HDOP HDOP = horizontal dilution of precision This is a measure for the currently achievable precision ofthe horizontal coordinates (latitude amp longitude) which depends on the momentary relative satellite positions andvisibility to the device

The lower the value the higher the precision Values up to 2 mean high precision up to 5 is good If the value ishigher than 20 coordinates may be off by 300 meters from the actual position

See httpsenwikipediaorgwikiDilution_of_precision_(navigation) for further details

37821 Car Capabilities message 0x56 ldquoVrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the vehicle capabilities It was introducedwith v2 of the protocol

ltdata is comma-separated list of vehicle capabilities of the form

bull Cltcmdgt indicates vehicle support command ltcmdgt

bull CltcmdLgt-ltcmdHgt indicates vehicle will support all commands in the specified range

37822 Car TPMS message 0x57 ldquoWrdquo (oldobsolete)

Note Message ldquoWrdquo has been replaced by ldquoYrdquo (see below) for OVMS V3 The V3 module will still send ldquoWrdquomessages along with ldquoYrdquo for old clients for some time Clients shall adapt to using ldquoYrdquo if available ASAP ldquoWrdquomessages will be removed from V3 in the near future

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the last known TPMS values of thevehicle

ltdatagt is comma-separated list of

bull front-right wheel pressure (psi)

bull front-right wheel temperature (celcius)

bull rear-right wheel pressure (psi)

bull rear-right wheel temperature (celcius)

378 Messages 379

Open Vehicles

bull front-left wheel pressure (psi)

bull front-left wheel temperature (celcius)

bull rear-left wheel pressure (psi)

bull rear-left wheel temperature (celcius)

bull Stale TPMS indicator (-1=none 0=stale gt0 ok)

37823 Car TPMS message 0x59 ldquoYrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the last known TPMS values of thevehicle

ltdatagt is comma-separated list of

bull number of defined wheel names

bull list of defined wheel names

bull number of defined pressures

bull list of defined pressures (kPa)

bull pressures validity indicator (-1=undefined 0=stale 1=valid)

bull number of defined temperatures

bull list of defined temperatures (Celcius)

bull temperatures validity indicator (-1=undefined 0=stale 1=valid)

bull number of defined health states

bull list of defined health states (Percent)

bull health states validity indicator (-1=undefined 0=stale 1=valid)

bull number of defined alert levels

bull list of defined alert levels (0=none 1=warning 2=alert)

bull alert levels validity indicator (-1=undefined 0=stale 1=valid)

Note Pressures are transported in kPa now instead of the former PSI To convert to PSI multiply by014503773773020923

37824 Peer connection message 0x5A ldquoZrdquo

This message is sent ltservertocargt or ltservertoappgt to indicate the connection status of the peer (car for ltserver-toappgt interactive apps for ltservertocargt) It indicates how many peers are currently connected

It is suggested that the car should use this to immediately report on and to increase the report frequency of status - inthe case that one or more interactive Apps are connected and watching the car

Batch client connections do not trigger any peer count change for the car but they still receive the car peer status fromthe server

ltdatagt is

bull Number of peers connected expressed as a decimal string

380 Chapter 37 OVMS Protocol v2

Open Vehicles

37825 Car export power message 0x47 ldquoGrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits ldquovgrdquo metrics from the vehicle

ltdatagt is comma-separated list of

bull vggenerating (1 = currently delivering power)

bull vgpilot (1 = pilot present)

bull vgvoltage (in V)

bull vgcurrent (in A)

bull vgpower (in kW)

bull vgefficiency (in )

bull vgtype (eg ldquochademordquo)

bull vgstate (eg ldquoexportingrdquo)

bull vgsubstate (eg ldquoonrequestrdquo)

bull vgmode (eg ldquostandardrdquo)

bull vgclimit (in A)

bull vglimitrange (in km)

bull vglimitsoc (in )

bull vgkwh (in kWh)

bull vgkwhgrid (in kWh)

bull vgkwhgridtotal (in kWh)

bull vgtime (in s)

bull vgtimermode (1 = generator timer enabled)

bull vgtimerstart

bull vgdurationempty (in min)

bull vgdurationrange (in min)

bull vgdurationsoc (in min)

bull vgtemp (in deg C)

Refer httpsdocsopenvehiclescomenlatestuserguidemetricshtml

379 Commands

3791 Commands and Expected Responses

For message types ldquoCrdquo and ldquocrdquo the following commands and responses are expected to be supported

379 Commands 381

Open Vehicles

3792 1 - Request feature list

Command parameters are unused and ignored by the car

Response is a sequence of individual messages with each message containing the following parameters

bull feature number

bull maximum number of features

bull feature value

Registered features are

bull 0 Digital SPEEDO (experimental)

bull 8 Location STREAM mode (consumes more bandwidth)

bull 9 Minimum SOC

bull 15 CAN bus can write-enabled

Note that features 0 through 7 are lsquovolatilersquo and will be lost (reset to zero value) if the power is lost to the car moduleor module is reprogrammed These features are considered extremely experimental and potentially dangerous

Features 8 through 15 are lsquopermanentrsquo and will be stored as parameters 23 through 31 These features are consideredmore stable but optional

3793 2 - Set feature

Command parameters are

bull feature number to set

bull value to set

Response parameters are unused and will merely indicate the success or not of the result

3794 3 - Request parameter list

Command parameters are unused and ignored by the car

Response is a sequence of individual messages with each message containing the following parameters

bull parameter number

bull maximum number of parameters

bull parameter value

Registered parameters are

bull 0 Registered telephone number

bull 1 Registration Password

bull 2 Miles Kilometer flag

bull 3 Notification method list

bull 4 Server IP

bull 5 GPRS APN

bull 6 GPRS User

382 Chapter 37 OVMS Protocol v2

Open Vehicles

bull 7 GPRS Password

bull 8 Vehicle ID

bull 9 Network Password

bull 10 Paranoid Password

Note that some parameters (24 through 31) are tied directly to the features system (for permanent features) and arethus not directly maintained by the parameter system or shown by this command

3795 4 - Set parameter

Command parameters are

bull parameter number to set

bull value to set

Response parameters are unused and will merely indicate the success or not of the result

3796 5 - Reboot

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result Shortly after sending theresponse the module will reboot

3797 6 - Charge Alert

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result Shortly after sending theresponse the module will issue a charge alert

3798 7 - Execute SMS command

Command parameter is

bull SMS command with parameters

Response is the output of the SMS command that would otherwise have been sent as the reply SMS with LF charactersconverted to CR

The caller id is set to the registered phone number Return code 1 is used for all errors ie authorization failurecommand failure and unknownunhandled commands

Note SMS commands with multiple replies are not yet supported only the last reply will be returned

3799 10 - Set Charge Mode

Command parameters are

bull mode (0=standard 1=storage3=range4=performance)

Response parameters are unused and will merely indicate the success or not of the result

379 Commands 383

Open Vehicles

37910 11 - Start Charge

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

37911 12 - Stop Charge

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

37912 15 - Set Charge Current

Command parameters are

bull current (specified in Amps)

Response parameters are unused and will merely indicate the success or not of the result

37913 16 - Set Charge Mode and Current

Command parameters are

bull mode (0=standard 1=storage3=range4=performance)

bull current (specified in Amps)

Response parameters are unused and will merely indicate the success or not of the result

37914 17 - Set Charge Timer Mode and Start Time

Command parameters are

bull timermode (0=plugin 1=timer)

bull start time (0x059F for midnight GMT 0x003B for 1am GMT etc)

Response parameters are unused and will merely indicate the success or not of the result

37915 18 - Wakeup car

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

37916 19 - Wakeup temperature subsystem

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

384 Chapter 37 OVMS Protocol v2

Open Vehicles

37917 20 - Lock Car

Command parameters are

bull pin (the car pin to use for locking)

Response parameters are unused and will merely indicate the success or not of the result

NB unlocklock may not affect the immobilizer+alarm (when fitted)

37918 21 - Activate Valet Mode

Command parameters are

bull pin (the car pin to activate valet mode)

Response parameters are unused and will merely indicate the success or not of the result

37919 22 - Unlock Car

Command parameters are

bull pin (the car pin to use for unlocking)

Response parameters are unused and will merely indicate the success or not of the result

NB unlocklock does not affect the immobilizer+alarm (when fitted)

37920 23 - Deactivate Value Mode

Command parameters are

bull pin (the car pin to use for deactivating value mode)

Response parameters are unused and will merely indicate the success or not of the result

37921 24 - Home Link

Command parameters are

bull button (home link button 0 1 or 2)

Response parameters are unused and will merely indicate the success or not of the result

37922 25 - Cooldown

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

379 Commands 385

Open Vehicles

37923 30 - Request GPRS utilization data

Command parameters are unused and ignored by the car

Response is a sequence of individual messages with each message containing the following parameters

bull record number

bull maximum number of records

bull date

bull car received bytes

bull car transmitted bytes

bull apps received bytes

bull apps transmitted bytes

Note that this request is handled by the server not the car so must not be sent in paranoid mode The response (fromthe server) will also not be sent in paranoid mode

NB Dates (and GPRS utilization data) are in UTC

37924 31 - Request historical data summary

Command parameters are

bull since (optional timestamp condition)

Response is a sequence of individual messages with each message containing the following parameters

bull type number

bull maximum number of types

bull type value

bull number of unique records (per type)

bull total number of records (per type)

bull storage usage (in bytes per type)

bull oldest data timestamp (per type)

bull newest data timestamp (per type)

NB Timestamps are in UTC

37925 32 - Request historical data records

Command parameters are

bull type (the record type to retrieve)

bull since (optional timestamp condition)

Response is a sequence of individual messages with each message containing the following parameters

bull response record number

bull maximum number of response records

bull data record type

386 Chapter 37 OVMS Protocol v2

Open Vehicles

bull data record timestamp

bull data record number

bull data record value

37926 40 - Send SMS

Command parameters are

bull number (telephone number to send sms to)

bull message (sms message to be sent)

Response parameters are unused and will merely indicate the success or not of the submission (not delivery) of theSMS

37927 41 - Send MMIUSSD Codes

Command parameters are

bull USSD_CODE (the ussd code to send)

Response parameters are unused and will merely indicate the success or not of the submission (not delivery) of therequest

37928 49 - Send raw AT Command

Command parameters are

bull at (the AT command to send - including the AT prefix)

Response parameters are unused and will merely indicate the success or not of the submission (not delivery) of therequest

379 Commands 387

Open Vehicles

388 Chapter 37 OVMS Protocol v2

CHAPTER 38

OVMS HTTP API

381 Welcome

For some time now Irsquove wanted to offer an HTTP API for OVMS The existing carlt-gtserver and serverlt-gtapp protocolis cool but requires going through some hoops (perl whatever) to handle the encryption and protocol level stuff AnHTTP API would make this much easier to externally script and would be great for pulling down logs and other suchthings

This document describes this HTTP API

Mark February 2013

382 Format

The API is a RESTfull service running at

bull httpapiopenvehiclescom6868api

bull httpsapiopenvehiclescom6869api

Other OVMS servers should provide this API on the same ports but for the rest of this manual we will simply refer toapiopenvehiclescom as the server being used

The return data is a json formatted array of hashes Each record is one for one vehicle and shows you the vehicle idas well as counts for the number of apps currently connected to that vehicle and whether the vehicle is connected tothe net (server) or not

From the server point of view we can treat an api session just like an app session From the vehicle point of view therewill be no difference - once an API connects to a vehicle the server will send a ldquoZ 1rdquo message to tell the module it hasa connection If the session times out or is logged out the server will inform the modules in the vehicles

389

Open Vehicles

3821 Example

For example once authenticated you can request a list of vehicles on your account

$ curl -v -X GET -b cookiejar httpapiopenvehiclescom6868apivehicles

About to connect() to apiopenvehiclescom port 6868 (0)

Trying apiopenvehiclescom

connected

Connected to tmcopenvehiclescom (641117040) port 6868 (0)gt GET apivehicles HTTP11User-Agent curl7240 (x86_64-apple-darwin120) libcurl7240OpenSSL098r zlib125Host apiopenvehiclescom6868Accept Cookie ovmsapisession=9ed66d0e-5768-414e-b06d-476f13be40ff

HTTP 10 assume close after bodylt HTTP10 200 Logout oklt Connection closelt Content-Length 280lt Cache-Control max-age=0lt Content-Type applicationjsonlt Date Fri 22 Feb 2013 124441 GMTlt Expires Fri 22 Feb 2013 124441 GMTlt[

idDEMOv_apps_connected0v_net_connected1idMARKSCARv_apps_connected1v_net_connected1idQCCARv_apps_connected0v_net_connected0idRALLYCARv_apps_connected0v_net_connected0idTESTCARv_apps_connected0v_net_connected0

]

(note that the above is re-formatted slightly to make it clearer to read)

383 Authentication

3831 Alternatives

Each API call must be authenticated and there are currently three options for this

Username+Passsword authentication Specify parameters lsquousernamersquo and lsquopasswordrsquo in the URL and they will bevalidated against registered users on the server Username+ApiToken authentication Specify parameter lsquousernamersquoas the registered user and lsquopasswordrsquo as a registered API token in the URL and they will be validated againstregistered API tokens for that user on the server Cookie authentication A cookie may be obtained (by either of theabove two authentication methods) and then used for subsequent API calls

3832 Cookie Based Authentication

Cookie based authentication avoids the requirement to authenticate each time It is also a requirement for sessionbased API calls This is done with a http ldquoGET apicookierdquo passing parameters lsquousernamersquo and lsquopasswordrsquo as yourwwwopenvehiclescom username and password (or API token) respectively

390 Chapter 38 OVMS HTTP API

Open Vehicles

$ curl -v -X GET -c cookiejarhttpapiopenvehiclescom6868apicookieusername=USERNAMEamppassword=PASSWORD

About to connect() to tmcopenvehiclescom port 6868 (0)

Trying 641117040

connected

Connected to tmcopenvehiclescom (641117040) port 6868 (0)GET apicookieusername=USERNAMEamppassword=PASSWORD HTTP11User-Agent curl7240 (x86_64-apple-darwin120) libcurl7240OpenSSL098r zlib125Host tmcopenvehiclescom6868Accept

HTTP 10 assume close after bodylt HTTP10 200 Authentication oklt Connection closelt Content-Length 9lt Cache-Control max-age=0lt Content-Type textplain

Added cookie ovmsapisession=9ed66d0e-5768-414e-b06d-476f13be40ff for domain tmcrarr˓openvehiclescom path api expire 0lt Set-Cookie ovmsapisession=9ed66d0e-5768-414e-b06d-476f13be40fflt Date Fri 22 Feb 2013 124356 GMTlt Expires Fri 22 Feb 2013 124356 GMTltLogin ok

Once logged in all subsequent requests should pass the cookie (ovmsapisession) The session will expire after 3minutes of no use or you can specifically terminate logout the session by calling ldquoDELETE apicookierdquo

The cookie can be destroyed (and session logged out) using the DELETE method (passing the original cookie)

$ curl -v -X DELETE -b cookiejarhttpapiopenvehiclescom6868apicookie

3833 API Token Maintenance

An API token can be created with a POST to the apitoken API endpoint

$ curl -v -X POST -F application=ltappgt -F purpose=ltpurposegt -F permit=ltpermitgthttpapiopenvehiclescom6868apitoken

Note that the lsquopurposersquo and lsquoapplicationrsquo fields are comments attached to the token and are intended to identify theapplication that createduses the token and the purpose that token is used for

The lsquopermitrsquo field defines the list of rights granted to the user of this token

Any of the three authentication mechanisms can be used for this so long as the permissions include either lsquoto-kenadminrsquo or lsquoadminrsquo rights

An API token can be deleted with a DELETE to the apitokenltTOKENgt API endpoint

$ curl -v -X DELETE httpapiopenvehiclescom6868apitokenltTOKENgt

383 Authentication 391

Open Vehicles

384 Requests

3841 GET apicookie

Login and return a session cookie

3842 DELETE apicookie

Delete the session cookie and logout

All vehicles still connected (via apivehicle) will be disconnected automatically

3843 GET apitoken

Return a list of registered API tokens

3844 POST apitoken

Create an API token

3845 DELETE apitokenltTOKENgt

Delete the specified API token

3846 GET apivehicles

Return a list of registered vehicles

bull id Vehicle ID

bull v_net_connected Number of vehicles currently connected

bull v_apps_connected Number of apps currently connected

bull v_btcs_connected Number of batch clients currently connected

3847 GET apivehicleltVEHICLEIDgt

Connect to the vehicle and return vehicle information

bull m_msgage_s age (seconds) of last status (S) message received if available

bull m_msgtime_s time stamp (UTC) of last status (S) message received if available

bull v_apps_connected number of apps currently connected (including the API connection)

bull v_btcs_connected number of batch clients currently connected

bull v_first_peer 01 1 = the API connection is the first peer connecting to the car

bull v_net_connected 01 1 = the car is currently connected to the server

392 Chapter 38 OVMS HTTP API

Open Vehicles

While no application is connected to the vehicle the module will send status updates using the configured ldquoidlerdquointerval to reduce data volume and energy consumption

Connecting to the car tells the module (if connected) to send status updates in the normally shorter ldquoconnectedrdquointervals (as configured) If yoursquore the first peer and the car is online the module will send a full status update withinthe next second after receiving the new peer count Depending on the connection speed you should give the car modulesome seconds to transmit the first update before proceeding to other status queries

You can also check m_msgage_s and m_msgtime_s to see if the status record is up to date (yet) These fields arealso included in the other status responses eg apichargeltVEHICLEIDgt

3848 DELETE apivehicleltVEHICLEIDgt

Disconnect from the vehicle

This is optional on session logout or expiry all vehicles will be disconnected automatically

3849 GET apiprotocolltVEHICLEIDgt

Return raw protocol records (no vehicle connection)

bull m_msgtime Datetime message received

bull m_paranoid Paranoid mode flag

bull m_ptoken Paranoid mode token

bull m_code Message code

bull m_msg Message body

38410 GET apistatusltVEHICLEIDgt

Return vehicle status

bull soc

bull units

bull idealrange

bull idealrange_max

bull estimatedrange

bull mode

bull chargestate

bull cac100

bull soh

bull cooldown_active

bull fl_dooropen

bull fr_dooropen

bull cp_dooropen

bull pilotpresent

384 Requests 393

Open Vehicles

bull charging

bull caron

bull carlocked

bull valetmode

bull bt_open

bull tr_open

bull temperature_pem

bull temperature_motor

bull temperature_battery

bull temperature_charger

bull temperature_cabin

bull tripmeter

bull odometer

bull speed

bull parkingtimer

bull temperature_ambient

bull carawake

bull staletemps

bull staleambient

bull charging_12v

bull vehicle12v

bull vehicle12v_ref

bull vehicle12v_current

bull alarmsounding

bull m_msgage_s age (seconds) of last status (S) message received if available

bull m_msgtime_s time stamp (UTC) of last status (S) message received if available

bull m_msgage_d age (seconds) of last doorsenv (D) message received if available

bull m_msgtime_d time stamp (UTC) of last doorsenv (D) message received if available

38411 GET apitpmsltVEHICLEIDgt

Return tpms status

bull fr_pressure

bull fr_temperature

bull rr_pressure

bull rr_temperature

bull fl_pressure

394 Chapter 38 OVMS HTTP API

Open Vehicles

bull fl_temperature

bull rl_pressure

bull rl_temperature

bull staletpms

bull m_msgage_w age (seconds) of last TPMS (W) message received if available

bull m_msgtime_w time stamp (UTC) of last TPMS (W) message received if available

38412 GET apilocationltVEHICLEIDgt

Return vehicle location

bull latitude

bull longitude

bull direction

bull altitude

bull gpslock

bull stalegps

bull speed

bull tripmeter

bull drivemode

bull power

bull energyused

bull energyrecd

bull m_msgage_l age (seconds) of last location (L) message received if available

bull m_msgtime_l time stamp (UTC) of last location (L) message received if available

38413 GET apichargeltVEHICLEIDgt

Return vehicle charge status

bull linevoltage

bull battvoltage

bull chargecurrent

bull chargepower

bull chargetype

bull chargestate

bull soc

bull units

bull idealrange

bull estimatedrange

384 Requests 395

Open Vehicles

bull mode

bull chargelimit

bull chargeduration

bull chargeb4

bull chargekwh

bull chargesubstate

bull chargetimermode

bull chargestarttime

bull chargetimerstale

bull cac100

bull soh

bull charge_etr_full

bull charge_etr_limit

bull charge_limit_range

bull charge_limit_soc

bull cooldown_active

bull cooldown_tbattery

bull cooldown_timelimit

bull charge_estimate

bull charge_etr_range

bull charge_etr_soc

bull idealrange_max

bull cp_dooropen

bull pilotpresent

bull charging

bull caron

bull temperature_pem

bull temperature_motor

bull temperature_battery

bull temperature_charger

bull temperature_ambient

bull temperature_cabin

bull carawake

bull staletemps

bull staleambient

bull charging_12v

396 Chapter 38 OVMS HTTP API

Open Vehicles

bull vehicle12v

bull vehicle12v_ref

bull vehicle12v_current

bull m_msgage_s age (seconds) of last status (S) message received if available

bull m_msgtime_s time stamp (UTC) of last status (S) message received if available

bull m_msgage_d age (seconds) of last doorsenv (D) message received if available

bull m_msgtime_d time stamp (UTC) of last doorsenv (D) message received if available

38414 GET apihistoricalltVEHICLEIDgt

Request historical data summary (as array of)

bull h_recordtype

bull distinctrecs

bull totalrecs

bull totalsize

bull first

bull last

38415 GET apihistoricalltVEHICLEIDgtltDATATYPEgt

Request historical data records

bull h_timestamp

bull h_recordnumber

bull h_data

38416 Not Yet Implemented

bull PUT apichargeltVEHICLEIDgt Set vehicle charge status

bull DELETE apichargeltVEHICLEIDgt Abort a vehicle charge

bull GET apilockltVEHICLEIDgt Return vehicle lock status

bull PUT apilockltVEHICLEIDgt Lock a vehicle

bull DELETE apilockltVEHICLEIDgt Unlock a vehicle

bull GET apivaletltVEHICLEIDgt Return valet status

bull PUT apivaletltVEHICLEIDgt Enable valet mode

bull DELETE apivaletltVEHICLEIDgt Disable valet mode

bull GET apifeaturesltVEHICLEIDgt Return vehicle features

bull PUT apifeatureltVEHICLEIDgt Set a vehicle feature

bull GET apiparametersltVEHICLEIDgt Return vehicle parameters

384 Requests 397

Open Vehicles

bull PUT apiparameterltVEHICLEIDgt Set a vehicle parameter

bull PUT apiresetltVEHICLEIDgt Reset the module in a particular vehicle

bull PUT apihomelinkltVEHICLEIDgt Activate home link

398 Chapter 38 OVMS HTTP API

Index

AApp 367

CCar 367

SServer 367

399

  • Open-Vehicle-Monitoring-System-3 (OVMS3)
  • User Guide
  • Plugins
  • BMW i3 i3s
  • DBC Based Vehicles
  • DEMO Vehicle
  • Fiat 500e
  • Hyundai Ioniq vFL
  • Jaguar IPace
  • Kia e-Niro
  • Kia Soul EV
  • Maxus eDeliver3
  • Mercedes-Benz B250E W242
  • MG EV
  • Mitsubishi Trio
  • Nissan Leafe-NV200
  • OBDII Vehicles
  • Renault Twizy
  • Renault Zoe
  • Smart ED Gen3
  • Smart EDEQ Gen4 (453)
  • Tesla Model 3
  • Tesla Model S
  • Tesla Roadster
  • Toyota RAV4 EV
  • Tracking Vehicles
  • VW e-Up
  • VW e-Up via OBD2
  • VW e-Up via Comfort CAN (T26A)
  • Command Line Interpreter
  • CAN Bus Data Logging
  • CRTD CAN Log Format
  • Web Framework amp Plugins
  • Scripting
  • CANopen
  • OVMS Server
  • OVMS Protocol v2
  • OVMS HTTP API
  • Index
Page 3: Open Vehicles - Home | Read the Docs

21 Smart EDEQ Gen4 (453) 189

22 Tesla Model 3 191

23 Tesla Model S 193

24 Tesla Roadster 195

25 Toyota RAV4 EV 201

26 Tracking Vehicles 203

27 VW e-Up 205

28 VW e-Up via OBD2 227

29 VW e-Up via Comfort CAN (T26A) 237

30 Command Line Interpreter 245

31 CAN Bus Data Logging 251

32 CRTD CAN Log Format 255

33 Web Framework amp Plugins 261

34 Scripting 341

35 CANopen 351

36 OVMS Server 361

37 OVMS Protocol v2 367

38 OVMS HTTP API 389

Index 399

ii

Open Vehicles

Note This online manual includes documentation for the stable release of the OVMS firmware (available as OTAversion tag ldquomainrdquo) and the latest nightly firmware build (available as OTA version ldquoedgerdquo) Select the manual versionmatching your setup using the menu on the bottom left

User Guides 1

Open Vehicles

2 User Guides

CHAPTER 1

Open-Vehicle-Monitoring-System-3 (OVMS3)

11 Introduction

The OVMS is an all open source vehicle remote monitoring diagnosis and control system

3

Open Vehicles

The system provides live monitoring of vehicle metrics like state of charge temperatures tyre pressures and diag-nostic fault conditions It will alert you about critical conditions and events like a charge abort battery cell failureor potential theft Depending on the vehicle integration it allows you to take control over the charge process cli-mate control tuning parameters of the engine and more OVMS developers are enthusiasts trying hard to provide asdetailed information about the internals of a vehicle as possible

While most new vehicles now include some kind of remote control system very few allow deep insight some willnot work in all regions and none will give you control over your personal data The OVMS fills that gap and alsoenables you to add all these features to existing vehicles of any kind

The OVMS can also be used for fleet monitoring It allows a fleet manager to not only track the vehicle locations butalso to monitor the vehiclersquos vitals remotely check for fault conditions offer services like automatic preheating forusers and take active control in case of abusive use As the system is open source and fully scriptable it can easilyintegrate custom access and control systems

For developers and technicians the OVMS includes a range of CAN tools including multiple logging formats aconfigurable OBD2 translator a DBC decoder a reverse engineering toolkit and a CANopen client The moduleprovides SSH access and WebSocket streaming and can stream and inject CAN frames via TCP Both the module andthe web frontend can be customized by plugins The module has three builtin CAN buses and can be extended by afourth one

The OVMS base component is a small and inexpensive hardware module that connects to the vehicle OBD2 port Thestandard kit includes a 3G modem to provide GSM connectivity and GPS and comes with a ready-to-use HologramioSIM card The US kit has been FCC certified the EU kit CE certified

The module provides a built-in Web App user interface and remote control via native cellphone Apps available forAndroid and iOS It integrates into homeprocess automation systems via MQTT and provides data logging to SDcard and to a server

12 Vehicle Support

bull Native Integration

ndash Chevrolet Volt Opel Ampera

ndash Chevrolet Bolt EV Opel Ampera-e

ndash BMW i3 i3s

ndash Fiat 500e

ndash Hyundai Ioniq vFL

ndash Jaguar Ipace

ndash Kia e-Niro Hyundai Kona

ndash Kia Soul EV

ndash Maxus eDeliver 3

ndash Mercedes-Benz B250E

ndash MG ZS EV

ndash Mitsubishi Trio (i-MiEV et al)

ndash Nissan Leaf e-NV200

ndash Renault Twizy

ndash Renault Zoe Kangoo

4 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

Open Vehicles

ndash Smart ED Gen3

ndash Smart EDEQ Gen4 (453)

ndash Tesla Model S

ndash Tesla Roadster

ndash Think City

ndash Toyota RAV4 EV

ndash VW e-Up

bull General Support

ndash DBC File Based

ndash GPS Tracking

ndash OBD-II Standard

ndash Zeva BMS

13 Links

bull User Resources

ndash User and Developer Guides (hint version selection in left menu at the bottom)

Stable release (OTA version ldquomainrdquo)

Latest nightly build (OTA version ldquoedgerdquo)

ndash User Support Forum

ndash Android App

ndash iOS App

bull Distributors

ndash FastTech (global)

ndash Medlock amp Sons (North America)

ndash OpenEnergyMonitor (UKEurope)

bull Servers

ndash Asia-Pacific

ndash GermanyEurope

bull Developers

ndash Developer Guide

ndash Developer Mailing List amp Archive

ndash Server Source

ndash Android App Source

ndash iOS App Source

13 Links 5

Open Vehicles

14 Hardware

bull Module Schematics and PCB Layouts

bull Base Module (v30-33)

ndash Black injection-moulded plastic enclosure approximately 99x73x29 mm excl plugs

ndash ESP32 WROVER processor (16MB flash 4MB SPI RAM 520KB SRAM dual core 160240MHz XtensaLX6 processor)

ndash WIFI 80211 bgn

ndash Bluetooth v42 BREDR and BLE

ndash 3x CAN buses

ndash 1x Micro USB connector (for flash download and serial console)

ndash 1x Micro SD card slot

ndash 1x Internal expansion slot

ndash 8x EGPIO 2x GPIO

ndash 1x GSM antenna connector

ndash 1x GPS antenna connector

ndash 1x DB9 vehicle connector

ndash 1x DB26 expansion connector

bull Modem Module v30-32

ndash US edition is SIM5360A (Dual-Band UMTSHSPA+ 8501900MHz Quad-Band GSMGPRSEDGE85090018001900MHz)

ndash EU edition is SIM5360J(E) (Dual-Band UMTSHSPA+ 9002100MHz Quad-Band GSMGPRSEDGE85090018001900MHz)

ndash 3G (EV-DOHSPA+) dual band modem

ndash Includes 2G (GSMGPRS) and 25G (EDGE) quad band

ndash GPSGNSS

6 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

Open Vehicles

ndash Nano (4FF) SIM slot

ndash HOLOGRAMIO nano sim included (can be exchanged if necessary)

bull Modem Module v33

ndash World edition SIM7600G (Multi-Band LTE-FDDLTE-TDDHSPA+ and GSMGPRSEDGE)

ndash 4G (LTE-FDDLTE-TDD) multi band modem

ndash Includes 3G (EV-DOHSPA+) 2G (GSMGPRS) and 25G (EDGE) quad band

ndash GPSGNSS

ndash Nano (4FF) SIM slot

ndash HOLOGRAMIO nano sim included (can be exchanged if necessary)

141 Extensions

The external DB26 DIAG connector provides access to the three CAN buses and offers some free extension ports Theinternal PCB expansion connector allows stacked additions of further modules and serves for routing GPIO ports tothe external DIAG connector See schematics for details

A very nice first extension module has been developed by Marko Juhanne OVMS-SWCAN

If you plan on developing a hardware extension or just want to do some custom adaptations have a look at ourprototyping PCB kit Itrsquos available in packs of 3 PCBs and includes headers and mounting material

If the kit isnrsquot available at the distributors please contact Mark Webb-Johnson markwebb-johnsonnet

14 Hardware 7

Open Vehicles

15 Development and Contributions

New developers are very welcome on any part of the system and we will gladly provide any help needed to getstarted

The purpose of this project is to get the community of vehicle hackers and enthusiasts to be able to expand the projectWe canrsquot do it all and there is so much to do What we are doing is providing an affordable and flexible base that thecommunity can work on and extend

Everything is open and APIs are public Other car modules can talk to the server and other Apps can show the statusand control the car This is a foundation that others hopefully will interface to and and build upon

If yoursquod like to contribute please accept our code of conduct

bull Introduce yourself on the developer mailing list

bull Be kind amp polite

bull Understand the framework concepts

bull Ask if you need help

bull Present your plans if in doubt

bull Write decent code

bull If you extend modules stick to their code style

bull Write brief but descriptive commit comments

bull Add user level descriptions to the change history

bull Provide documentation in the user guide

bull Use pull requests to submit your code for inclusion

A note on pull requests

Pull requests shall focus on one specific issue feature vehicle at a time and shall only mix vehicle specific changeswith framework changes if they depend on each other If changes are not or only loosely related split them intomultiple PRs (just as you would do with commits)

Usage hint create a branch for each pull request include only those commits in that branch (by cherry-picking ifnecessary) that shall be included in the pull request That way you can push further commits to that branch Githubwill automatically add them to an open pull request

16 Donations

The OVMS is a non-profit community project Hardware production and service can normally be financed by salesbut some things (eg prototype development and certifications) need extra money To help the project you can makea donation on the OVMS website httpswwwopenvehiclescomforum

Please also consider supporting the vehicle developers directly Check out their web sites and support addresses fortheir respective donation channels

Thank you

8 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

Open Vehicles

17 License

The project includes some third party libraries and components to which their respective licenses apply see componentsources for details

The project itself is published under the MIT license

Copyright (c) 2011-2020 Open Vehicles

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

Software which uses other licenses will be annotated appropriately

17 License 9

Open Vehicles

10 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

CHAPTER 2

User Guide

21 Warnings and Notices

211 OVMS-33-7600G FCC Statement

This equipment has been tested and found to comply with the limits for a Class B digital device pursuant to part15 of the FCC Rules These limits are designed to provide reasonable protection against harmful interference in aresidential installation This equipment generates uses and can radiate radio frequency energy and if not installedand used in accordance with the instructions may cause harmful interference to radio communications Howeverthere is no guarantee that interference will not occur in a particular installation If this equipment does cause harmfulinterference to radio or television reception which can be determined by turning the equipment off and on the user isencouraged to try to correct the interference by one or more of the following measures

bull Reorient or relocate the receiving antenna

bull Increase the separation between the equipment and receiver

bull Connect the equipment into an outlet on a circuit different from that to which the receiver is connected

bull Consult the dealer or an experienced radioTV technician for help

Caution Any changes or modications to this device not explicitly approved by manufacturer could void your authorityto operate this equipment

This device complies with part 15 of the FCC Rules Operation is subject to the following two conditions (1)This device may not cause harmful interference and (2) this device must accept any interference received includinginterference that may cause undesired operation

212 OVMS-33-7600G Specific Absorption Rate (SAR) information

This OVMS-33-7600G meets the governmentrsquos requirements for exposure to radio waves The guidelines are basedon standards that were developed by independent scientific organizations through periodic and thorough evaluationof scientific studies The standards include a substantial safety margin designed to assure the safety of all personsregardless of age or health FCC RF Exposure Information and Statement the SAR limit of USA (FCC) is 16 Wkg

11

Open Vehicles

averaged over one gram of tissue Device types OVMS-33-7600G has also been tested against this SAR limit Thisdevice was tested for typical body-worn operations with the back of the phone kept 0mm from the body To maintaincompliance with FCC RF exposure requirements use accessories that maintain an 0mm separation distance betweenthe userrsquos body and the back of the phone The use of belt clips holsters and similar accessories should not containmetallic components in its assembly The use of accessories that do not satisfy these requirements may not complywith FCC RF exposure requirements and should be avoided

213 OVMS-33-7600G CE Statement

EU importer information

OpenEnergyMonitorInTec F9Ffordd y Parc Parc MenaiBangorLL57 4FGUnited Kingdom

This product can be used across EU member states

Specification

12 Chapter 2 User Guide

Open Vehicles

Manufacturer Open Vehicles LtdHardware Version Software Version Frequency Range

bull 24G WIFI 2412MHz ~ 2472MHz(Max powerRated 1569dBm)

bull GSM 900 880MHz ~ 915MHz(Max powerRated 3266dBm)

bull DCS 1800 1710MHz ~ 1785MHz(Max powerRated 2975dBm)

bull WCDMA Band I 1920MHz ~ 1980MHz(Maxpower Rated 2340dBm)

bull WCDMA Band VIII 880MHz~915MHz(Maxpower Rated 2310dBm)

bull E-UTRA Band 1 1920MHz ~ 1980MHz(Maxpower Rated 2280dBm)

bull E-UTRA Band 3 1710MHz~1785MHz(Maxpower Rated 2240dBm)

bull E-UTRA Band 7 2500MHz ~ 2570MHz(Maxpower Rated 2297dBm)

bull E-UTRA Band 8 880MHz ~ 915MHz(Maxpower Rated 2240dBm)

bull E-UTRA Band 20 832MHz ~ 862MHz(Maxpower Rated 2295dBm)

bull E-UTRA Band 28 703MHz ~ 748MHz(Maxpower Rated 2237dBm)

bull E-UTRA Band 34 2010MHz ~ 2025MHz(Maxpower Rated 2279dBm)

bull E-UTRA Band 38 2570MHz ~ 2620MHz(Maxpower Rated 2296dBm)

bull E-UTRA Band 40 2300MHz ~ 2400MHz(Maxpower Rated 2348dBm)

Receiver category 3

Members applicability

1 Extreme temperature -20-45 Celcius

2 The device complies with RF specifications when the device used at 5mm form your body

3 RED 201453EU

Declaration of Conformity

Hereby Open Vehicles Ltd declares that this OVMS-33-7600G product is in compliance with essential requirementsand other relevant provisions of Directive 201453EU A copy of the Declaration of conformity can be found atwwwopenvehiclescom

21 Warnings and Notices 13

Open Vehicles

214 General Warnings

WarningOVMS is a hobbyist project not a commercial product It was designed by enthusiasts for enthusiasts Installationand use of this module requires some technical knowledge and if you donrsquot have that we recommend you contactother users in your area to ask for assistance

WarningThe OVMS module is continuously powered by the car even when the car is off While the OVMS module usesextremely low power it does continuously draw power from the carrsquos battery so it will contribute to lsquovampirersquo powerdrains

Do not allow your car battery to reach 0 SOC and if it does plug in and charge the car immediately Failure to dothis can result in unrecoverable failure of the carrsquos battery

The module can monitor the main and 12V battery and send alert notifications if the SOC or voltage drops below ahealthy level

215 Average Power Usage

The power used by the module depends on the component activation You can save power by disabling unusedcomponents This can be done automatically by the Power Management module to avoid deep discharging the 12Vbattery or you can use scripts to automate switching components off and on

The base components need approximately these power levels continuously while powered on

Component Avg Power 12V CurrentBase System 200 mW 17 mAWifi 330 mW 28 mAModem 170 mW 13 mAGPS 230 mW 19 mATotal 930 mW 78 mA

This adds up to

bull ~ 22 Wh or 2 Ah day

14 Chapter 2 User Guide

Open Vehicles

bull ~ 156 Wh or 13 Ah week

bull ~ 680 Wh or 57 Ah month

Note that depending on the vehicle type the module may also need to wake up the ECU periodically to retrieve thevehicle status Check the vehicle specific documentation sections for hints on the power usage for this and options toavoid or reduce this

22 Components

221 The OVMS Module

The OVMS v3 module is housed in a plastic enclosure held secure by four small screws Once open you can see themain OVMS v3 motherboard and an optional modem board

At one end of the module is the main DB9 connector you will use to connect to the vehicle as well as GSM (cellular)and GPS (positioning) antenna connections

At the other end of the module is the DA26 expansion connector the USB diagnostic connector and a Micro SD cardslot

Warning The USB port is a fragile PCB socket without reinforcement Handle it carefully do not apply forcewhen plugging or unplugging cables to not bend the plug If you need to use the port frequently two dots of hotglue at the port sides on the PCB can help to avoid breaking it off

If you open the module and take out the board take care to guide the port carefully and correctly into itrsquos case holewhen inserting the board into the casing again Insert the board USB port side first

If removinginstalling optional expansion boards (such as used for cellular connectivity) please take care to ensureyou secure screw down the expansion board using the four pillar posts provided Also please ensure that the cellularmodem connections are correct (follow the printed table on the modem board to know which antenna is which)

22 Components 15

Open Vehicles

WarningThe OVMS v3 enclosure is not waterproof and the components can be damaged by water Do not get the modulewet and do not connect it to your vehicle if it is wet

222 Cellular Modem Option and GSM Antenna

The cellular modem option allows you to control your vehicle when out of wifi coverage range The majority ofOVMS users choose this option and you will require it if you want to monitor your vehicle when away from home oroffice

OVMS modules sold in USA and Europe are provided with a Hologram SIM card pre-installed This low cost serviceallows you to get cellular connectivity simply It also allows you to roam between countries without worry Formodules purchased from China we recommend you purchase a Hologram SIM directly from the hologramio store(also available on Amazon)

Depending on settings verbosity towards the OVMS server rhythm of GPS tracking etc OVMS v3 will use between1 and 3 Megabytes per month of data (when using the v2 server protocol)

You do not have to use the Hologram service If you use another cellular provider the Sim Card format required is4FF Nano Micro Sim cards are hard to recut into the smaller format so please be careful to not damage the socketotherwise ask your operator for a swap (some do it for free)

If you are using the cellular option you should attach a suitable cellular antenna to the module using the antennaconnector labeled ldquoGSMrdquo

Modem Status LED

The blue LED on the modem board shows the current modem status

LED Status SIM5360 (3G) SIM7600 (4G)ON Searching network Searching networkFast blinking (200ms) Data Transmit Data Transmit 4G registeredSlow blinking (800ms) Registered network 2G3G registered networkOFF Power off Sleep Power off Sleep

223 GPSGNSS Antenna

Some OVMS vehicles can read the GPS signals from the car communication networks directly and do not require anyadditional hardware For others the OVMS v3 modem option also includes a GNSSGPS satellite tracking receiver

If you are using this option you should connect a suitable active GPS antenna to the connector labelled ldquoGPSrdquo

16 Chapter 2 User Guide

Open Vehicles

224 Vehicle Connection

The connection to the vehicle is by the DB9 connector labelled ldquoVEHICLErdquo This provides power to the OVMSmodule as well as connection to the vehicle communication networks

Different vehicles require different cables so you should refer to the appropriate vehicle section of this user guide todetermine which is correct for yours

225 OVMS Server v2

The OVMS Server v2 protocol is a proprietary protocol used to communicate between the vehicle and an OVMS v2server as well as from that server to the cellphone apps To provide compatibility with existing OVMS v2 cellphoneapps and servers OVMS v3 includes full support for the OVMS v2 protocol

226 OVMS Server v3

The OVMS Server v3 protocol is MQTT This is an industry standard protocol and means an OVMS v3 module cancommunicate with any standard MQTT server While this is the future of OVMS support for this is experimental atthe moment and production users should use OVMS Server v2 protocol

227 Upgrading from OVMS v1v2 to v3

The antenna and vehicle connectors for OVMS v3 are the same as for OVMS v2 and existing cablesantennas cangenerally be re-used for OVMS v3 Note however that the frequency ranges supported by individual 3G networksmay be different than 2G so may benefit from an antenna specifically designed for the 3G frequency ranges used

23 Installation

231 Pre-Installation Steps

WarningPrior to connecting the OVMS module to the vehicle or computer via USB if you have the GSM cellular option werecommend you connect a GSM antenna GSM systems are designed to always operate with an antenna andpowering on one without could damage the equipment

Prior to installation please make sure you have the following available

1 The OVMS v3 module in itrsquos enclosure

2 A micro-usb cable suitable for connecting to your computer

3 A laptop or desktop computer (if necessary)

23 Installation 17

Open Vehicles

4 A cable suitable for connecting to your vehicle

5 A GSM antenna (if you are using the cellular option)

6 A GPS antenna (if your vehicle type requires one)

You should also have ready access to this User Guide and wifi connectivity to the Internet

232 OVMS Module Installation

Powering the module

If you intend to configure the module on your desk before connecting it to the vehicle make sure your USB portdelivers power (around 500mA depending on modem and wifi activity) We recommend using a USB hub with aseparate power supply or a direct port of your laptop PC

Warning The v33 LTE Modem (SIMCOM 7600G) may not be able to connect or not power up at all whenpowered from USB even with a powered USB hub

If you cannot get the cellular connection to work on your desk try powering from your carrsquos OBD port first

Another option is adding a 12V supply on your desk eg using a standard RC 3S LiPo battery (connect 12V+ toOBD pin 16 and GND- to OBD pin 4) You can connect USB and OBD12V supply simultaneously be aware themodule will boot as soon as any power source is present

OVMS Server account

If you want to use the OVMS App andor server based telemetry services yoursquoll need an OVMS v2 server account Ifyou have not registered for an OVMS server account yet you can do so before starting the wizard to avoid needing toswitch networks in between There are currently two public v2 OVMS servers

1 Asia-Pacific httpswwwopenvehiclescom

2 Europe httpsdexters-webde

You will need to create a user account first Within your user account you then need to create a vehicle account Yoursquollneed to pick a unique vehicle ID for this eg your vehicle license plate number

Initial Connection (Wifi and Browser)

From the factory or after a factory reset your OVMS module will be running an access point with the followingcredentials

SSID OVMS Password OVMSinit

As this is insecure you should take care not to leave the module running unconfigured

Using your laptoptabletphone establish a wifi connection to the module You should see an IP address in the range1921684x allocated with a gateway at 19216841

Note Some smartphones (eg Android) require mobile data to be switched off to use a WiFi connection without ainterent connectivity

Launch your web browser and connect as follows

URL http19216841

Once connected you will be presented with a screen as follows

18 Chapter 2 User Guide

Open Vehicles

23 Installation 19

Open Vehicles

Setup wizard

The first thing to do is run the setup wizard Click Start setup now The wizard takes you through the initial setup infive simple steps telling you what it is doing and what to expect for each step

20 Chapter 2 User Guide

Open Vehicles

23 Installation 21

Open Vehicles

The wizard will need to reconfigure the module for the Wifi setup read the notes and be prepared to reconnect to themodule as necessary

Note we recommend not to use a password manager during the setup process Some browsers eg Chrome will fillin the module ID as the username which is wrong The login username needs to be admin

The wizard should be able to restore access after problems occurring in the process As a last resort if it fails to recoverat some point you can always do a factory reset and start over again

Manual configuration

After finishing the wizard or if you prefer to do a manual setup the configuration menus will provide single pages foreach module function These also contain advanced options for the features so itrsquos worth having a look

Vehicle Configuration

Go to Config Vehicle

Yoursquoll want to enter your vehicle type Vehicle ID (the same as you registered on the OVMS server) and distance unitsYou can also optionally enter your timezone (see httpswwwgnuorgsoftwarelibcmanualhtml_nodeTZ-Variablehtml for an article on GLIBC timezones for information on the format of this a list of suitable zone strings can alsobe found here httpsremotemonitoringsystemscatime-zone-abbreviationsphp)

OVMS Server v2 Configuration

Go to Config Server V2 to configure the connection to the OVMS v2 server you will be using

22 Chapter 2 User Guide

Open Vehicles

You should enter the server host (apiopenvehiclescom or ovmsdexters-webde usually) and vehicle password (akaserver password - as entered on the server when you registered your vehicle) The Vehicle ID field should already bethere and the other parameters are optional

Auto Start Configuration

OVMS has a powerful scripting language that can be used for complex configurations but to get started it is simplestto use the Auto Start system You get to this from the web interface by clicking Config Autostart

23 Installation 23

Open Vehicles

You will usually want to click to Enable auto start and Start server v2 The other fields should have been populatedcorrectly automatically for you If you are using the optional modem module you should also click Start modem toenable the modem

Once complete you can Save amp reboot to activate your new configuration

WarningDo not set the Wifi mode to AP+Client or Client before having configured your Wifi network

If you have configured this manually the Wifi network may not start automatically Log in using a USB terminal andeither do a factory reset (see Module Factory Reset) or (better) issue enable to enter secure mode then issue configset auto wifimode ap and reboot

Networking Options

OVMS v3 has a number of networking options to choose from You can either use these individually or combine themto provide failover and alternative network connectivity arrangements

1 Wifi Client OVMS can connect to a WiFi Access Point using standard WiFi (80211 bgn) protocols toconnect to a SSID (Access Point name) with associated password In simple client mode you can connect onlyto a single pre-specified SSID Alternatively you can use the scanning client mode to connect to any known

24 Chapter 2 User Guide

Open Vehicles

WiFi Access Point when within range (note however that this is not possible when you run both client andaccess point on the same OVMS device)

2 Wifi Access Point OVMS can operate as a WiFi Access Point itself using standard WiFi (80211 bgn) pro-tocols This allows users to connect to the OVMS module itself Note that OVMS v3 is not intended to be ahotspot and users cannot access the Internet via the OVMS module Wifi Access Point mode can be combinedwith simple Wifi Client mode to provide an access point for maintenance of the module as well as a client toaccess the Internet via another Access Point within range

3 Cellular Data OVMS supports optional modems to provide cellular connectivity These are configured viaConfig Modem

233 GSM SIM Activation (Hologram)

OVMS has partnered with Hologram and to provide a Hologram GSM SIM pre-installed in every OVMS kit purchasedfrom our partners in Europe and USA For modules purchased from China we recommend you purchase a HologramSIM directly from the hologramio store (also available on Amazon) In addition Hologram have provided OVMS acoupon code valid for US$5 off data usage

Hologram Coupon Code OVMS

To activate your Hologram SIM register at httpsdashboardhologramio then invoke ldquoActivate SIMrdquo in the dash-board

Note You donrsquot need to purchase a phone number for your SIM right now as there is no SMS support in V3 yet Forthe current status of SMS support see

bull Issue 62 SMS Notifications

bull Issue 63 SMS Command Gateway

When activating your Hologram SIM yoursquoll need to enter the ICCID written on the SIM itself You can also get thatelectronically (without having to open up the enclosure) from the OVMS web or terminal shell (Tools gt Shell) withthe following command

OVMS metric list mnetmdmiccid

The ICCID is also displayed during the setup process and on the modem configuration page when using the web userinterface

23 Installation 25

Open Vehicles

234 Firmware Update

The factory firmware that is provided with the module may be quite out of date You should perform a firmware updateto ensure that you have the latest firmware You can do this either over Wifi client connections or via an SD CARD

We recommend using the auto update system This will be preconfigured if you have used the setup wizard Theautomatic updates are done within a selectable hour of day and only if Wifi connectivity is available at the time

26 Chapter 2 User Guide

Open Vehicles

Flash from Web

You can typically just press the Flash now button and wait for completion

Flash from File

Using an SD CARD formatted as FAT download the firmware update and place it in a file called ovms3bin in theroot directory of the SD CARD Once the SD CARD is inserted the firmware update will start immediately

235 12V Monitoring

Note Since release 32006 the 12V calibration and alert setup can be done from the web UIrsquos vehicle configurationpage

As 12V batteries tend to die without warning and need to handle an additional unplanned constant load from theOVMS the module includes a 12V monitoring and alert system

Calibration

The 12V voltage is measured using the incoming voltage that powers the OVMS As the sensor used by the modulehas some manufacturing tolerances you should do an initial calibration Use a voltage meter to measure the actualvoltage somewhere suitable (eg at a 12V auxiliary equipment plug) calibrate the OVMS to show the same Thecalibration factor is set by

config set systemadc factor12v ltfactorgt

Calculate the ltfactorgt using oldFactor (displayedVoltage actualVoltage)

bull oldFactor is the old value set If you have not changed it yet it is 1957

bull displayedVoltage is the Voltage as displayed by the OVMS

bull actualVoltage is the Voltage as measured by hand using a voltmeter

The voltage is read once per second and smoothed over 5 samples so after changing the factor wait 5-10 seconds forthe new reading to settle

23 Installation 27

Open Vehicles

Configuration

The default 12V reference voltage (= fully charged amp calmed down voltage level) can be set by

config set vehicle 12vref ltvoltagegt

This config value initializes metric vb12vvoltageref on boot The metric will then be updated automati-cally if your vehicle supports the vecharging12v flag The measured reference voltage reflects the health of the12V battery and serves as the reference for the 12V alert if itrsquos higher than the configured default

The 12V alert threshold can be set by

config set vehicle 12valert ltvoltagediffgt

The 12V alert threshold is defined by a relative value to the 12v reference voltage If the actual 12V reading dropsbelow 12vref - 12valert the 12V alert is raised

The default reference voltage is 126V the default alert threshold 16V so the alert will be triggered if the voltagedrops below 110V This is suitable for standard lead-acid type batteries If yoursquove got another chemistry change thevalues accordingly

Related Metrics

Metric Example Value Meaningvb12vcurrent 06A Momentary current level at the 12V batteryvb12vvoltage 1328V Momentary voltage level at the 12V batteryvb12vvoltageref 1251V Reference voltage of the fully charged amp calmed down 12V batteryvb12vvoltagealert no If the 12V critical alert is active (yesno)vecharging12v yes If the 12V battery is charging or not (yesno)

Related Events

Event Data Purposevehiclealert12von 12V system voltage is below alert thresholdvehiclealert12voff 12V system voltage has recoveredvehiclecharge12vstart Vehicle 12V battery is chargingvehiclecharge12vstop Vehicle 12V battery has stopped charging

24 The OVMS Console

241 Console Connections

OVMS v3 includes a powerful command line console that can be accessed in various ways

1 Using a micro USB cable to a host computer

If the OVMS is not recognised via USB download the driver from SILABS website You will also need asuitable terminal emulator The baud rate is 115200 and you should not enable hardware flow control

2 TELNET (over wifi)

28 Chapter 2 User Guide

Open Vehicles

Note that for security reasons the telnet server component is not enabled in the default productionfirmware (but may be available in custom builds) If Telnet is available telnet to the IP address of themodule (or ltvehicleidgtlocal MDNS address)

3 SSH (over wifi)

SSH to the IP address of the module (or ltvehicleidgtlocal MDNS address) Note that when first bootedwith a network connection the module takes a minute or so to generate server side keys (which are storedin the config store)

4 Web Console SHELL tab

Use a web browser to connect to the IP address of the module (or ltvehicleidgtlocal MDNS address) ASHELL tab is available for direct command line console access

5 Remote Apps

The OVMS Android App currently includes a shell screen that can be used to issue command line consolecommands via the OVMS server v2 This functionality is not currently available in the iPhoneiPad App

6 SMS

Console commands can be issued via SMS

USB Console

Our recommendations for the USB console are as follows

1 You can use a Windows Linux Mac OSX workstation or an Android device with a USB OTG adapter cable

2 If your operating system does not have the SILABS USB driver you can download the driver from SILABSwebsite If you use Linux and your distribution includes the braille display driver ldquobrlttyrdquo you may need touninstall that as it claims any CP2102 device to be a braille device This applies eg to openSuSE 150

3 Plug in the module to your PClaptop using a micro USB cable Check to ensure a serial port appears (using theSILABS driver) For OSX and Linux this will normally appear as devttySLAB_USBtoUART or devttyUSB0(or 12 if other serial devices are connected) List your devices using ldquols devUSBrdquo

4 Once the serial port is available you will need a terminal emulator

bull For OSX the simplest is the built-in SCREEN utility You run this as screen -L devttySLAB_USBtoUART 115200 But note that the device path may be different for you - check with lsquolsdevUSBrsquo You can use lsquocontrol-a control-yrsquo or lsquocontrol-a k yrsquo (three key sequences) to exit the screenThe ldquo-Lrdquo option tells screen to capture a log of your session into the file ldquoscreenlogltngtrdquo

bull For Linux the SCREEN utility is also simple to get If it is not included with your distribution you can simplyyum install screen or apt-get install screen (depending on your distribution) From there the command is thesame as for OSX Alternatively you can use minicom (which is included with many linux distributions)

bull For Windows a simple approach is to download the free PUTTY terminal emulator This supports both directASYNC (over USB) connections as well as SSH (network) You can download putty using this link

bull For Android there are multiple USB serial Apps in the Play store A good recommendation is Serial USBTerminal by Kai Morich

5 Once you have established the connection press ENTER to see the ldquoOVMSgtrdquo prompt

SSH Console

A workstation (Mac Linux Window) on the same wifi network as the OVMS module can use the ssh protocol toconnect In Windows you can use the free PUTTY ssh client In Linux and OSX ssh is built-in

24 The OVMS Console 29

Open Vehicles

The syntax is simply

ssh userip

Where lsquouserrsquo is the username (normally lsquoovmsrsquo) and lsquoiprsquo is the IP address of the OVMS v3 module In environmentssupporting mDNS networking you should also be able to connect using the mDNS name ltvehicleidgtlocal Thepassword you enter is the module password

If you use ssh publicprivate key pairs you can store your public key on the OVMS v3 module to take advantage ofpasswordless login

OVMS config set sshkeys ltusergt ltpublic-keygt

In this case lsquouserrsquo is the username you use to ssh and the public key is your RSA public key (the long base64 blob oftext you find in id-rsapub between lsquossh-rsarsquo and your usernamecomment)

You can also use SCP to copy files to and from the OVMS v3 VFS

Note With OpenSSH version 88 (or later) the ssh-rsa algorithm has been disabled by default and needs to beenabled manually either on the command line

ssh -o HostkeyAlgorithms=+ssh-rsa -o PubkeyAcceptedAlgorithms=+ssh-rsa userip

or by adding a host entry to your ~sshconfig file

Host ovmsnamelocalHostkeyAlgorithms +ssh-rsaPubkeyAcceptedAlgorithms +ssh-rsa

242 Console Basics

Letrsquos use SSH to demonstrate this

$ ssh ovmsovmslocal

Welcome to the Open Vehicle Monitoring System (OVMS) - SSH ConsoleFirmware 31003-2-g7ea18b4-dirtyfactorymainHardware OVMS WIFI BLE BT cores=2 rev=ESP321

OVMS

When first connecting using USB the console will be in non-secure mode (as indicated by the ldquoOVMSgtrdquo prompt)Here only a limited number of commands are available (such as viewing network status modem status or systemtime) To get to secure mode enter the command lsquoenablersquo and provide the module password The prompt will thenchange to ldquoOVMSrdquo

OVMSgt enablePasswordSecure modeOVMS

You can enter the lsquodisablersquo command to get out of secure mode and lsquoexitrsquo to exit the console completely

When connecting via a pre-authenticated protocol such as SSH you will be in secure mode automatically

At any time you can use ldquordquo to show the available commands For example

30 Chapter 2 User Guide

Open Vehicles

OVMS Run a scriptboot BOOT frameworkcan CAN frameworkcharge Charging frameworkco CANopen frameworkconfig CONFIG frameworkdisable Leave secure mode (disable access to most commands)egpio EGPIO frameworkenable Enter secure mode (enable access to all commands)event EVENT frameworkexit End console sessionhelp Ask for helphomelink Activate specified homelink buttonlocation LOCATION frameworklock Lock vehiclelog LOG frameworkmetrics METRICS frameworkmodule MODULE frameworknetwork NETWORK frameworknotify NOTIFICATION frameworkobdii OBDII frameworkota OTA frameworkpower Power controlre RE frameworkscript Run a scriptsd SD CARD frameworkserver OVMS Server Connection frameworkmodem MODEM frameworkstat Show vehicle statusstore STORE frameworktest Test frameworktime TIME frameworkunlock Unlock vehicleunvalet Deactivate valet modevalet Activate valet modevehicle Vehicle frameworkvfs Virtual File System frameworkwakeup Wake up vehiclewifi WIFI framework

You can also use ldquordquo as part of a command to expand on the available options within that command root

OVMS wifi mode WIFI mode frameworkscan Perform a wifi scanstatus Show wifi status

OVMS wifi mode ap Acts as a WIFI Access Pointapclient Acts as a WIFI Access Point and Clientclient Connect to a WIFI network as a clientoff Turn off wifi networking

OVMS wifi mode client Usage wifi mode client ltssidgt ltbssidgt

Command tokens can be abbreviated so long as enough characters are entered to uniquely identify the command Op-

24 The OVMS Console 31

Open Vehicles

tionally pressing TAB at that point will auto-complete the token If the abbreviated form is not sufficient to be unique(in particular if no characters have been entered yet) then TAB will show a concise list of the possible subcommandsand retype the portion of the command line already entered so it can be completed

OVMS wifi ltTABgtmode scan statusOVMS wifi

Pressing TAB is legal at any point in the command if there is nothing more that can be completed automatically thenthere will just be no response to the TAB

25 Logging

251 Logging to the Console

Components of the OVMS system output diagnostic logs (information warnings etc) You can choose to displaythese logs on your connected console with the lsquolog monitor yesnorsquo command

OVMS log monitor Usage log monitor [no|yes]no Dont monitor logyes Monitor log

By default the USB console will have log monitoring lsquoyesrsquo SSH (and telnet if enabled) lsquonorsquo

The web shell does not use the log monitor command but has a checkbox in the upper right corner of the shellpanel instead The keyboard shortcut for the checkbox is L (Alt-L or Alt-Shift-L depending on your browser) Theweb frontend gets the continuous stream of log messages independent of the shell panel or the monitoring being activeand shows the last 100 messages received when opening the shell panel

Logs are output at various levels of verbosity and you can control what is shown both globally and on a per-componentbasis

OVMS log level none No logging (0)error Log at the ERROR level (1)warn Log at the WARN level (2)info Log at the INFO level (3)debug Log at the DEBUG level (4)verbose Log at the VERBOSE level (5)

(Note sorted here for level clarity)

The syntax of this command is log level ltlevelgt [ltcomponentgt] If the component is not specified thelevel applies to all components that donrsquot get a level set explicitly afterwards The levels increase in verbosity andsetting a particular level will also include all log output at a lower level of verbosity (so for example setting level infowill also include warn and error output)

A log line typically looks like this

I (32244049) ovms-server-v2 One or more peers have connectedLog message

Component nameTimestamp (milliseconds since boot)

Log level (I=INFO)

32 Chapter 2 User Guide

Open Vehicles

Log levels are applied on log message generation so a later change to a higher level will not reveal messages generatedpreviously

252 Logging to SD CARD

You can also choose to store logs on SD CARD This is very useful to capture debugging information for the develop-ers as the log will show what happened before a crash or misbehaviour

We recommend creating a directory to store logs ie

OVMS vfs mkdir sdlogs

To enable logging to a file issue for example

OVMS log file sdlogs20180420log

The destination file can be changed any time To disable logging to the file issue log close to restart loggingafter a close issue log open You may choose an arbitrary file name good practice is using some date andor bugidentification tag Note logging will append to the file if it already exists To remove a file use vfs rm

File logging does not persist over a reboot or crash (unless configured as shown below) you can use a script bound tothe sdmounted event to re-enable file logging automatically or configure automatic logging (see below)

You can use the webserver to view and download the files The webserver default configuration enables directorylistings and access to files located under the document root directory which is sd by default Any path not bound toan internal webserver function is served from the document root So you can get an inventory of your log files now atthe URL

http19216841logs

and access your log files from there or directly by their respective URLs Another option to retrieve the files withoutunmounting the SD card is by scp if you have configured SSH access

253 Logging Configuration

Use the web UI or config command to configure your log levels and file setup to be applied automatically on boot

OVMS config list loglog (readable writeable)

fileenable yesfilekeepdays 7filemaxsize 1024filepath sdlogslogfilesyncperiod 3level infolevelmodem infolevelv-twizy verboselevelwebserver debug

25 Logging 33

Open Vehicles

The log command can be used for temporary changes if you change the configuration it will be applied as a wholereplacing your temporary setup

If a maximum file size gt0 is configured the file will be closed and archived when the size is reached The archivename consists of the log file name with added suffix of the timestamp ie sdlogslog20180421-140356Using a logs directory will keep all your archived logs accessible at one place If filekeepdays is defined olderarchived logs will automatically be deleted on a daily base

Take care not to remove an SD card while logging to it is active (or any running file access) The log file should stillbe consistent as it is synchronized after every write but the SD file system currently cannot cope with SD removalwith open files You will need to reboot the module To avoid this always use the ldquoCloserdquo button or the log closecommand before removing the SD card

You donrsquot need to re-enable logging to an SD path after insertion the module will watch for the mount event andautomatically start logging to it

254 Performance Impact

SD card IO has an impact on the module performance So file logging should generally be switched off or runon a low level (ie ldquoinfordquo or ldquowarnrdquo) unless yoursquore hunting some bug or checking some details of operation Wealso recommend using a fast SD card for logging (check the speed with sd status check if you can raise configsdcard maxfreqkhz to 20000 kHz)

34 Chapter 2 User Guide

Open Vehicles

File logging is done by a separate task but flushing the file buffers to the SD card still may block the logging CPUcore or even both CPU cores for a short period To reduce the impact of this the log task by default only flushes thebuffer after 15 seconds of log inactivity This means you may lose the last log messages before a crash

To change the flush behaviour set config filesyncperiod to

bull 0 = never flush (ie only at log close log cycle)

bull lt 0 = flush every n log messages (ie -1 = flush after every message)

bull gt 0 = flush after n2 seconds idle

The log task counts the time spent for flushes and outputs it with the log status command

OVMS log statusLog listeners 3File logging status active

Log file path sdlogslogCurrent size 8170 kBCycle size 1024 kBCycle count 8Dropped messages 0Messages logged 70721Total fsync time 6511 s

This is an example for the default configuration of filesyncperiod 3 the logging here has on average taken6511 70721 = 9 ms per message

26 Configuration

OVMS stores all itrsquos configuration in a standardised protected configuration area accessed by the lsquoconfigrsquo commandThe configurations are organised as follows

ltparametergt ltinstancegt = ltvaluegt

For example

Parameter Instance Valuevehicle id OVMSBOXwifissid MYSSID MyPasswordauto init yes

Each parameter can be defined (by the component that owns it) as having readable andor writeable attributes andthese act as access control for the parameters

bull A lsquowriteablersquo parameter allows values to be created deleted and modified

bull A lsquoreadablersquo parameter allows values to be seen Instance names can be seen on non-readable parameters (it isjust the values themselves that are protected)

For example the lsquovehiclersquo parameter is readable and writeable

OVMS config list vehiclevehicle (readable writeable)

id MYCARtimezone HKT-8

But the lsquowifissidrsquo parameter is only writeable

26 Configuration 35

Open Vehicles

OVMS config list wifissidwifissid (protected writeable)

MYSSIDMyOtherSSIDMyNeighbour

The lsquoconfigrsquo command is used to manipulate these configurations as is fairly self-explanatory

OVMS config list Show configuration parametersinstancesrm Remove parameterinstanceset Set parameterinstance=value

You can add new instances to parameters simply by setting them

Beginning with firmware release 32009 a dedicated configuration section usr is provided for plugins Take care toprefix all instances introduced by a unique plugin name so your plugin can nicely coexist with others

27 WiFi Networking

The OVMS WiFi system is based on the ESP32 integrated WiFi transceiver It uses and provides WiFi protocols80211 bgn and WPA2 authentication The current hardware can only use 24 GHz frequency bands

The WiFi antenna is built into the ESP32 module (PCB antenna) Itrsquos possible to replace that by an external antennabut yoursquoll need electronics knowledge and SMD soldering skills amp equipment

271 Client amp Access Point Modes

The OVMS WiFi network can be configured as a client (connecting to existing WiFi networks) andor access point(providing itrsquos own private WiFi network) Both modes can be run simultaneously which is the recommended defaultThat way you can always connect to your module via WiFi

OVMS wifi statusPower onMode Access-Point + Client mode

STA SSID WLAN-214677 (-787 dBm) [scanning]MAC 30aea45fe7ecIP 19216821022552552550GW 19216821AP 7cff4d152f86

AP SSID DEX106EMAC 30aea45fe7edIP 19216841AP Stations 0

In client mode the module can connect to a fixed network or automatically scan all channels for known networks toconnect to (ldquoscanning moderdquo) Scanning mode is configured by enabling client mode without a specific client SSID

The module will normally receive an IP address gateway and DNS from the WiFi access point by DHCP See belowon how to connect with a manual static IP setup

36 Chapter 2 User Guide

Open Vehicles

In access point mode the module provides access for other WiFi devices on a private network with the IP subnet1921684024 The modulersquos IP address on this network is 19216841 The module does not provide aDNS or routing to a public WiFi or GSM network on this subnet

You can define multiple AP networks but only one can be active at a time

Use the wifi mode command to manually set the mode use the auto start configuration to configure your defaultmode and networks

Note The module cannot act as a mobile hotspot ie provide access to the internet via itrsquos modem connectionThatrsquos in part due to security considerations and in part due to hardware limitations If you need this considerinstalling a dedicated mobile hotspot and using that one via WiFi instead of the modem for the modulersquos internetaccess (you wonrsquot need the modem in this setup)

272 Scanning for Networks

To manually scan your environment for available WiFi networks do a wifi scan

OVMS wifi scanScanning for WIFI Access Points

AP SSID MAC ADDRESS CHAN RSSI AUTHENTICATION================================ ================= ==== ==== ==============WLAN-214677 7cff4d152f86 1 -83 WPA2_PSKTelekom_FON 78dd1209dcbe 11 -84 OPENWLAN-184248 78dd1209dcbc 11 -85 WPA2_PSK===========================================================================Scan complete 3 access point(s) found

This can also be done in the web UIrsquos WiFi client network configuration page by clicking on the Select button

After the module lost connection to a network a scan is performed automatically every 10 seconds until a new con-nection can be established If yoursquod like to see the background scans and results in the log enable log level verbosefor component esp32wifi

Scan Troubleshooting

If the module doesnrsquot find your access point or can only see it occasionally in the scan results you may need to raiseyour scan times This has been observed on some older Android hotspots

By default the module will scan each channel for 120 milliseconds To raise that set your scan time in millisecondsusing the config command like this eg to 200 milliseconds

OVMS config set network wifiscantmin 200

200 milliseconds have been reported to solve the Android hotspot issue In addition to the tmin configuration youmay need to allow more time looking for further access points after finding the first one Do so by setting tmax eg

OVMS config set network wifiscantmax 300

Note that every increase will increase the time a full scan takes so donrsquot set too high values Too high values mayresult in connection drops on the AP network of the module

27 WiFi Networking 37

Open Vehicles

273 WiFi Signal Quality

Note For best performance yoursquoll need a signal level of -85 dBm or higher

bull Open the web status page the Wifi signal level can be monitored in the ldquoLiverdquo box

bull Try moving turning tilting your router ndash centimeters can make a huge difference After each move step backfrom the router and watch how the signal develops

bull Try switching to another Wifi channel (router configuration)

bull Try adding a repeater half way from the router to the car

The module monitors the WiFi client signal quality and drops a WiFi connection (switches to modem if available) if itbecomes too bad The WiFi connection will be kept active and monitored and as the signal recovers the module willautomatically reconnect to the AP

The default threshold is to stop using the connection if it drops below -89 dBm A connection is assumed to be usableif the signal is above -87 dBm

Depending on your WiFi environment the WiFi connection may still be usable at lower signal levels but it normallywill need stable levels above -87 dBm

To tweak the thresholds use the web UI WiFi configuration or change the following configuration variables

OVMS config set network wifisqgood -870OVMS config set network wifisqbad -890

274 WiFi Mesh Configuration

In normal operation the module will try to stick to an established connection as long as possible If signal qualitydrops it will switch to the modem connection but monitor the WiFi signal and reassociate to the current AP if possible

If using a mesh network you may want to force scanning for a better mesh AP as soon as the signal drops below theldquobadrdquo threshold To do so set the network configuration wifibadreconnect to true either using the web UIor by doing

OVMS config set network wifibadreconnect yes

With this the module will perform a full WiFi reconnect cycle as soon as the signal becomes bad

This is meant for the car moving between cells of your mesh network eg if the first cell is checked in at your gatebut a much better cell becomes available in your garage car port It should not be enabled if your Wifi signal isgenerally poor as that will cause many disconnects amp reconnects

275 Static IP SSID Configuration

To connect with a static client address instead of using DHCP use the wifi ip static command

OVMS wifi ip static [ltipgt ltsubnetgt ltgatewaygt]

The gateway will also be used as the DNS

To configure persistent static details for a known SSID set these using the following configuration syntax

38 Chapter 2 User Guide

Open Vehicles

OVMS config set wifissid ltssidgtovmsstaticip ltipgtltsubnetgtltgatewaygt

You can also force connection to a specific AP by itrsquos MAC address ldquoBSSIDrdquo in WiFi terms To do so you need tosupply the MAC address as a second argument to the wifi mode client or as the third argument to the wifimode apclient command

OVMS wifi mode client ltssidgt ltbssidgt

OVMS wifi mode apclient ltapssidgt ltssidgt ltbssidgt

This currently needs manual activation by command Hint use a script for example bound to a location

276 AP Bandwidth Configuration

In normal operation the default AP bandwidth is set to 20Mhz to reduce interference and improve the signal quality Ifa wider 40Mhz bandwidth is preferred eg for high throughput logging set the network configuration wifiapbwwith the command

OVMS config set network wifiapbw 40

Once the parameter is set the module will require rebooting to take effect The default bandwidth can be restored byeither removing the parameter or setting it to 20

28 Virtual File System (VFS)

OVMS includes a Virtual File System (VFS) used to unify all storage in the system The primary configuration andscripting storage is mounted as lsquostorersquo and the SD card as lsquosdrsquo A lsquovfsrsquo set of commands is provided for basicmanipulation of these stores

OVMS vfs append VFS Append a line to a filecat VFS Display a filecp VFS Copy a fileedit VFS Edit a filels VFS Directory Listingmkdir VFS Create a directorymv VFS Rename a filerm VFS Delete a filermdir VFS Delete a directorystat VFS Status of a filetail VFS Output tail of a file

Please take care This is a very small microcontroller based system with limited storage The store area should onlybe used for storage of configurations and small scripts The sd SD CARD area is more flexibly and can be used forstoring of configuration logs firmware images etc

281 Network Access

Network access to the VFS is available via SCP or through the web server

SCP can access the whole file system and is readwrite

28 Virtual File System (VFS) 39

Open Vehicles

copy a new firmware to the sd card on an OVMS named leaf in my ssh configscp buildovms3bin leafsddev_ovms3bin

copy a config backup from OVMS named leaf to my local directoryscp leafsdbackupcfg-2019-12-05zip

In the upload example the firmware can then be loaded with the OTA flash vfs command

The web server offers read access rooted at the sd card An example retrieving that same config file from the SCPexample would look like

httpleaf-abrlocalbackupcfg-2019-12-05zip

29 Metrics

Metrics are at the heart of the OVMS v3 system They are strongly typed named parameters with values in specificunits (and able to be automatically converted to other units) For example a metric to record the motor temperaturemay be an integer in Celsius units and may be convertible to Fahrenheit

The full list of metrics available can be shown

OVMS metrics listmfreeram 4232852mhardware OVMS WIFI BLE BT cores=2 rev=ESP321mmonotonic 3568Secvplatitude 222809vplongitude 114161vpodometer 100000Kmvpsatcount 12vpspeed 0Kphvptrip 0Kmvtalert 0001vthealth 95939674vtpressure 2068432164832757917579kPavttemp 33333438degCvtype DEMO

You can filter the metrics list output for names matching a given substring for example metrics listvolt will show all voltage related metrics

A base OVMS v3 system has more than 100 metrics available (see below) and vehicle modules can add more for theirown uses (see vehicle sections)

In general vehicle modules (and some other system components) are responsible for updating the metrics and serverconnections read those metrics reformat them and send them on to servers and Apps (for eventual display to the user)Status commands (such as STAT) also read these metrics and display them in user-friendly forms

OVMS statNot chargingSOC 500Ideal range 200KmEst range 160KmODO 1000000KmCAC 1600AhSOH 100

40 Chapter 2 User Guide

Open Vehicles

For developer use there are also some other metric commands used to manually modify a metricrsquos value (for testingand simulation purposes) and trace changes

OVMS metrics list Show all metricspersist Show persistent metrics infoset Set the value of a metrictrace METRIC trace framework

Some metrics are presistent across warm reboots This prevents values such as SOC from being lost when firmware isupdated (or in the event of a crash) You can display these with metrics list -p and view general informationabout presistent metrics with metrics persist

291 Standard Metrics

Metric name Example value Descriptionmfreeram 3275588 Total amount of free RAM in bytesmhardware OVMS WIFI BLE BT Base module hardware infommonotonic 49607Sec Uptime in secondsmnetmdmiccid 89490240001766080167 SIM ICCIDmnetmdmmodel 35316B09SIM5360E Modem module hardware infomnetmdmnetwork congstar Current GSM network providermnetmdmsq -101dBm and signal qualitymnetprovider WLAN-214677 Current primary network providermnetsq -79dBm signal qualitymnettype wifi and type (nonemodemwifi)mnetwifinetwork WLAN-214677 Current Wifi network SSIDmnetwifisq -791dBm and signal qualitymserial Reserved for module serial nomtasks 20 Task count (use module tasks to list)mtimeutc 1572590910Sec UTC time in secondsmversion 32005-155-g3133466f Firmware versionmegpioinput 012345679 EGPIO input port state (ports 0 9 present=high)megpiomonitor 89 EGPIO input monitoring portsmegpiooutput 45679 EGPIO output port statesv2connected yes yes = V2 (MP) server connectedsv2peers 1 V2 clients connectedsv3connected yes = V3 (MQTT) server connectedsv3peers V3 clients connectedvb12vcurrent 0A Auxiliary 12V battery momentary currentvb12vvoltage 1229V Auxiliary 12V battery momentary voltagevb12vvoltagealert yes = auxiliary battery under voltage alertvb12vvoltageref 123V Auxiliary 12V battery reference voltagevbctemp 1313 13degC Cell temperaturesvbctempalert 00 0 Cell temperature deviation alert level [0=normal 1=warning 2=alert]vbctempdevmax 143086 -129degC Cell maximum temperature deviation observedvbctempmax 1918 17degC Cell maximum temperaturesvbctempmin 1312 12degC Cell minimum temperaturesvbcvoltage 41054095 4105V Cell voltagesvbcvoltagealert 00 0 Cell voltage deviation alert level [0=normal 1=warning 2=alert]vbcvoltagedevmax 00096-00104 00125V Cell maximum voltage deviation observed

Continued on next page

29 Metrics 41

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvbcvoltagemax 41354125 414V Cell maximum voltagesvbcvoltagemin 38753865 388V Cell minimum voltagesvbcac 907796Ah Calculated battery pack capacityvbconsumption 0Whkm Main battery momentary consumptionvbcoulombrecd 475386Ah Main battery coulomb recovered on tripchargevbcoulombrecdtotal 9475386Ah Main battery coulomb recovered total (life time)vbcoulombused 0406013Ah Main battery coulomb used on tripvbcoulombusedtotal 835406013Ah Main battery coulomb used total (life time)vbcurrent 0A Main battery momentary current (output=positive)vbenergyrecd 269691kWh Main battery energy recovered on tripchargevbenergyrecdtotal 321269691kWh Main battery energy recovered total (life time)vbenergyused 00209496kWh Main battery energy used on tripvbenergyusedtotal 31770209496kWh Main battery energy used total (life time)vbhealth General textual description of battery healthvbplevelavg 95897 Cell level - pack averagevbplevelmax 9641 Cell level - strongest cell in packvbplevelmin 94871 Cell level - weakest cell in packvbplevelstddev 0548 Cell level - pack standard deviationvbptempavg 13degC Cell temperature - pack averagevbptempmax 13degC Cell temperature - warmest cell in packvbptempmin 13degC Cell temperature - coldest cell in packvbptempstddev 0degC Cell temperature - current standard deviationvbptempstddevmax 073degC Cell temperature - maximum standard deviation observedvbpvoltageavg 41V Cell voltage - pack averagevbpvoltagegrad 00032V Cell voltage - gradient of current seriesvbpvoltagemax 4105V Cell voltage - strongest cell in packvbpvoltagemin 409V Cell voltage - weakest cell in packvbpvoltagestddev 000535V Cell voltage - current standard deviationvbpvoltagestddevmax 000783V Cell voltage - maximum standard deviation observedvbpower 0kW Main battery momentary power (output=positive)vbrangeest 99km Estimated rangevbrangefull 508km Ideal range at 100 SOC amp current conditionsvbrangeideal 48km Ideal rangevbrangespeed 216kmh Momentary ideal range gainloss (chargedischarge) speedvbsoc 963 State of chargevbsoh 85 State of healthvbtemp 13degC Main battery momentary temperaturevbvoltage 574V Main battery momentary voltagevc12vcurrent 78A Output current of DCDC-convertervc12vpower 123W Output power of DCDC-convertervc12vtemp 345degC Temperature of DCDC-convertervc12vvoltage 123V Output voltage of DCDC-convertervccharging no yes = currently chargingvcclimit 0A Maximum charger output currentvccurrent 125A Momentary charger output currentvcdurationfull 25Min Estimated time remaing for full chargevcdurationrange -1Min for sufficient rangevcdurationsoc 0Min for sufficient SOCvcefficiency 876 Momentary charger efficiency

Continued on next page

42 Chapter 2 User Guide

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvckwh 26969kWh Energy sum for running chargevckwhgrid 36969kWh Energy drawn from grid during running sessionvckwhgridtotal 25669kWh Energy drawn from grid total (life time)vclimitrange 0km Sufficient range limit for current chargevclimitsoc 80 Sufficient SOC limit for current chargevcmode standard standard range performance storagevcpilot no Pilot signal presentvcpower 125kW Momentary charger input powervcstate done charging topoff done prepare timerwait heating stoppedvcsubstate scheduledstop scheduledstart onrequest timerwait powerwait stopped interruptedvctemp 16degC Charger temperaturevctime 0Sec Duration of running chargevctimermode yes = timer enabledvctimerstart Time timer is due to start seconds since midnight UTCvctype undefined type1 type2 chademo roadster teslaus supercharger ccsvcvoltage 0V Momentary charger supply voltagevdcp yes yes = Charge port openvdfl yes = Front left door openvdfr yes = Front right door openvdhood yes = Hoodfrunk openvdrl yes = Rear left door openvdrr yes = Rear right door openvdtrunk yes = Trunk openvealarm yes = Alarm currently soundingveaux12v yes = 12V auxiliary system is on (base system awake)veawake no yes = Vehicle is fully awake (switched on by the user)vecconfig yes = ECUcontroller in configuration stateveclogin yes = Module logged in at ECUcontrollervecabintemp 20degC Cabin temperaturevecabinfan 100 Cabin fanvecabinsetpoint 24degC Cabin set pointvecabinintake fresh Cabin intake type (fresh recirc etc)vecabinvent feetface Cabin vent type (comma-separated list of feet face screen etc)vecharging12v no yes = 12V battery is chargingvecooling yes = Coolingvedrivemode 33882626 Active drive profile code (vehicle specific)vedrivetime 0Sec Seconds driving (turned on)vefootbrake 0 Brake pedal state []vegear Geardirection negative=reverse 0=neutralvehandbrake yes = Handbrake engagedveheadlights yes = Headlights onveheating yes = Heatingvehvac yes = HVAC activevelocked yes = Vehicle lockedveon no yes = Vehicle is in ldquoignitionrdquo state (drivable)veparktime 49608Sec Seconds parking (turned off)veregenbrake yes = Regenerative braking activeveservrange 12345km Distance to next scheduled maintenanceservice [km]veservtime 1572590910Sec Time of next scheduled maintenanceservice [Seconds]

Continued on next page

29 Metrics 43

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvetemp Ambient temperaturevethrottle 0 Drive pedal state []vevalet yes = Valet mode engagedvggenerating no True = currently delivering powervgclimit 0A Maximum generator input current (from battery)vgcurrent 125A Momentary generator input current (from battery)vgdurationempty 25Min Estimated time remaining for full dischargevgdurationrange -1Min for range limitvgdurationsoc 0Min for SOC limitvgefficiency 876 Momentary generator efficiencyvgkwh 26969kWh Energy sum generated in the running sessionvgkwhgrid 36969kWh Energy sent to grid during running sessionvgkwhgridtotal 25669kWh Energy sent to grid totalvglimitrange 0km Minimum range limit for generator modevglimitsoc 80 Minimum SOC limit for generator modevgmode standard Generator mode (TBD)vgpilot no Pilot signal presentvgpower 125kW Momentary generator output powervgstate done Generator state (TBD)vgsubstate Generator substate (TBD)vgtemp 16degC Generator temperaturevgtime 0Sec Duration of generator runningvgtimermode false True if generator timer enabledvgtimerstart Time generator is due to startvgtype Connection type (chademo ccs )vgvoltage 0V Momentary generator output voltagevitemp Inverter temperaturevipower 427kW Momentary inverter motor power (output=positive)viefficiency 982 Momentary inverter efficiencyvmrpm Motor speed (RPM)vmtemp 0degC Motor temperaturevpacceleration 0ms2 Vehicle accelerationvpaltitude 3278m GPS altitudevpdirection 312deg GPS directionvpgpshdop 13 GPS horizontal dilution of precision (smaller=better)vpgpslock no yes = has GPS satellite lockvpgpsmode AA ltGPSgtltGLONASSgt NADE (NoneAutonomousDifferentialEstimated)vpgpsspeed 0kmh GPS speed over groundvplatitude 513023 GPS latitudevplocation Home Name of current location if definedvplongitude 739006 GPS longitudevpodometer 579131km Vehicle odometervpsatcount 8 GPS satellite count in viewvpspeed 0kmh Vehicle speedvptrip 0km Trip odometervtalert 0001 TPMS tyre alert levels [0=normal 1=warning 2=alert]vthealth 95939674 TPMS tyre health statesvtpressure 20682164 kPa TPMS tyre pressuresvttemp 33333438degC TPMS tyre temperatures

Continued on next page

44 Chapter 2 User Guide

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvtype RT Vehicle type codevvin VF1ACVYB012345678 Vehicle identification number

210 Over The Air (OTA) Updates

OVMS v3 includes 16MB flash storage This is partition as

4MB for factory application image (factory)4MB for the first OTA application image (ota_0)4MB for a second OTA application image (ota_1)1MB for store configuration and scripting storageThe remainder for bootloader generic non-volatile storage and other data

In general the factory application firmware is stored in flash at the factory during module production That firmwareis never changed on production modules and is always kept as a failover backup

That leaves two firmwares for Over The Air (OTA) updates If the currently running firmware is the factory one anOTA updated firmware can be written to either of the OTA partitions If the current running firmware is ota_0 thenany new OTA updates will be written to ota_1 (and similarly if ota_1 is currently running then new OTA updates willbe written to ota_0) In this way the currently running firmware is never modified and is always available as a failoverbackup

You can check the status of OTA with the lsquoota statusrsquo command

OVMS ota statusFirmware 31003-2-g7ea18b4-dirtyfactorymain (build idf v31-dev-453-rarr˓g0f978bcb Apr 7 2018 162657)Server Available 31003Running partition factoryBoot partition factory

That is showing the currently running firmware as a custom image v31003-2-g7ea18b4-dirty running in factorypartition The running currently running partition is factory and the next time the system is booted it will run fromfactory as well

As a convenience if there is currently active wifi connectivity a network lookup will be performed and the currentlyavailable firmware version on the server will be shown In this case that is the standard 31003 release (as shown inthe lsquoServer Availablersquo line)

If we wanted to boot from ota_1 we can do this with lsquoota boot ota_1rsquo

OVMS ota boot ota_1Boot from ota_1 at 0x00810000 (size 0x00400000)

OVMS ota statusFirmware 31003-2-g7ea18b4-dirtyfactorymain (build idf v31-dev-453-rarr˓g0f978bcb Apr 7 2018 162657)Server Available 31003Running partition factoryBoot partition ota_1

If the bootloader fails to boot from the specified OTA firmware it will failover and boot from factory

We can flash firmware to OTA either from a file on VFS (normally sd) or over the Internet (via http) Letrsquos try asimple OTA update over HTTP

210 Over The Air (OTA) Updates 45

Open Vehicles

OVMS ota flash httpCurrent running partition is factoryTarget partition is ota_0Download firmware from apiopenvehiclescomfirmwareotav31mainovms3bin to ota_0Expected file size is 2100352Preparing flash partitionDownloading (100361 bytes so far)Downloading (200369 bytes so far)Downloading (300577 bytes so far)Downloading (1903977 bytes so far)Downloading (2004185 bytes so far)Download complete (at 2100352 bytes)Setting boot partitionOTA flash was successful

Flashed 2100352 bytes from apiopenvehiclescomfirmwareotav31mainovms3binNext boot will be from ota_0

OVMS ota statusFirmware 31003-2-g7ea18b4-dirtyfactorymain (build idf v31-dev-453-rarr˓g0f978bcb Apr 7 2018 162657)Server Available 31003Running partition factoryBoot partition ota_0

Rebooting now (with lsquomodule resetrsquo) would boot from the new ota_0 partition firmware

OVMS ota statusFirmware 31003ota_0main (build idf v31-dev-453-g0f978bcb Apr 7 2018rarr˓131119)Server Available 31003Running partition ota_0Boot partition ota_0

211 Boot Status

OVMS maintains a record of the reason for each boot in RAM that survives a reboot It can show you how long themodule has been running for and the reason for the last reboot

OVMS boot statusLast boot was 2244 second(s) ago

This is reset 9 since last power cycleDetected boot reason SoftResetCrash counters 0 total 0 earlyCPU0 boot reason was 12CPU1 boot reason was 12

If an unexpected (not lsquomodule resetrsquo) reboot occurs within the first 10 seconds of startup (usually during the boot-timeauto-loading of modules scripts etc) the crash counters are incremented If those crash counters reach 5 (without aclean reset in between) then the auto-loading of modules is disabled for the 6th boot

In case of a crash the output will also contain additional debug information ie

Last crash abort() was called on core 1Backtrace

(continues on next page)

46 Chapter 2 User Guide

Open Vehicles

(continued from previous page)

0x40092ccc 0x40092ec7 0x400dbf1b 0x40176ca9 0x40176c6d 0x400eebd9 0x4013aed90x4013b538 0x40139c15 0x40139df9 0x4013a701 0x4013a731

If the module can access the V2 server after the crash reboot it will also store this information along with the crashcounters in the server table ldquo-OVM-DebugCrashrdquo which will be kept on the server for 30 days

Please include this info when sending a bug report along with the output of ldquoota statusrdquo and ndash if available ndash any logfiles capturing the crash event (see Logging to SD CARD) If you can repeat the crash please try to capture a log atldquolog level verboserdquo

212 Events

Internally OVMS raises events whenever significant events occur An event is a lightweight message of a name plusoptionally associated internal binary data Event names are top-down structured (so can be filtered by prefix) andsufficient to identify the source and type of the event Individual vehicle types may also issue their own events andcustom user events are also possible

To bind a script to an event save the script in directory storeeventslteventnamegt (hint directories canbe created using the web UI editor) Whenever events are triggered all the scripts in the corresponding storeeventslteventnamegt directory are executed Event scripts are executed in alphanumerical order of their namesGood practice is to prefix script names with 2-3 digit numbers in steps of 10 or 100 (ie first script named 50-)so new scripts can easily be integrated at a specific place If the event script is written in Javascript be sure to add thesuffix js to the name Other names will be executed using the standard command interpreter

If you want to introduce a custom event (eg for a plugin) prefix the event name by usrltpluginnamegtfollowed by the event purpose Example Foglight

Be aware events are processed in series from a queue so depending on the system load and the list of registeredevent listeners there may be some delay from event generation to eg a script execution

2121 Commands

bull event list [ltkeygt] ndash Show registered listeners for all or events matching a key (part of the name)

bull event trace lton|offgt ndash Enabledisable logging of events at the ldquoinfordquo level Without tracing events arealso logged but at the ldquodebugrdquo level Ticker events are never logged

bull event raise [-dltdelay_msgt] lteventgt ndash Manually raise an event optionally with a delay You canraise any event you like but you shouldnrsquot raise system events without good knowledge of their effects

2122 Standard Events

Event Data Purposeappconnected One or more remote Apps have connectedappdisconnected No remote Apps are currently connectedcanopennodeemcy lteventgt CANopen node emergency receivedcanopennodestate lteventgt CANopen node state change receivedcanopenworkerstart ltworkergt CANopen bus worker task startedcanopenworkerstop ltworkergt CANopen bus worker task stoppingclockHHMM Per-minute local time hour HH minute MM

Continued on next page

212 Events 47

Open Vehicles

Table 2 ndash continued from previous pageEvent Data PurposeclockdayN Per-day local time day N (0=Sun 6=Sat)configchanged Configuration has changedconfigmounted Configuration is mounted and availableconfigunmounted Configuration is unmounted and unavailableegpioinputltportgtltstategt EGPIO input port change (port=0 9 state=highlow)egpiooutputltportgtltstategt EGPIO output port change (port=0 9 state=highlow)gpslockacquired GPS lock has been acquiredgpslocklost GPS lock has been losthousekeepinginit Housekeeping has initialisedlocationalertflatbedmoved GPS movement of parked vehicle detectedlocationenterltnamegt ltnamegt The specified geolocation has been enteredlocationleaveltnamegt ltnamegt The specified geolcation has been leftnetworkdown All networks are downnetworkinterfacechange Network interface change detectednetworkinterfaceup Network connection is establishednetworkmgrinit Network manager has initialisednetworkmgrstop Network managed has been stoppednetworkmodemdown Modem network is downnetworkmodemup Modem network is upnetworkreconfigured Networking has been reconfigurednetworkup One or more networks are upnetworkwifidown WIFI network is downnetworkwifistabad WIFI client has bad signal levelnetworkwifistagood WIFI client has good signal levelnetworkwifiup WIFI network is upnotifylttypegtltsubtypegt An info alert error notification is sentretoolsclearedall RE frame log has been clearedretoolsclearedchanged RE frame change flags clearedretoolscleareddiscovered RE frame discovery flags clearedretoolsmodeanalyse RE switched to analysis moderetoolsmodediscover RE switched to discovery moderetoolsstarted RE (reverse engineering) toolkit startedretoolsstopped RE toolkit stoppedretoolspidscanstart RE OBD2 PID scan startedretoolspidscanstop RE OBD2 PID scan stoppedretoolspidscandone RE OBD2 PID scan completedsdinsert The SD card has just been insertedsdmounted The SD card is mounted and ready to usesdremove The SD card has just been removedsdunmounted The SD card has completed unmountingsdunmounting The SD card is currently unmountingserverv2authenticating V2 server connection is authenticatingserverv2connected V2 server connection established onlineserverv2connecting V2 server connection in progressserverv2connectwait V2 server is pausing before connectionserverv2disconnected V2 server connection has been lostserverv2stopped V2 server has been stoppedserverv2waitnetwork V2 server connection is waiting for networkserverv2waitreconnect V2 server is pausing before re-connection

Continued on next page

48 Chapter 2 User Guide

Open Vehicles

Table 2 ndash continued from previous pageEvent Data Purposeserverv3authenticating V3 server connection is authenticatingserverv3connected V3 server connection established onlineserverv3connecting V3 server connection in progressserverv3connectwait V3 server is pausing before connectionserverv3disconnected V3 server connection has been lostserverv3stopped V3 server has been stoppedserverv3waitnetwork V3 server connection is waiting for networkserverv3waitreconnect V3 server is pausing before re-connectionserverwebsocketclosed ltcntgt Web server lost a websocket clientserverwebsocketopened ltcntgt Web server has a new websocket clientsystemmodemdown Modem has been disconnectedsystemmodemgotgps Modem GPS has obtained locksystemmodemgotip Modem received IP address from DATAsystemmodeminstalled Modem type has been identified driver installedsystemmodemlostgps Modem GPS has lost locksystemmodemmuxstart Modem MUX has startedsystemmodemnetdeepsleep Modem is deep sleeping DATA networksystemmodemnethold Modem is pausing DATA networksystemmodemnetloss Modem has lost DATA networksystemmodemnetsleep Modem is sleeping DATA networksystemmodemnetstart Modem is starting DATA networksystemmodemnetwait Modem is pausing before starting DATAsystemmodempoweredon Modem is powered onsystemmodempoweringon Modem is powering onsystemmodemreceivedussd ltussdgt A USSD message has been receivedsystemmodemstop Modem has been shut downsystemshutdown System has been shut downsystemshuttingdown System is shutting downsystemstart System is startingsystemvfsfilechanged ltpathgt VFS file updated (note only sent on some file changes)systemwifiapstaconnected WiFi access point got a new client connectionsystemwifiapstadisconnected WiFi access point lost a client connectionsystemwifiapstaipassigned WiFi access point assigned an IP address to a clientsystemwifiapstart WiFi access point mode startingsystemwifiapstop WiFi access point mode stoppingsystemwifidown WiFi is shutting downsystemwifiscandone WiFi scan has been finishedsystemwifistaconnected WiFi client is connected to a stationsystemwifistadisconnected WiFi client has disconnected from a stationsystemwifistagotip WiFi client got an IP addresssystemwifistalostip WiFi client lost itrsquos IP addresssystemwifistastart WiFi client mode startingticker1 One second has passed since last tickerticker10 Ten seconds have passedticker300 Five minutes have passedticker3600 One hour has passedticker60 One minute has passedticker600 Ten minutes have passedvehiclealarmoff Vehicle alarm has been disarmed

Continued on next page

212 Events 49

Open Vehicles

Table 2 ndash continued from previous pageEvent Data Purposevehiclealarmon Vehicle alarm has been armedvehiclealert12voff 12V system voltage has recoveredvehiclealert12von 12V system voltage is below alert thresholdvehiclealertbms BMS cellpack voltstemps exceeded thresholdsvehicleasleep Vehicle systems are asleepvehicleawake Vehicle systems are awakevehicleaux12von Vehicle 12V auxiliary system is on (base system awake)vehicleaux12voff Vehicle 12V auxiliary system is offvehiclecharge12vstart Vehicle 12V battery is chargingvehiclecharge12vstop Vehicle 12V battery has stopped chargingvehiclechargefinished Vehicle charge has completed normallyvehiclechargemode ltmodegt Vehicle charge mode has been setvehiclechargepilotoff Vehicle charge pilot signal is offvehiclechargepiloton Vehicle charge pilot signal is onvehiclechargeprepare Vehicle is preparing to chargevehiclechargestart Vehicle has started to chargevehiclechargestate ltstategt Vehicle charge state has changedvehiclechargestop Vehicle has stopped chargingvehiclechargetimermodeoff Vehicle charge timer mode has been switched offvehiclechargetimermodeon Vehicle charge timer mode has been switched onvehicledrivemodeltngt Vehicle drivemode has been set to profile ltngt (vehicle specific)vehiclegearforward Vehicle has been put in forward gearvehiclegearneutral Vehicle has been put in neutral gearvehiclegearreverse Vehicle has been put in reverse gearvehicleheadlightsoff Vehicle headlights are offvehicleheadlightson Vehicle headlights are onvehiclelocked Vehicle has been lockedvehicleoff Vehicle has been switched offvehicleon Vehicle has been switched onvehiclerequiregps A vehicle has indicated it requires GPSvehiclerequiregpstime A vehicle has indicated it requires GPS timevehicletypecleared Vehicle module has been unloadedvehicletypeset lttypegt Vehicle module has been loadedvehicleunlocked Vehicle has been unlockedvehiclevaletoff Vehicle valet mode deactivatedvehiclevaleton Vehicle valet mode activated

213 Geofenced Locations

This section of the manual is still under development

214 Notifications

Notifications can be simple text messages or transport structured data To distinguish by their purpose and originnotifications have a type and a subtype

Notifications are sent by the module via the available communication channels (clientserver connections) If a channelis temporarily down (eg due to a connection loss) the notifications for that channel will be kept in memory until thechannel is available again (Note this message queue does not survive a crash or reboot of the module)

50 Chapter 2 User Guide

Open Vehicles

Channels process notifications differently depending on the way they work For example a v2 server will forward textnotifications as push messages to connected smart phones and email readers a v3 server will publish them under anMQTT topic and the webserver will display the message as a modal dialog See the respective manual sections fordetails

Notification types currently defined

bull info ndash informational text messages

bull alert ndash alert text messages

bull error ndash error code messages

bull data ndash historical data records usually CSV formatted

bull stream ndash live data streaming (high bandwidth) usually JSON formatted

The standard subtypes used are listed below these can be used to filter messages Vehicles may introduce customnotifications and replace standard notifications see the respective user guide section for details

Subtypes by convention are given in lower case with dots lsquorsquordquo as structural separators

Notification channels currently defined

bull ovmsv2 ndash server v2 connection

bull ovmsv3 ndash server v3 connection

bull ovmsweb ndash websocket connections

bull pushover ndash pushover text messaging service

Channels may have multiple active instances (ldquoreadersrdquo) for example you can open multiple websocket connectionsChannels may exclude notification types Currently stream records are only supported on a websocket connectionall other types are supported on all channels

Use notify status to see the currently registered channels (ldquoreadersrdquo) Example

OVMS notify statusNotification system has 3 readers registered

pushover(1) verbosity=1024ovmsv2(2) verbosity=1024ovmsweb(3) verbosity=65535

Notify typesalert 0 entriesdata 0 entrieserror 0 entriesinfo 0 entriesstream 0 entries

The channelrsquos ldquoverbosityrdquo defines the supported maximum length of a textual notification message on that channelNotification senders should honor this but not all may do so If messages exceed this limit they may be truncated

2141 Sending notifications

You can send custom notifications from the shell or command scripts by using the notify raise command Thecommand can send the output of another command an error code (implies type error) or any text you enter Forexample to send a custom text message do

OVMS notify raise text info usrantonwelcome Hello wonderful person

214 Notifications 51

Open Vehicles

In this case the type would be info and the subtype usrantonwelcome The type must match one of thedefined types the subtype can be chosen arbitrarily Please use a unique usr prefix for custom notifications to avoidcollisions

To send a battery status command result do

OVMS notify raise command info batterystatus stat

To send notifications from Duktape scripts use the API call OvmsNotifyRaise()

When a text (infoalert) or error notification is sent (ie has at least one listening channel eg pushover) anevent is raised once when the notification is queued The event will be named notifylttypegtltsubtypegt Forexample the second example above would come with an event notifyinfobatterystatus

2142 Suppress notifications

You can filter the channels to be used for notifications by their subtypes By default no subtypes are filtered on anychannel so all notifications are sent to all clients

To disable (suppress) notifications create a config entry based on the respective subtype that lists the channels toinclude or exclude

OVMS config set notify ltsubtypegt ltchannelsgt

ltchannelsgt options are

a) explicit inclusion eg ovmsv2pushover (only enable these)

b) explicit exclusion eg -ovmsv3-ovmsweb (only disable these)

c) - (dash) to disable all

d) empty to enable all

Example to disable the OTA update notifications on all channels do

OVMS config set notify otaupdate -

52 Chapter 2 User Guide

Open Vehicles

2143 Standard notifications

Type Subtype Purpose Contentalert alarmsounding Vehicle alarm is soundingalert alarmstopped Vehicle alarm has stoppedalert batt12valert 12V Battery criticalalert batt12vrecovered 12V Battery restoredalert battbmsalert Battery packcell alert (critical voltagetemperature deviation)alert battsocalert Battery SOC criticalinfo chargedone stat on charge finishedinfo chargestarted stat on start of chargeinfo chargetoppingoff stat on start of topping off chargephaseinfo chargestopped stat on planned charge stopalert chargestopped stat on unplanned charge stopdata debugcrash Transmit crash backtraces (rarr -OVM-DebugCrash)data debugtasks Transmit task statistics (rarr -OVM-DebugTasks)info drivetripreport Trip driving statistics (see Trip report)alert flatbedmoved Vehicle is being transported while parked - possible theftflatbedinfo heatingstarted stat on start of heating (battery)data loggrid Grid (chargegenerator) history log (see below) (rarr -LOG-Grid)data logtrip Trip history log (see below) (rarr -LOG-Trip)alert modemno_pincode No PIN code for SIM card configuredalert modemwrongpincode Wrong pin codeinfo otaupdate New firmware availabledownloadedinstalledinfo pushover Connection failure message delivery responsestream retoolslistupdate RE toolkit CAN frame list updatestream retoolsstatus RE toolkit general status updateinfo valetdisabled Valet mode disabledinfo valetenabled Valet mode enabledalert valethood Vehicle hood opened while in valet modealert valettrunk Vehicle trunk opened while in valet modealert vehicleidle Vehicle is idling stopped turned on

2144 Grid history log

The grid history log can be used as a source for long term statistics on your charges and typical energy usages and tocalculate your vehicle energy costs

Log entries are created on each change of the charge or generator state (vcstate vgstate)

You need to enable this log explicitly by configuring a storage time via config param notify loggridstoretime (in days) or via the web configuration page Set to 0empty to disable the log Already stored logentries will be kept on the server until expiry or manual deletion

Note the stability of the total energy counters included in this log depends on their source and persistence on thevehicle andor module If they are kept on the module they may lose their values on a power outage

bull Notification subtype loggrid

bull History record type -LOG-Grid

bull Format CSV

bull Archive time config notify loggridstoretime (days)

214 Notifications 53

Open Vehicles

bull Fieldscolumns

ndash pos_gpslock

ndash pos_latitude

ndash pos_longitude

ndash pos_altitude

ndash pos_location

ndash charge_type

ndash charge_state

ndash charge_substate

ndash charge_mode

ndash charge_climit

ndash charge_limit_range

ndash charge_limit_soc

ndash gen_type

ndash gen_state

ndash gen_substate

ndash gen_mode

ndash gen_climit

ndash gen_limit_range

ndash gen_limit_soc

ndash charge_time

ndash charge_kwh

ndash charge_kwh_grid

ndash charge_kwh_grid_total

ndash gen_time

ndash gen_kwh

ndash gen_kwh_grid

ndash gen_kwh_grid_total

ndash bat_soc

ndash bat_range_est

ndash bat_range_ideal

ndash bat_range_full

ndash bat_voltage

ndash bat_temp

ndash charge_temp

ndash charge_12v_temp

54 Chapter 2 User Guide

Open Vehicles

ndash env_temp

ndash env_cabintemp

ndash bat_soh

ndash bat_health

ndash bat_cac

ndash bat_energy_used_total

ndash bat_energy_recd_total

ndash bat_coulomb_used_total

ndash bat_coulomb_recd_total

2145 Trip history log

The trip history log can be used as a source for long term statistics on your trips and typical trip power usages as wellas your battery performance in different environmental conditions and degradation over time

Entries are created at the beginning and end of each ldquoignitionrdquo cycle (veon change) Configure a minimum triplength for logging by the config variable notify logtripminlength or via the web UI If your vehicle doesnot support the vptrip metric set the minimum trip length to 0

The log entry at the beginning of a trip is created to track non-driving SOC changes vampire drains and BMS SOCcorrections that occurred in between If yoursquore just interested in the actual drive results filter the records eg bypos_trip gt 01 or env_drivetime gt 10 (by default log entries will be created 3 seconds after the veonstate change)

You need to enable this log explicitly by configuring a storage time via config param notify logtripstoretime (in days) or via the web configuration page Set to 0empty to disable the log Already stored logentries will be kept on the server until expiry or manual deletion

bull Notification subtype logtrip

bull History record type -LOG-Trip

bull Format CSV

bull Archive time config notify logtripstoretime (days)

bull Fieldscolumns

ndash pos_gpslock

ndash pos_latitude

ndash pos_longitude

ndash pos_altitude

ndash pos_location

ndash pos_odometer

ndash pos_trip

ndash env_drivetime

ndash env_drivemode

ndash bat_soc

ndash bat_range_est

214 Notifications 55

Open Vehicles

ndash bat_range_ideal

ndash bat_range_full

ndash bat_energy_used

ndash bat_energy_recd

ndash bat_coulomb_used

ndash bat_coulomb_recd

ndash bat_soh

ndash bat_health

ndash bat_cac

ndash bat_energy_used_total

ndash bat_energy_recd_total

ndash bat_coulomb_used_total

ndash bat_coulomb_recd_total

ndash env_temp

ndash env_cabintemp

ndash bat_temp

ndash inv_temp

ndash mot_temp

ndash charge_12v_temp

ndash tpms_temp_min

ndash tpms_temp_max

ndash tpms_pressure_min

ndash tpms_pressure_max

ndash tpms_health_min

ndash tpms_health_max

2146 Trip report

The trip report outputs some core statistics of the current or most recent trip (drive cycle) It can be queried any timeusing the stat trip command or be configured to be sent automatically on turning the vehicle off

Use the web UI (Config rarr Notifications) or set config variable notify reporttripenable to yes andoptionally a minimum trip length in notify logtripminlength (defaults to 02 km) If your vehicle doesnot support the vptrip metric set the minimum trip length to 0

The statistics available depend on your vehicle type (ie metrics support of that vehicle adaption) Vehicles also mayoverride the report to provide custom statistics By default a full trip report will contain

bull Trip length

bull Average driving speed

bull Overall altitude difference (start to end point)

56 Chapter 2 User Guide

Open Vehicles

bull Energy consumption in Wh per kmMi

bull Recuperation percentage (in relation to energy used)

bull SOC difference amp new SOC

bull Estimated range difference amp new range

bull Average acceleration amp deceleration

The average driving speed is calculated only from speeds above 5 kph (3 mph) (to exclude slow speed rolling) andthe acceleration amp deceleration averages exclude values below 25 kphs (16 mphs) (constant speed cruising)

215 Time

This section of the manual is still under development

216 SSLTLS

Warning Letrsquos Encrypt root certificate expiration on September 30 2021

To prevent losing TLS connectivity with an LE secured server (like dexters-webde) with module firmwareversions 32016 or earlier you need to install the new root certificate manually Sorry for the inconvenience

See below Letrsquos Encrypt Root Certificate Update

2161 SSLTLS Trusted Certificate Authorities

A default minimal list of trusted certificate authorities (CA) is provided with the firmware you can see the currentloaded list with the tls trust list command

OVMS tls trust listAddTrust External CA Root length 15211521 byte certificate AddTrust External CA Root

cert version 3serial number 01issuer name C=SE O=AddTrust AB OU=AddTrust External TTP Network

rarr˓CN=AddTrust External CA Rootsubject name C=SE O=AddTrust AB OU=AddTrust External TTP Network

rarr˓CN=AddTrust External CA Rootissued on 2000-05-30 104838expires on 2020-05-30 104838signed using RSA with SHA1RSA key size 2048 bitsbasic constraints CA=truekey usage Key Cert Sign CRL Sign

If you want to add to this list you can place the PEM formatted root CA certificate in the storetrustedcadirectory on your config partition using the text editor Then reload the list with

OVMS tls trust reloadReloading SSLTLS trusted CA listSSLTLS has 4 trusted CAs using 5511 bytes of memory

215 Time 57

Open Vehicles

On boot the trusted Certificate Authorities provided in firmware and put in your storetrustedca directorywill be automatically loaded and made available

These trusted certificate authorities are used by the various module in the OVMS system when establishing SSLTLSconnections (in order to verify the certificate of the server being connected to)

2162 How to get the CA PEM for a Server

Download from CA

If you know the CA check their download section

Using a Browser

This only works for https servers

1 Open the website you want to access

2 Open the encryption info (eg Chrome lock icon at URL rarr show certificate)

3 Display the certificate chain (eg Chrome tab ldquoDetailsrdquo first element)

4 Select the last entry before the actual server certificate

5 Export the certificate in PEM format (usually the default)

6 Install the file contents as shown above

Using OpenSSL or GNU TLS CLI

This works for all servers and ports

openssl s_client -connect HOSTNAMEPORT -servername HOSTNAME -showcerts ltdevnull | sed -ne -BEGIN CERTIFICATE--END CERTIFICATE-p

or

gnutls-cli --print-cert --port PORT HOSTNAME ltdevnull | sed -ne -BEGIN CERTIFICATE--END CERTIFICATE-p

Substitute HOSTNAME and PORT accordingly eg https = port 443 The sed just strips the other info from theoutput and can be omitted to check for errors or details

There should be two certificates in the output look for BEGIN and END markers The first one is the server certificatethe second one the CA certificate Copy that second certificate into the editor take care to include the BEGIN andEND lines

2163 Letrsquos Encrypt Root Certificate Update

If running firmware version 32016 or earlier you need to install the new Letrsquos Encrypt root certificate (ldquoISRGRoot X1rdquo) manually to enable encrypted connections to servers secured by a Letrsquos Encrypt certificate

1 Save the certificate text shown below to file storetrustedcaisrgx1

2 Issue command tls trust reload or reboot the module

Certificate text

58 Chapter 2 User Guide

Open Vehicles

-----BEGIN CERTIFICATE-----MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2VhcmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygch77ct984kIxuPOZXoHj3dcKivVqbvYATyjb3miGbESTtrFjRQSa78f0uoxmyF+0TM8ukj13Xnfs7jEvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6UA5TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sWT8KOEUt+zwvo7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hmELNKjD+Jo2FR3qyHB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UCB5iPNgiV5+I3lg02dZ77DnKxHZu8AlJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUvKBds0pjBqAlkd25HN7rOrFleaJ1ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWnOlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTnjh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbwqHyGO0aoSCqI3Haadr8faqU9GYrOPNk3sgrDQoofb4hVC1CLQJ13hef4Y53CIrU7m2Ys6xt0nUW7vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEBwQEAwIBBjAPBgNVHRMBAf8EBTADAQHMB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkqhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaSV9lZLubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ3BebYhtF8GaV0nxvwuo77xPy9auJGpsMiuX1+mvoiBOv2XqkSsisRcOjKKNFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7UrTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l++sKAIuvtd7u+Nxe5AW0wdeRlN8NwdCjNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVcoyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui01lvh+wjChP4kqKOJ2qxq4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9Ut7y0Ff9yi0GE44Za4rF2LN9d11TPAmRGunUHBcnWEvgJBQl9nJEiU0ZsnvgcubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57demyPxgcYxneR44KJ4EBs+lVDR3veyJm+kXQ99b21+jh5Xos1AnX5iItreGCc=-----END CERTIFICATE-----

217 Scripting

2171 Command Scripts

Lists of commands can be entered into a script file and stored in the VFS for execution (in the storescriptsdirectory) These are called lsquocommand scriptsrsquo and are simple sequential lists of OVMS commands A commandscript can be executed with

OVMS ltscriptgtOVMS script run ltscriptgt

Command scripts can also be stored in the storeeventslteventnamegt directory structure Whenever eventsare triggered all the scripts in the corresponding storeeventslteventnamegt directory are executed Eventscripts are executed in alphanumerical order of their names Good practice is to prefix script names with 2-3 digitnumbers in steps of 10 or 100 (ie first script named 50-) so new scripts can easily be integrated at a specificplace

Output of background scripts without console association (eg event scripts) will be sent to the log with tag scriptat ldquoinfordquo level

Note that the developer building firmware can optionally set the OVMS_DEV_SDCARDSCRIPTS build flag If thatis set then the system will also check sdscripts and sdevents for scripts This should not be used forproduction builds as you could hack the system just by plugging in an SD card

217 Scripting 59

Open Vehicles

In addition to command scripts more sophisticated scripting capabilities may be enabled if the JavaScript environmentis enabled in the build This is discussed in the next section of this guide

2172 JavaScripting

OVMS v3 includes a powerful JavaScript engine In addition to the standard relatively fixed firmware flashed tothe module JavaScripting can be used to dynamically load script code to run alongside the standard firmware Thisjavascript code can respond to system events and perform background monitoring and other such tasks

The simplest way of running javascript is to place a piece of javascript code in the storescripts directory withthe file extension js Then the standard mechanism of running scripts can be employed

OVMS ltscriptjsgtOVMS script run ltscriptjsgt

Short javascript snippets can also be directly evaluated with

OVMS script eval ltcodegt

Such javascript code can also be placed in the storeeventslteventnamegt directories to be automaticallyexecuted when the specified event is triggered The script file name suffix must be js to run the Javascript interpreter

Note The scripting engine used is Duktape Duktape supports ECMAScript E5E51 with some additions from laterECMAScript standards Duktape does not emulate a browser environment so you donrsquot have window or documentobjects etc just core Javascript plus the OVMS API and plugins

Duktape builtin objects and functions httpsduktapeorgguidehtmlduktapebuiltins

2173 Persistent JavaScript

When a javascript script is executed it is evaluated in the global javascript context Care should be taken that localvariables may pollute that context so it is in general recommended that all JavaScript scripts are wrapped

(function() user code

)()

It is also possible to deliberately load functions and other code into the global context persistently and have thatcode permanently available and running When the JavaScript engine initialises it automatically runs a special startupscript

storescriptsovmsmainjs

That script can in turn include other code If you make a change to such persistent code and want to reload it you canwith

OVMS script reload

2174 JavaScript Modules

The OVMS JavaScript engine supports the concept of modules (using the nodejs style of exports) Such modules canbe written like this

60 Chapter 2 User Guide

Open Vehicles

exportsprint = function(obj ind) var type = typeof objif (type == object ampamp ArrayisArray(obj)) type = arrayif (ind) ind =

switch (type) case string

print( + objreplace(g ) + )break

case arrayprint([n)for (var i = 0 i lt objlength i++) print(ind + )exportsprint(obj[i] ind + )if (i = objlength-1) print()print(n)

print(ind + ])break

case objectprint(n)var keys = Objectkeys(obj)for (var i = 0 i lt keyslength i++) print(ind + + keys[i] + )exportsprint(obj[keys[i]] ind + )if (i = keyslength-1) print()print(n)

print(ind + )break

defaultprint(obj)

if (ind == ) print(n)

By convention modules such as this are placed in the storescriptslib directory as ltmodulenamegtjsThese modules can be loaded with

JSON = require(libJSON)

And used as

JSONprint(this)

To automatically load a custom module on startup add the MyPlugin = require(libMyPlugin) lineto ovmsmainjs

There are a number of internal modules already provided with the firmware and by convention these are providedunder the intltmodulenamegt namespace The above JSON module is for example provided as intJSON andautomatically loaded into the global context These internal modules can be directly used (so JSONprint(this)works directly)

217 Scripting 61

Open Vehicles

2175 Testing JavaScript Modules

Use the editor (see Tools menu) to test or evaluate arbitrary Javascript code This can be done on the fly ie withoutsaving the code to a file first Think of it as a server side Javascript shell

Testing modules normally involves reloading the engine as the require() call caches all loaded modules untilrestart To avoid this during module development use the following template code This mimics the require() callwithout caching and allows to do tests within the same evaluation run

Load modulemymodule = (function()exports =

insert module code here

return exports)()

Module API testsmymodulemyfunction1()JSONprint(mymodulemyfunction2())

As the module is actually loaded into the global context this way just like using require() anything else using themodule API (eg a web plugin) will also work after evaluation

2176 Heap Memory

Due to limitations of the general esp-idf system memory management Duktape will normally use the custom memorymanager umm_malloc by Ralph Hempel

umm_malloc needs a dedicated chunk of the system memory to work with The default for Duktape is 512 KB(taken from SPIRAM) which is normally sufficient even for extended scripting If you need more RAM the sizecan be changed by config set module duktapeheapsize ltsize_in_KBgt Maximum allowed size is1024 KB The heap size needs to be configured at Duktape startup and cannot be changed while Duktape is runningTo reconfigure the heap size set the new configuration and do a script reload

Call meminfo() to query the current heap memory usage status The function returns an object containing somestandard and some memory library internal info The shell command script meminfo outputs the object in JSONformat Example

OVMS script meminfo

totalBytes 524224usedBytes 273344freeBytes 250880largestFreeBytes 180608memlib ummummTotalEntries 2723ummUsedEntries 2615ummFreeEntries 108ummTotalBlocks 16382ummUsedBlocks 8542ummFreeBlocks 7840ummMaxFreeContiguousBlocks 5644ummUsageMetric 108ummFragmentationMetric 27

62 Chapter 2 User Guide

Open Vehicles

ldquolargestFreeBytesrdquo is the largest block of contiguous memory available Note these values will change by someamount between the garbage collection runs done every 60 seconds the maximum usage will be just before thegarbage collection and the base line just after

ldquomemlibrdquo tells about the memory manager in use the following fields are the internal state variables and statistics ofthat manager (having the memlib name as a name prefix) These can be useful to monitor the memory managementload and performance

If running a firmware configured to use the default system memory manager the output will look like this

OVMS script meminfo

totalBytes 4072176usedBytes 415996freeBytes 3656180largestFreeBytes 3635864memlib syssysMinimumFreeBytes 3653072sysAllocatedBlocks 6013sysFreeBlocks 454sysTotalBlocks 6467

2177 Internal Objects and FunctionsMethods

A number of OVMS objects have been exposed to the JavaScript engine and are available for use by custom scriptsvia the global context

The global context is the analog to the window object in a browser context it can be referenced explicitly as thison the JavaScript toplevel or as globalThis from any context

You can see the global context objects methods functions and modules with the JSONprint(this) method

OVMS script eval JSONprint(this)

performance now function now() [native code]

assert function () [native code] print function () [native code] write function () [native code] meminfo function () [native code] OvmsCommand Exec function Exec() [native code]

OvmsConfig Delete function Delete() [native code] Get function Get() [native code] Instances function Instances() [native code] Params function Params() [native code] Set function Set() [native code]

OvmsEvents Raise function Raise() [native code]

OvmsLocation Status function Status() [native code]

(continues on next page)

217 Scripting 63

Open Vehicles

(continued from previous page)

OvmsMetrics AsFloat function AsFloat() [native code] AsJSON function AsJSON() [native code] Value function Value() [native code]

OvmsNotify Raise function Raise() [native code]

OvmsVehicle ClimateControl function ClimateControl() [native code] Homelink function Homelink() [native code] Lock function Lock() [native code] SetChargeCurrent function SetChargeCurrent() [native code] SetChargeMode function SetChargeMode() [native code] SetChargeTimer function SetChargeTimer() [native code] StartCharge function StartCharge() [native code] StartCooldown function StartCooldown() [native code] StopCharge function StopCharge() [native code] StopCooldown function StopCooldown() [native code] Type function Type() [native code] Unlock function Unlock() [native code] Unvalet function Unvalet() [native code] Valet function Valet() [native code] Wakeup function Wakeup() [native code]

JSON format function () [ecmascript code] print function () [ecmascript code]

PubSub publish function () [ecmascript code] subscribe function () [ecmascript code] clearAllSubscriptions function () [ecmascript code] clearSubscriptions function () [ecmascript code] unsubscribe function () [ecmascript code]

Global Context

bull assert(conditionmessage) Assert that the given condition is true If not raise a JavaScript exceptionerror with the given message

bull print(string) Print the given string on the current terminal If no terminal (for example a backgroundscript) then print to the system console as an informational message

bull write(stringUint8Array) Write the given string or Uint8Array to the current output channel (ieterminalHTTP connection) Use this to transfer binary data to a reader

bull meminfo() Returns an object containing the current heap memory status (see Heap Memory)

bull performancenow() Returns monotonic time since boot in milliseconds with microsecond resolution

64 Chapter 2 User Guide

Open Vehicles

JSON

The JSON module extends the native builtin JSONstringify and JSONparse methods by a format and aprint method to format andor print out a given javascript object in JSON format Both by default insert spacingand indentation for readability and accept an optional false as a second parameter to produce a compact version fortransmission

bull JSONprint(data) Output data (any Javascript data) as JSON readable

bull JSONprint(data false) compact (without spacingindentation)

bull str = JSONformat(data) Format data as JSON string readable

bull str = JSONformat(data false) compact (without spacingindentation)

bull JSONstringify(value[ replacer[ space]]) see MDN JSONstringify

bull JSONparse(text[ reviver]) see MDN JSONparse

Note The JSON module is provided for compatibility with standard Javascript object dumps and for readability Ifperformance is an issue consider using the Duktape native builtins JSONstringify() Duktapeenc() andJSONparse() Duktapedec() (see Duktape builtins and Duktape JSON for explanations of these)

For example Duktapeenc(JC data) is equivalent to JSONformat(data false) except for therepresentation of functions Using the JX encoding will omit unnecessary quotings

Warning All Duktape JSON encoders and decoders have a very high performance penalty and should beavoided for large objects or frequent encodingdecoding with large being any object larger than a handful ofconfiguration or state variables

For general data storage and exchange with the web UI use the CBOR serialization instead

CBOR

CBOR is a binary serialization format and especially with Duktape the better alternative over JSON for storage anddata transmission if human readability isnrsquot required

ldquoCBORrdquo stands for ldquoConcise Binary Object Representationrdquo See httpscborio for details on the specification andavailable implementations CBOR isnrsquot necessarily more compact in storage space but can be encoded and decodedmuch faster and with much less memory overhead as JSON

Duktape implements CBOR support by the builtin CBORencode() and CBORdecode() methods

bull enc = CBORencode(data) Encode data (any Javascript data) to CBOR format (result is an ArrayBuffer)

bull data = CBORdecode(enc) Decode CBOR format (ArrayBufferUint8Array) to Javascript data

CBOR support in Duktape is still considered experimental but the underlying implementation is mature

CBOR also isnrsquot part of the standard browser builtin Javascript APIs yet so the OVMS web framework includes thecbor-js library by Patrick Gansterer (same API as on the Duktape side)

The webserver command API supports binary output from commands amp Javascript API methods and the output canbe passed to CBORdecode() directly

Example

The following scheme shows how to transmit a javascript data object from the module backend into the web frontend

217 Scripting 65

Open Vehicles

Module backendbackendgetdata = function ()

var mydata = pi 3141 fib [ 011235813 ] write(CBORencode(mydata))

Web frontendloadjs( command backendgetdata() output binary )done((stream) =gt

var mydata = CBORdecode(stream))

For full examples see the ldquoAuxBatMonrdquo and ldquoPwrMonrdquo plugins

Note When loading CBOR data via VFSLoad() you need to set the binary option to true so the loader willreturn a Uint8Array instead of a standard string

HTTP

The HTTP API provides asynchronous GET amp POST requests for HTTP and HTTPS Requests can return text andbinary data and follow 301302 redirects automatically Basic authentication is supported (add username amp passwordto the URL) digest authentication is not yet implemented

The handler automatically excludes the request objects from garbage collection until finished (successfailure) so youdonrsquot need to store a global reference to the request

bull req = HTTPRequest(cfg) Perform asynchronous HTTPHTTPS GET or POST request

Pass the request parameters using the cfg object

ndash url standard URLURI syntax optionally including user auth and query string

ndash post optional POST data set to an empty string to force a POST request Note you needto provide this in encoded form If no Content-Type header is given it will default tox-www-form-urlencoded

ndash headers optional array of objects containing key-value pairs of request headers NoteUser-Agent will be set to the standard OVMS user agent if not present here

ndash timeout optional timeout in milliseconds default 120 seconds

ndash binary optional flag true = perform a binary request (see response object)

ndash done optional success callback function called with the response object as argument with thispointing to the request object

ndash fail optional error callback function called with the error string as argument with this point-ing to the request object

ndash always optional final callback function no arguments this = request object

The cfg object is extended and returned by the API (req) It will remain stable at least until the requesthas finished and callbacks have been executed On completion the req object may contain an updatedurl and a redirectCount if redirects have been followed Member error (also passed to the failcallback) will be set to the error description if an error occurred The always callback if present is calledin any case after a done or fail callback has been executed Check thiserror in the alwayscallback to know if an error occurred

On success member object response will be present and contain

66 Chapter 2 User Guide

Open Vehicles

ndash statusCode the numerical HTTP Status response code

ndash statusText the HTTP Status response text

ndash headers array of response headers each represented by an object ltnamegt ltvaluegt

ndash body only for text requests response body as a standard string

ndash data only for binary requests response body as a Uint8Array

Notes any HTTP response from the server is considered success check responsestatusCode forserver specific errors Callbacks are executed without an output channel so all print outputs will bewritten to the system log Hint use JSONprint(this false) in the callback to get a debug logdump of the request

Examples

simple POST ignore all resultsHTTPRequest( url httpsmartpluglocalswitch post state=onampwhen=nowrarr˓ )

fetch and inspect a JSON objectHTTPRequest(

url httpsolarcontrollerlocalstatusfmt=jsondone function(resp)

if (respstatusCode == 200) var status = JSONparse(respbody)if (status[power] gt 5000)OvmsVehicleStartCharge()

else if (status[power] lt 3000)OvmsVehicleStopCharge()

)

override user agent log completed request objectHTTPRequest(

url httpsdexters-webdeftestjsonheaders [ User-Agent Mr What Zit Tooya ]always function() JSONprint(this false)

)

bull HTTPrequest() Legacy alias for HTTPRequest() please do not use

Note SSL requests (https) can take up to 12 seconds on an idle module SSL errors also may not reflect the actualerror for example an empty server response with code 400 may be reported as a general ldquoSSL errorrdquo If you get ldquoSSLerrorrdquo on a valid request you may need to install a custom root CA certificate see SSLTLS

VFS

The VFS API provides asynchronous loading and saving of files on store and sd Text and binary data issupported Currently only complete files can be loaded the saver supports an append mode In any case the data tosaveload needs to fit into RAM twice as the buffer needs to be converted tofrom Javascript

The handler automatically excludes the request objects from garbage collection until finished (successfailure) so youdonrsquot need to store a global reference to the request

217 Scripting 67

Open Vehicles

Loading or saving protected paths (storeovms_config) is not allowed Saving to a path automaticallycreates missing directories

See AuxBatMon 12V History Chart for a complete application usage example

bull req = VFSLoad(cfg) Perform asynchronous file load

Pass the request parameters using the cfg object

ndash path full file path eg sdmydatatelemetryjson

ndash binary optional flag true = perform a binary request returned data will be an Uint8Array)

ndash done optional success callback function called with the data content read as the single argumentthis pointing to the request object

ndash fail optional error callback function called with the error string as argument with this point-ing to the request object

ndash always optional final callback function no arguments this = request object

The cfg object is extended and returned by the API (req) It will remain stable at least until the requesthas finished and callbacks have been executed On success the req object contains a data property (alsopassed to the done callback) which is either a string (text mode) or a Uint8Array (binary mode)

Member error (also passed to the fail callback) will be set to the error description if an error occurredThe always callback if present is called in any case after a done or fail callback has been executedCheck thiserror in the always callback to know if an error occurred

Example

Load a custom telemetry object from a JSON file on SD cardvar telemetryVFSLoad(path sdmydatatelemetryjsondone function(data) telemetry = Duktapedec(jx data) process telemetry

fail function(error) print(Error loading telemetry + error)

)

bull req = VFSSave(cfg) Perform asynchronous file save

Pass the request parameters using the cfg object

ndash data the string or Uint8Array to save

ndash path full file path (missing directories will automatically be created)

ndash append optional flag true = append to the end of the file (also creating the file as necessary)

ndash done optional success callback function called with no arguments this pointing to the requestobject

ndash fail optional error callback function called with the error string as argument with this point-ing to the request object

ndash always optional final callback function no arguments this = request object

The cfg object is extended and returned by the API (req) It will remain stable at least until the requesthas finished and callbacks have been executed

68 Chapter 2 User Guide

Open Vehicles

Member error (also passed to the fail callback) will be set to the error description if an error occurredThe always callback if present is called in any case after a done or fail callback has been executedCheck thiserror in the always callback to know if an error occurred

Example

Save the above telemetry object in JSON format on SD cardVFSSave(

path sdmydatatelemetryjsondata Duktapeenc(jx telemetry)fail function(error)

print(Error saving telemetry + error)

)

Warning File IO especially saving can cause short freezes of the module

Minimize save frequency and if possible avoid saving while the vehicle is in operation (driving charging) byusing a check like

Saving to VFS may cause short blockings so only allow when vehicle is offfunction allowSave()

return OvmsMetricsValue(veon) ampamp OvmsMetricsValue(vccharging)

Note Saving to and loading from SD card

When storing plugin data on an SD card the plugin needs to take care of the SD card being mounted later in the bootprocess than the scripts are loaded Plugins additionally may need to take into account that the user may replace theSD card any time

When trying to save or load from an unmounted SD error will be set to volume not mounted If this happensduring plugin initialization the plugin should subscribe to the SD mount event to retry the loadsave as soon as the SDcard becomes available

Code scheme

var storeFile = sdusrhistorycborvar listen_sdmount = nullvar history =

function loadStoreFile() VFSLoad(path storeFilebinary truedone function(data)

print(storeFile + loadedn)history = CBORdecode(data)startRecording()

fail function(error)

print(storeFile + + thiserror + n)if (listen_sdmount ampamp thiserror == volume not mounted)

retry once after SD mountlisten_sdmount = PubSubsubscribe(sdmounted loadStoreFile)

else

(continues on next page)

217 Scripting 69

Open Vehicles

(continued from previous page)

startRecording()

)

function startRecording() if (listen_sdmount) PubSubunsubscribe(listen_sdmount)listen_sdmount = null

PubSubsubscribe(tickerEvent ticker) for example

if (storeFile) loadStoreFile()

else startRecording()

PubSub

The PubSub module provides access to a Publish-Subscribe framework In particular this framework is used to deliverevents to the persistent JavaScript framework in a high performance flexible manner An example script to print outthe ticker10 event is

var myTicker=function(msgdata) print(Event +msg+n)

PubSubsubscribe(ticker10myTicker)

The above example created a function myTicker in global context to print out the provided event name Then thePubSubsubscribe module method is used to subscribe to the ticker10 event and have it call myTickerevery ten seconds The result is ldquoEvent ticker10rdquo printed once every ten seconds

PubSub interprets events similar to MQTT as hierarchical topics with dots separating the levels It delivers the eventsin multiple passes with each new pass removing the last dotted part of the topic (ie bottom-up) so the most specificsubscriptions will be called first The handler is always called with the original eventtopic name So to eg catchall events vehiclecharge you can simply subscribe to vehiclecharge and inspect the actual eventname in your handler

PubSubsubscribe(vehiclecharge function (event) print(Got charging related event + event)

)

bull id = PubSubsubscribe(topic handler) Subscribe the function handler to messages of thegiven topic Note that types are not limited to OVMS events The method returns an id to be used tounsubscribe the handler

bull PubSubpublish(topic [data]) Publish a message of the given topic All subscribed handlers willbe called with the topic and data as arguments data can be any Javascript data

bull PubSubunsubscribe(id | handler | topic) Cancel a specific subscription all subscriptions ofa specific handler or all subscriptions to a topic

70 Chapter 2 User Guide

Open Vehicles

OvmsCommand

bull str = OvmsCommandExec(command) The OvmsCommand object exposes one method ldquoExecrdquo Thismethod is passed a single parameter as the command to be executed runs that command and then returnsthe textual output of the command as a string For example

print(OvmsCommandExec(boot status))Last boot was 14 second(s) ago

This is reset 0 since last power cycleDetected boot reason PowerOn (114)Crash counters 0 total 0 early

OvmsConfig

bull array = OvmsConfigParams() Returns the list of available configuration parameters

bull array = OvmsConfigInstances(param) Returns the list of instances for a specific parameter

bull string = OvmsConfigGet(paraminstancedefault) Returns the specified parame-terinstance value

bull object = OvmsConfigGetValues(param [prefix]) Gets all param instances matching theoptional prefix with their associated values If a prefix is given the returned property names will havethe prefix removed Note all values are returned as strings you need to convert them as needed

bull OvmsConfigSet(paraminstancevalue) Sets the specified parameterinstance value

bull OvmsConfigSetValues(param prefix object) Sets all properties of the given object asparam instances after adding the prefix Note non-string property values will be converted to their stringrepresentation

bull OvmsConfigDelete(paraminstance) Deletes the specified parameter instance

Beginning with firmware release 32009 a dedicated configuration parameter usr is provided for plugins Youcan add new config instances simply by setting them for example by OvmsConfigSet(usr mypluginlevel 123) or by the config set command

Read plugin configuration example

Set default configurationvar cfg = level 100 enabled no

Read user configurationObjectassign(cfg OvmsConfigGetValues(usr myplugin))

if (cfg[enabled] == yes) print(Im enabled at level + Number(cfg[level]))

Keep in mind to prefix all newly introduced instances by a unique plugin name so your plugin can nicely coexist withothers

OvmsEvents

This provides access to the OVMS event system While you may raise system events the primary use is to raisecustom events Sending custom events is a lightweight method to inform the web UI (or other plugins) about simplestate changes Use the prefix usr on custom event names to prevent conflicts with later framework additions

217 Scripting 71

Open Vehicles

Another use is the emulation of the setTimeout() and setInterval() browser methods by subscribing to adelayed event Pattern

function myTimeoutHandler() raise the timeout event again here to emulate setInterval()

PubSubsubscribe(usrmyplugintimeout myTimeoutHandler)

start timeoutOvmsEventsRaise(usrmyplugintimeout 1500)

bull OvmsEventsRaise(event [delay_ms]) Signal the event optionally with a delay (millisecondsmust be given as a number) Delays are handled by the event system the method call returns immediately

OvmsLocation

bull isatlocation = OvmsLocationStatus(location) Check if the vehicle is currently in a loca-tionrsquos geofence (pass the location name as defined) Returns true or false or undefined if thelocation name passed is not valid

Note to get the actual GPS coordinates simply read metrics vplatitude vplongitude and vpaltitude

OvmsMetrics

bull str = OvmsMetricsValue(metricname [decode]) Returns the typed value (default) or stringrepresentation (with decode = false) of the metric value

bull num = OvmsMetricsAsFloat(metricname) Returns the float representation of the metric value

bull str = OvmsMetricsAsJSON(metricname) Returns the JSON representation of the metric value

bull obj = OvmsMetricsGetValues([filter] [decode]) Returns an object of all metrics match-ing the optional name filtertemplate (see below) by default decoded into Javascript types (ie numericalvalues will be JS numbers arrays will be JS arrays etc) The object returned is a snapshot the valueswonrsquot be updated

The filter argument may be a string (for substring matching as with metrics list) an array of fullmetric names or an object of which the property names are used as the metric names to get The objectwonrsquot be changed by the call see Objectassign() for a simple way to merge objects Passing anobject is especially convenient if you already have an object to collect metrics data

The decode argument defaults to true pass false to retrieve the metrics string representations insteadof typed values

With the introduction of the OvmsMetricsGetValues() call you can get multiple metrics at once and let thesystem decode them for you Using this you can for example do

Get all metrics matching substring vbc (vehicle battery cell)var metrics = OvmsMetricsGetValues(vbc)print(Temperature of cell 3 + metrics[vbctemp][2] + degCn)print(Voltage of cell 7 + metrics[vbcvoltage][6] + Vn)

Get some specific metricsvar ovmsinfo = OvmsMetricsGetValues([mversion mhardware])JSONprint(ovmsinfo)

72 Chapter 2 User Guide

Open Vehicles

This obsoletes the old pattern of parsing a metricrsquos JSON representation using eval() JSONparse() orDuktapedec() you may still find in some plugins Example

var celltemps = eval(OvmsMetricsAsJSON(vbctemp))print(Temperature of cell 3 + celltemps[2] + degCn)

Warning Never use eval() on unsafe data eg user input eval() executes arbitrary Javascript so canbe exploited for code injection attacks

OvmsNotify

bull id = OvmsNotifyRaise(type subtype message) Send a notification of the given type andsubtype with message as contents Returns the message id allocated or 0 in case of failure Examples

send an info notification to the userOvmsNotifyRaise(info usrmypluginstatus Alive and kicking)

send a JSON stream to a web pluginOvmsNotifyRaise(stream usrmypluginupdate JSONformat(streamdatararr˓false))

send a CSV data record to a serverOvmsNotifyRaise(data usrmypluginrecord -MyStatus086400Alive)

OvmsVehicle

The OvmsVehicle object is the most comprehensive and exposes several methods to access the current vehicle Theseinclude

bull str = OvmsVehicleType() Return the type of the currently loaded vehicle module

bull success = OvmsVehicleWakeup() Wakeup the vehicle (return TRUE if successful)

bull success = OvmsVehicleHomelink(buttondurationms) Fire the given homelink button

bull success = OvmsVehicleClimateControl(onoff) Turn onoff climate control

bull success = OvmsVehicleLock(pin) Lock the vehicle

bull success = OvmsVehicleUnlock(pin) Unlock the vehicle

bull success = OvmsVehicleValet(pin) Activate valet mode

bull success = OvmsVehicleUnvalet(pin) Deactivate valet mode

bull success = OvmsVehicleSetChargeMode(mode) Set the charge mode (ldquostandardrdquo ldquostoragerdquo ldquorangerdquo ldquoperformancerdquo)

bull success = OvmsVehicleSetChargeCurrent(limit) Set the charge current limit (in amps)

bull success = OvmsVehicleSetChargeTimer(onoff start) Set the charge timer

bull success = OvmsVehicleStartCharge() Start the charge

bull success = OvmsVehicleStopCharge() Stop the charge

bull success = OvmsVehicleStartCooldown() Start a cooldown charge

bull success = OvmsVehicleStopCooldown() Stop the cooldown charge

217 Scripting 73

Open Vehicles

bull result = OvmsVehicleObdRequest(arguments) Perform OBDUDS request (synchronous)

Pass the request parameters using the arguments object

ndash txid the CAN ID to send the request to (or 0x7df for broadcast)

ndash rxid the CAN ID to expect the response at (or 0 for broadcast)

ndash request the request to send either a hex encoded string or an Uint8Array

ndash bus optional CAN bus device name default ldquocan1rdquo

ndash timeout optional timeout in milliseconds default 3000

ndash protocol optional protocol to use default 0 = ISOTP_STD ndash see vehicleh for other protocols

The result object will have these properties

ndash error 0 = no error else the error code with negative ranges being system errors positive codes areOBDUDS response error codes (NRCs)

ndash errordesc a human readable error description

ndash response only on success the binary response (Uint8Array)

ndash response_hex only on success hex encoded response (string)

Example

Establish diagnostic session with an ECUvar res = OvmsVehicleObdRequest( txid 0x765 rxid 0x7cf request 1003 rarr˓)if (reserror)print(reserrortext)

elseprint(resresponse_hex)

2178 Test Utilities

You can use the web UI editor and shell to edit upload and test script files If you need many test cycles a convenientalternative is to use shell scripts to automate the process

If yoursquove configured ssh public key authentication you can simply use scp to upload scripts and ssh to executecommands

binbash Upload amp execute a script file

FILE=testjsPATH=storescripts

OVMS_HOST=yourovmslocal

SCP=usrbinscp -qSSH=usrbinssh

Upload$SCP $FILE $OVMS_HOST$PATH$FILE

Execute$SSH $OVMS_HOST script run $FILE

74 Chapter 2 User Guide

Open Vehicles

Customize to your needs If you want to test a plugin simply replace the script run command by scriptreload followed by some script eval calls to your plugin API

Note this may be slow as the ssh session needs to be negotiated for every command

A faster option is using the OVMS HTTP REST API The following script uses curl to upload and execute a script

binbash Upload amp execute a script file

FILE=testjsPATH=storescripts

OVMS_HOST=httpyourovmslocalOVMS_USER=adminOVMS_PASS=yourpassword

CURL=usrbincurl -c auth -b authSED=usrbinsedDATE=usrbindate

Loginif [[ -e auth ]] then

AUTHAGE=$(($($DATE +s) - $($DATE +s -r auth)))else

AUTHAGE=3600fiif [[ $AUTHAGE -ge 3600 ]] thenRES=$($CURL $OVMS_HOSTlogin --data-urlencode username=$OVMS_USER --data-

rarr˓urlencode password=$OVMS_PASS 2gtdevnull)if [[ $RES =~ Error ]] thenecho -n LOGIN ERROR echo $RES | $SED -e sltligt([^lt])1grm authexit 1

fifi

UploadRES=$($CURL $OVMS_HOSTedit --data-urlencode path=$PATH$FILE --data-rarr˓urlencode content$FILE 2gtdevnull)if [[ $RES =~ Error ]] thenecho -n UPLOAD ERROR echo $RES | $SED -e sltligt([^lt])1grm authexit 1

fi

Execute$CURL $OVMS_HOSTapiexecute --data-urlencode command=script run $FILE

217 Scripting 75

Open Vehicles

218 Factory Reset

2181 Module Configuration

A standard factory reset erases the configuration store After a factory reset you will be able to access the USBconsole with an empty module password and the ldquoOVMSrdquo wifi access point with the initial password ldquoOVMSinitrdquo Werecommend using the setup wizard to configure the module or restoring a configuration backup as soon as possible1as the module is accessible by anyone knowing the initial password

The standard factory reset does not revert OTA firmware installs See below for methods to switch back to andoptionally replace the factory firmware

Method 1 Command

If you have console command access a factory reset can be accomplished with this command

OVMS module factory resetReset configuration store to factory defaults and lose all configuration data (yn)rarr˓yStore partition is at 00c10000 size 00100000Unmounting configuration storeErasing 1048576 bytes of flashFactory reset of configuration store complete and reboot now

That command will erase all configuration store and reboot to an empty configuration

Note to issue this command from the web shell or a remote shell (App Server ) you need to skip the confirmationstep by adding the option -noconfirm ie

OVMS module factory reset -noconfirm

Method 2 SD card

If you donrsquot have console access you can perform a factory reset by placing an empty file named factoryresettxt in the root directory of an SD card and insert that SD into the (running) module The file will be deleted and themodule will reboot within about 30 seconds

Method 3 Switch S2

You can also open the module case remove any SD card (important) power on the module wait 10 seconds thenpush and hold switch ldquoS2rdquo for 10 seconds ldquoS2rdquo is located here

1 Wait for the SSH key generation to finish after reboot before attempting to restore the backup Trying to run both processes concurrently maycrash the module Key generation takes about 2 minutes look for log message ldquoSSH server key installedrdquo

76 Chapter 2 User Guide

Open Vehicles

Method 4 USB

If you donrsquot have console access and donrsquot have an SD card you can perform a factory reset from a PC via USB usingthe esptoolpy tool from the Espressif ESP-IDF toolkit (see below for installation)

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 erase_region 0xC10000 0x100000

Note the port needs to be changed to the one assigned by your system ie devttyUSB0 on a Linux system orCOMx on Windows After using esptoolpy to manually erase the config region you should go into the console and dothe module factory reset step to properly factory reset

Note Methods 1 2 and 3 need a running system ie will not work if your module cannot boot normally In this casefirst try method 4 If that doesnrsquot help also switch back to the factory firmware as shown below

2182 Module Factory Firmware

You can switch back to factory firmware with this command

OVMS ota boot factoryBoot from factory at 0x00010000 (size 0x00400000)

Or without console access (lost module password) using the esptoolpy from the Espressif ESP-IDF toolkit

218 Factory Reset 77

Open Vehicles

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 erase_region 0xd000 0x2000

Note the device needs to be changed to the one assigned by your system ie devttyUSB0 on a Linux system orCOMx on Windows

2183 Flash Factory Firmware via USB

esptoolpy can also be used to flash a new factory firmware Download the firmware file ovms3bin you wantto flash then issue

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 --before default_reset --after hard_reset write_flash --compress --flash_mode dio --flash_freq 40m --flash_size detect 0x10000 ovms3bin

Note if you were running an OTA partition before you also need to switch back to the factory partition as shownabove

2184 Full Reflash via USB

If you accidentally did an erase_flash or erased the wrong region you will need to do a full reflash of your module(including the boot loader and partitioning scheme)

The need for a full reflash will typically show by the USB output of the module boot being just something like

rst0x10 (RTCWDT_RTC_RESET)boot0x3f (SPI_FAST_FLASH_BOOT)flash read err 1000ets_mainc 371ets Jun 8 2016 002257

To do a full reflash download the three bin files from the release you want to flash eg from

httpsovmsdexters-webdefirmwareotav32edge

Then issue

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 --before default_reset --after hard_reset write_flash --compress --flash_mode dio --flash_freq 40m --flash_size detect 0x1000 bootloaderbin 0x10000 ovms3bin 0x8000 partitionsbin

replacing the port and file paths accordingly for your system

If this fails open a support ticket on httpswwwopenvehiclescom and attach a log of the boot process or install thedeveloper environment and do a make flash

2185 Installing esptoolpy

The esptoolpy package and installation instructions can be found here

httpsgithubcomespressifesptool

78 Chapter 2 User Guide

Open Vehicles

The package normally can be installed without manual download using the python package manager ldquopiprdquo ie onUnixLinux

sudo pip install esptool

Warning You can brick your module using the esptool Only use the commands shown above

219 OBDII ECU

2191 Purpose

The OBDII interface is a connector electrical specification and protocol used for viewing the operation and statusof a car It is mandated in all light duty vehicles sold in North America beginning in 1996 and while the focus ofthe information it provides is for monitoring the emissions of Internal Combustion Engines it has proven to be ahandy port for connecting a variety of aftermarket displays and monitors to a car Electric Vehicles have no need foremissions monitoring so often omit the port from the car thus making the these aftermarket devices incompatibleThe OBDII ECU capability of the OVMS v3 is used to create a simulated OBDII port which can be used to attachmany of these aftermarket devices to the car

2192 Cabling

The cable and OBDII connector are not provided with the OVMSv3 module and can be built using the diagram belowAlternatively you can purchase the OVMS V3 HUD OBD II-F Cable from FastTech

DA26 OBDII Female Signal name6 14 CAN3-L16 6 CAN3-H8 4 amp 5 Chassis amp Signal Ground18 16 +12v switched output to HUDdongle

NB Also place a 120 ohm resistor between OBDII pins 14 amp 6 for bus termination

2193 Setup

From the Web Interface check the ldquoStart OBD2ECUrdquo box and select CAN3 from the dropdown menu (if using thewiring diagram above) This will enable the OBDII ECU Task to run the next time the OVMSv3 module is poweredon or reset Also check the ldquoPower on external 12Vrdquo box in order to feed 12v power through to the device Click onSave at the bottom of the page

From the command line the following commands are available

obdii ecu start can3 Starts the OBDII ECU taskobdii ecu stop Stops the OBDII ECU taskobdii ecu list Displays the parameters being served and their current valueobdii ecu reload Reloads the map of parameters after a config change

power ext12v on Turns on power feed to the devicepower ext12v off Turns off power feed to the device

219 OBDII ECU 79

Open Vehicles

2194 Operation

During operation an OBDII device for example a Head-Up Display (HUD) or OBDII Diagnostic module will makeperiodic requests usually a few times per second for a set of parameters The OVMSv3 module will reply to thoseparameters with the metric if configured to do so on an individual basis These parameters can be common itemssuch as vehicle speed engine RPM and engine coolant temperature but because of the differences between ICE andEV vehicles many of the parameters do not have equivalent values in an EV Speed and engine (motor) RPM can bedirectly mapped but there is typically no ldquoengine coolantrdquo That parameter (in fact most parameters) can be mappedto some other value of interest For example the Engine Coolant display on the HUD can be configured to displaymotor or battery temperature instead Engine Load (PID 4 a percentage value) is mapped by default to battery Stateof Charge (also a percentage) However note that not all vehicle metrics may be supported by all vehicles

Parameters requested by the OBDII device are referred to by ldquoPID valuerdquo Note that each PID has a specific range ofallowed values and that it is not possible to directly represent values outside that range For example PID 5 (Enginecoolant temperature) has a range of -40 to +215 it would not be possible to map the full range of motor RPMs to thisparameter Values outside the allowed range are limited to the range boundary value The complete table of possibleparameters are described here httpsenwikipediaorgwikiOBD-II_PIDsMode_01

Vehicle metrics are referred to by name See the table in Appendix 1 for a list of available metrics which vehiclesreport them and which of those are of a format that can be mapped by the OBDII ECU task

2195 Defaults and customization

By default the following mapping of PID value to OVMSv3 metric is used

PID (Dec) PID (Hex) Requested Parameter Mapped Metric Value Metric Name4 0x04 Engine Load Battery SOC vbsoc5 0x05 Coolant Temp Motor Temp vmtemp12 0x0c Motor RPM Motor RPM vmrpm13 0x0d Vehicle Speed Vehicle Speed vpspeed16 0x10 MAF Air Flow 12v Battery vb12vvoltage

The OBDII ECU task supports the remapping and reporting of PIDs 4-18 31 33 47 and 51 (all decimal) PIDs 0and 32 are used by the OBDII protocol for management and not available for assignment Other PIDs return zero

PIDs requested for which no mapping has been established are ignored by the OBDII ECU task As an aid for discov-ering which PIDs are being requested the configuration parameter lsquoautocreatersquo may be used to populate entries intothe obdii ecu list display (lsquoconfig set obd2ecu autocreate yesrsquo) Such autocreated entries are marked as ldquoUnimple-mentedrdquo and return zero to the device They are not added to the configured (saved) obd2ecumap and get cleared ateach boot or reset They may be mapped to a supported metric if desired using

config set obd2ecumap ltPIDgt ltmetric namegt

Example

OVMS config set obd2ecumap 5 vbtemp(map battery temp to engine coolant temp)

OVMS vfs edit storeobd2ecu10(script for fuel pressure PID see below)

OVMS obdii ecu reloadOBDII ECU pid map reloaded

(continues on next page)

80 Chapter 2 User Guide

Open Vehicles

(continued from previous page)

OVMS obdii ecu list

PID Type Value Metric0 (0x00) internal 00000004 (0x04) internal 95000000 vbsoc5 (0x05) metric 16000000 vbtemp10 (0x0a) script 000000011 (0x0b) unimplemented 000000012 (0x0c) internal 0000000 vmrpm13 (0x0d) internal 0000000 vpspeed16 (0x10) internal 13708791 vb12vvoltage32 (0x20) internal 0000000

Types ldquointernalrdquo means default internal handling of the PID ldquometricrdquo means a user-set mapping of PID to thenamed metric ldquounimplementedrdquo are PIDs requested by the device but for which no map has been set ldquoscriptrdquomeans the user has configured a script to handle the PID

2196 Special handling

Several PIDs are handled specially by the OBDII ECU task

bull PIDs 0 and 32 are bit masks that indicate what other PIDs are being reported by the OBDII ECU task These aremaintained internally based on the default mapped and scripted PID table Note that some OBDII devices usePID 0 as a test for ECU presence and operating mode (standard or extended) and ignore the returned valuesThe OBDII ECU task supports both modes

bull PID 12 Engine RPM is often monitored by the OBDII device to detect when the car is turned off Since anEVrsquos motor is not rotating when the car is stopped a HUD may decide to power down when it sees the RPMdrop below a particular value or if there is no variation (jitter) in its value To prevent this the OBDII ECU taskwill source a fake value of 500 rpm plus a small periodic variation if the car is not moving (vehicle speed isless than 1) To actually let the device turn off see ldquoExternal Power Controlrdquo below

bull PID 16 MAF Air Flow is commonly used by OBDII devices to display fuel flow by measuring the amount ofair entering the engine in support of combustion Since this is irrelevant to an EV the OBDII ECU task mapsthis metric to a simple integer Most HUDs displays limit this to a range of 0-199 literhr which is acceptable todisplay the +12v battery voltage Since the conversion factors are complicated this value is at best approximatein spite of its implied precision

bull Mode 9 PID 2 VIN is used to report the carrsquos DMV VIN to the attached OBDII device Since the rest ofthe parameters reported by the OBDII ECU task are simulated and some OBDII devices may use the VIN fortracking purposes the reporting of the VIN may be turned off by setting the privacy flag to ldquoyesrdquo The commandis lsquoconfig set obd2ecu privacy yesrsquo Setting it to lsquonorsquo which is the default allows the reporting of the VIN

bull Mode 9 PID 10 ECU Name is statically mapped to report the OVMSv3rsquos Vehicle ID field (vehicle name notVIN) This string may be customized to any printable string of up to 20 characters if not used with the OVMSv2 or v3 mobile phone applications (lsquoconfig set vehicle id car_namersquo)

2197 Metric Scripts

Should one desire to return a value not directly available by a single named metric it is possible to map a PID to a shortscript where combinations of metrics constants etc may be used to create a custom value Note that the restrictionson PID value ranges still applies Also note that the special handling for PID 12 (engine RPM) is not applied in theOBDII ECU task so it must be included in the script if driving a HUD

219 OBDII ECU 81

Open Vehicles

Scripts should be placed in the directory storeobd2ecuPID where PID is the decimal value of the PID to be pro-cessed Example for creating a ldquokw per kmrdquo sort of metric

ret1=OvmsMetricsAsFloat(vpspeed)ret2=OvmsMetricsAsFloat(vbpower)out=00if (ret1 gt 0) out=ret2ret1 out

Put this text in a file storeobd2ecu4 to map it to the ldquoEngine Loadrdquo PID See ldquoSimple Editorrdquo chapter for file editingor use lsquovfs appendrsquo commands (tedious) Note however that Vehicle Power (vbpower) is not supported on all cars(which is why this is not the default mapping for this PID)

Warning The error handling of the scripting engine is very rough at this writing and will typically cause a full modulereboot if anything goes wrong in a script

2198 External Power Control

Since the OVMSv3 module remains powered at all times and the normal means for deducing that a car has beenturned off donrsquot work on an EV (see PID 12 above) an external OBDII device needs to be explicitly turned on andoff This is currently done with short event scripts The following commands configure the OVMSv3 to make theexternal 12v feed follow the vehicle onoff state or use the vfs edit command to create or modify the files

vfs mkdir storeeventsvfs mkdir storeeventsvehicleonvfs mkdir storeeventsvehicleoff

vfs append power ext12v on storeeventsvehicleonext12vvfs append power ext12v off storeeventsvehicleoffext12v

220 EGPIO

2201 Hardware

The OVMS has 10 general purpose IO ports provided by a MAX7317 IO expander

The MAX7317 ports can be individually configured as either an open-drain output or an overvoltage-protected Schmittinput Being open-drain you need to add pull-up resistors for input and output switch uses to get a defined high level(eg 10K to 33V) See the datasheet for details on maximum current amp voltage ratings

Depending on your hardware configuration up to 4 ports may be used by the module 6 are generally free to use

Port Signal(s) ExpPin Default usage0 MDM_EN 15 Modem enable1 SW_CTL ndash Ext12V control (SW_12V)2 CAN1_EN + EIO_1 17 CAN1 transceiver enable3 MDM_DTR + EIO_2 19 Modem sleep control4 EIO_3 21 -free-5 EIO_4 20 -free-6 EIO_5 18 -free-7 EIO_6 16 -free-8 EIO_7 14 -free-9 EIO_8 12 -free-

82 Chapter 2 User Guide

Open Vehicles

SW_CTL (port 1) controls a BTS452R power switch which could deliver a nominal output of 25W or 18A and up to40W or 29A short term at the SW_12V pin but the main fuse of the module (located at the corner near the DB9 plug)limits the 12V current total sum of the board plus any external hardware to continuous 075A on a revision 31 boardand 10A on a revision 32 board The unswitched EXT_12V pin is also behind the fuse

The module including modem needs a 12V current share of ~80mA in full operation Calculate with 100mA to beon the safe side That leaves continuous 065A on a revision 31 board and 09A on a revision 32 board for externaldevices and addons powered by the module The fuse has a little headroom but donrsquot rely on that

SW_12V is meant to power auxiliary devices from the OVMS for example head-up displays Of course you can aswell power a standard 12V automotive relay or fan directly from this without additional hardware

The EGPIO (EIO) ports are not connected directly to the DA26 connector but are available atthe internal expansion port To route an EGPIO port to the DA26 connector connect it to oneof the GEP_17 lines at the expansion port either directly or via some additional driver

Fig 1 Expansion Port (Prototype PCB)Fig 2 DA26 Connector

Example to route EIO_8 (port 9) to GEP_7 (pin 21 on the DA26) seta jumper on pins 10+12 on the expansion port

2202 Commands

EGPIO control is provided by the egpio command set

bull egpio output ltportgt ltlevelgt [ltportgt ltlevelgt] ndash set output level(s)

bull egpio input ltportgt [ltportgt ] ndash query inputlevel(s)

bull egpio status ndash show output input amp monitor status

bull egpio monitor lton|offgt [ports] ndash enabledisablemonitoring

bull egpio monitor status ndash show current monitoring status

220 EGPIO 83

Open Vehicles

To configure a port for input it needs to be switched to output levelhigh (1) That is done automatically by the input and monitor com-mands

If you set multiple outputs the ports will be set one at a time so outputlevels will change with a slight delay You can use this behaviour to setdata lines before a clock line eg when sending bits serially into a shiftregister

Note The MAX7317 needs active polling to detect input state changes Monitoring is disabled by default it can beenabled manually or configured to start automatically on module init Without monitoring only manual input querieswill update the input state trigger input events and input metric updates

2203 Configuration

Parameter Instance Descriptionauto egpio yes = Start monitoring on boot (default no)egpio monitorports List of ports to monitor by default (space separated)egpio monitorinterval Polling interval in milliseconds (min 10 default 50)

The default interval of 50 ms (= 20 Hz) means an input signal needs to be at least 50 ms long to be detected Thispolling frequency produces a CPU load of ~05 on core 1 and is normally sufficient to detect even very short buttonpushes

2204 Metrics

Metric name Example value Descriptionmegpioinput 012345679 EGPIO input port state (ports 0 9 present=high)megpiomonitor 89 EGPIO input monitoring portsmegpiooutput 45679 EGPIO output port state

Hint to process these metrics from Javascript read them into an array using eval() and test for the presence of aport number using eg the includes() method in a browser plugin Duktape does not support includes() youcan test indexOf(port) instead

Example

var input = eval(OvmsMetricsAsJSON(megpioinput))if (inputindexOf(9) lt 0)

print(Input port 9 (EIO8) is currently lown)

2205 Events

Event Data Purposeegpioinputltportgtltstategt ndash EGPIO input port change (port=0 9 state=highlow)egpiooutputltportgtltstategt ndash EGPIO output port change (port=0 9 state=highlow)

84 Chapter 2 User Guide

Open Vehicles

Hint to listen to events from Javascript bind to msgevent on a receiver object from browser context or usePubSub from module context

Example

PubSubsubscribe(egpioinput9low function()print(Input port 9 (EIO8) is now lown)

)

221 TPMS

OVMS v3 includes a capability to read and write sets of TPMS wheel sensors IDs from the vehicle TPMS ECU andstore in your configuration Support for this is vehicle-specific and may require optional hardware boards so pleasefollow your individual vehicle guides for further information

The command to read the current TPMS wheel sensor IDs from the car is

OVMS tpms read SET

(replace SET with your own identifier for this set of wheels such as lsquosummerrsquo lsquowinterrsquo etc)

You can check the stored wheel sensor ID sets with

OVMS tpms list

If you change wheels you can write the new wheel IDs to the TPMS ECU in the car with

OVMS tpms write SET

(replace SET with your own identifier for this set of wheels such as lsquosummerrsquo lsquowinterrsquo etc)

Note that in most cases the car must be switched on for the above commands to work Please refer to your vehiclespecific user guide for more information on this

Note also that OVMS doesnrsquot have any radio capable of receiving TPMS signals and cannot read the IDs from thewheel sensors themselves OVMS can only read the IDs from the TPMS ECU in the car itself You can howeverdrop by pretty much any garage (or use any of a large number of TPMS tools) to trigger and read these IDs from thewheels Once your garage gives you the sensor IDs (each expressed as an 8 character hexadecimal ID) you can enterthem into OVMS as

OVMS tpms set SET ID1 ID2 ID3 ID4 (replace SET with your own identifier for this set of wheelsand ID1 with the hexadecimal sensor ID)

222 Optional K-Line Expansion Board

The optional K-Line Expansion Board is available to extend the capabilities of the OVMS system It can be used totalk to vehicle ECUs using K-Line communication standards

221 TPMS 85

Open Vehicles

There are two installation options

1 If you are using a modem module you install the K-Line Expansion Board on top of the modem Unscrew thefour black screws holding the modem in place In your K-Line expansion board kit you will find four brassstand offs with holes at one end and small bolts at the other Use these to screw down the modem Now orientthe K-line Expansion Board so the top left corner (marked with a white triangle) matches the white triangle onthe modem board Carefully push the K-Line Expansion Board into place (making sure that the pins align andare not bent) Once done the four black screws can be used to secure it in place

2 If you are not using a modem module you install the K-Line Expansion Board directly onto the main OVMSboard Screw the provided standoffs into the main board and Carefully attach the provided pin headers intothe main OVMS board Now orient the K-line Expansion Board so the top left corner (marked with a whitetriangle) matches the white triangle on the main OVMS board Carefully push the K-Line Expansion Board intoplace (making sure that the pins align and are not bent) Once done the four black screws can be used to secureit in place

86 Chapter 2 User Guide

Open Vehicles

Next the K-Line expansion board will need to be configured to match your vehiclersquos K-Line bus and ECU hardwarerequirements Refer to your vehicle specific guide for information on what your vehicle requires

bull S1 is used to turn onoff the extra lsquomasterrsquo mode components For most vehicles this should be OFF

bull SW1 is used to select the power source for the K-Line bus It can be 0 (no power connected) 1 (5v powerfrom USB bus) 2 (5v power converted from vehiclersquos 12v power) or 3 (12v power direct from the vehicle)For most vehicles either 2 or 3 is used

The K-Line bus from the vehicle is connected via a vehicle specific cable This connection is usually to pin 1 on theDB9 connector On OVMS modules v32 and later (as well as v31 boards labelled on board as July 2018 or later)this is internally connected to GEP7 (General Expansion Pin 7) This is necessary to bring the K-Line bus up to theinternal expansion pins (for the K-Line Expansion Board to be able to reach it)

If you have an earlier board there is a relatively simply wiring modification that can be made to upgrade to this

1 You will need a soldering iron solder and a small length of insulated wire

2 Pin 1 on the DB9 connector is the K-Line pin from the vehicle

3 Pin 21 on the DA26 connector is GEP 7 (which is also connected to a pin on internal expansion connector)

4 On the underside of the board you can solder a jumper wire between DB9 pin 1 and DA26 pin 21 to makethis connection

Please refer to the vehicle specific guides for further information on this

222 Optional K-Line Expansion Board 87

Open Vehicles

88 Chapter 2 User Guide

CHAPTER 3

Plugins

The OVMS can easily be extended by plugins Plugins may consist of any combination of module scripts (Javascript)and web UI extensions (HTML)

Installation currently needs to be done manually but is simple See below and the plugin documentation on specificsteps and on how to use the plugin functions A plugin store with simplified download and optional automatic updatingwill be provided in the future

This page is intended as an overview of all plugins currently available in the OVMS repository If yoursquore a plugindeveloper and want to add your plugin here please submit a pull request containing your plugin directory Organizeyour files and include a READMErst as shown here

31 ABRP abetterrouteplannercom

Send live data to abetterrouteplannercom

Overview

abetterrouteplanner is probably the best website to plan a route with an EV and optimize the number of stops neededand where to charge your vehicle

Moreover it has a wonderful functionality to update your plan taking into account your live data to adjust withthe real consumption of the vehicle by connecting an obd device and soft like EVNotify or Torque Pro

This plugin sends your live data from the OVMS box

Author David S Arnold

New in version 12 Your own parameters (car model abrp token but also api-url) are now stored as config param-eters you can consult them using the shell with config list usr or modify with config set command

89

Open Vehicles

Contents

bull ABRP abetterrouteplannercom

ndash Installation

ndash Script code

ndash Usage

311 Installation

You can use the embedded website toolsshell and toolseditor of the OVMS box to create the directory and file Thiseditor will allow you to paste the plugin code from the documentation

Files to be created in storescripts

bull ovmsmainjs if not already exists

bull sendlivedata2abrpjs by copying the file below

Next configure your car model API URL amp token

Note ABRP only supports live data feeds for some car models You can request a notification when support has beenadded for your car Do not feed live data using other car models Also ABRP has not yet added this OVMS pluginas a general data source so you need to disguise as ldquoTorquerdquo

If using the ABRP 4 UI

bull Login to abetterrouteplanner

bull Open ldquoSettingsrdquo enable detailed setup

bull Add your car (if ABRP has no live support for your car model it will display ldquoLive data not availablerdquo)

bull Click ldquoLink Torquerdquo click ldquoNextrdquo 3 times

bull Set the ldquoWebserver URLrdquo by config set usr abrpurl Note according to Iterniothe URL httpapiiterniocom1tlmsend should generally be used here instead of theTorque specific one displayed

bull Set the ldquoUser Email Addressrdquo (API token) by config set usr abrpuser_token

If using ABRP classic UI

bull Login to abetterrouteplanner in classic view

bull In Settingsmore Settings therersquos an item lsquoLive Car Connectionrsquo with 2 buttons lsquoSetuprsquo and lsquoView livedatarsquo

bull Click on Setup (if there is no Setup button live data support isnrsquot available for your car model)

bull Click on Torque

bull Set the ldquoWebserver URLrdquo by config set usr abrpurl

bull Set the ldquoUser Email Addressrdquo (API token) by config set usr abrpuser_token

Determine your car model code

bull Open API car models list

90 Chapter 3 Plugins

Open Vehicles

bull To improve readability optionally paste the page into JSONlintcom

bull Search for your car brand and model the code is the field following the car specification for examplerenaultzoe2052r110

bull Set the code by config set usr abrpcar_model

Finally reboot your OVMS module This was a one-time configuration

Yoursquore now ready Test it with the shell page in the embedded web server using the command script eval abrpinfo() and then with the command script eval abrponetime() You can also do it with the mobile app

312 Script code

This is a javascript code to extract in the file sendlivedata2abrpjs

Warning note the minimum firmware version 32008-147

1 2 storescriptssendlivedata2abrpjs3 4 Module plugin5 Send live data to a better route planner6 This version uses the embedded GSM of OVMS so theres an impact on data

rarr˓consumption7 requires OVMS firmware version 32008-147 minimum (for HTTP call)8 9 Version 13 2020 inf0mike (forum httpswwwopenvehiclescom)

10 11 Enable12 - install at above path13 - add to storescriptsovmsmainjs14 abrp = require(sendlivedata2abrp)15 - script reload16 17 Usage18 - script eval abrpinfo() =gt to display vehicle data to be sent to abrp19 - script eval abrponetime() =gt to launch one time the request to abrp server20 - script eval abrpsend(1) =gt toggle send data to abrp21 - (0) =gt stop sending data22 - script eval abrpresetConfig() =gt reset configuration to defaults23 24 Version 13 updates25 - Fix for rounding of fractional SOC causing abrp to report SOC off by 126 - Fix for altitude never being sent27 - New convenience method to reset config to defaults28 29 Version 12 updates30 - based now on OVMS configuration to store user token car model and url31 - review messages sent during charge32 - send a message when vehicle is on before moving to update abrp33 34 Version 11 fix and update35 - fixed the utc refreshing issue36 - send notifications37 - send live data only if necessary

(continues on next page)

31 ABRP abetterrouteplannercom 91

Open Vehicles

(continued from previous page)

38 39

40

41

42 43 Declarations44 CAR_MODEL find your car model here httpsapiiterniocom1tlmget_carmodels_

rarr˓listapi_key=32b2162f-9599-4647-8139-66e9f952837045 OVMS_API_KEY API_KEY to access to ABRP API given by the developer46 MY_TOKEN Your token (corresponding to your abrp profile)47 TIMER_INTERVAL to subscribe to a ticker event48 URL url to send telemetry to abrp following httpsiterniocomindexphp

rarr˓iternio-telemetry-api49 CR Carriage Return for console prints50 51 objTLM JSON object containing data read52 objTimer timer object53 54

55 const CAR_MODEL = 56 const OVMS_API_KEY = 32b2162f-9599-4647-8139-66e9f952837057 const MY_TOKEN = ----58 const TIMER_INTERVAL = ticker60 every minute59 const EVENT_MOTORS_ON = vehicleon60 const URL = httpapiiterniocom1tlmsend61

62 const DEFAULT_CFG = 63 url URL64 user_token MY_TOKEN65 car_model CAR_MODEL66 67

68 const CR = n69

70 var objTLM71 var objTimer objEvent72 var sHasChanged = 73 var bMotorsOn = false74

75 initialise from default76 var abrp_cfg = JSONparse(JSONstringify(DEFAULT_CFG))77

78 check if json object is empty79 function isJsonEmpty(obj) 80 for(var key in obj) 81 if(objhasOwnProperty(key))82 return false83 84 return true85 86

87 Read amp process config88 function readConfig() 89 check if config exist90 var read_cfg = OvmsConfigGetValues(usr abrp)91 print(JSONstringify(read_cfg) + CR)92 if (isJsonEmpty(read_cfg) == true)

(continues on next page)

92 Chapter 3 Plugins

Open Vehicles

(continued from previous page)

93 no config yet set the default values94 OvmsConfigSetValues(usrabrpabrp_cfg)95 else 96 config existing97 abrp_cfgurl = read_cfgurl98 abrp_cfguser_token = read_cfguser_token99 abrp_cfgcar_model = read_cfgcar_model

100 101 102

103 Make json telemetry object104 function InitTelemetryObj() 105 return 106 utc 0107 soc 0108 soh 0109 speed 0110 car_model abrp_cfgcar_model111 lat 0112 lon 0113 alt 0114 ext_temp 0115 is_charging 0116 batt_temp 0117 voltage 0118 current 0119 power 0120 121 122

123 Fill json telemetry object124 function UpdateTelemetryObj(myJSON) 125 if(myJSON)126 if the data object is undefined or null then return early127 return false128 129 var read_num = 0130 var read_str = 131 var read_bool = false132

133 sHasChanged = 134

135 if (bMotorsOn) 136 sHasChanged = _MOTORS-ON137 bMotorsOn = false138 139

140 using Mathfloor avoids rounding up of 5 values to next whole number141 as some vehicles report fractional values Abrp seems to only support integer

rarr˓values142 read_num = Mathfloor(Number(OvmsMetricsValue(vbsoc)))143 if (myJSONsoc = read_num) 144 myJSONsoc = read_num145 sHasChanged += _SOC + myJSONsoc + 146 147

148 read_num = Number(OvmsMetricsValue(vbsoh))(continues on next page)

31 ABRP abetterrouteplannercom 93

Open Vehicles

(continued from previous page)

149 if (myJSONsoh = read_num) 150 myJSONsoh = read_num151 sHasChanged += _SOH + myJSONsoh + 152 153

154 if ( (myJSONsoh + myJSONsoc) == 0 ) 155 Sometimes the canbus is not readable and abrp doesnt like 0 values156 print(canbus not readable reset module and then put motors on + CR)157 return false158 159

160 myJSONlat = OvmsMetricsAsFloat(vplatitude)toFixed(3)161 above code line works except when value is undefined after reboot162

163 read_num = OvmsMetricsAsFloat(vplatitude)164 read_num = read_numtoFixed(3)165 if (myJSONlat = read_num) 166 myJSONlat = read_num167 sHasChanged += _LAT + myJSONlat + deg168 169

170 read_num = Number(OvmsMetricsAsFloat(vplongitude))171 read_num = read_numtoFixed(3)172 if (myJSONlon = read_num) 173 myJSONlon = read_num174 sHasChanged += _LON + myJSONlon + deg175 176

177 read_num = Number(OvmsMetricsAsFloat(vpaltitude))178 read_num = read_numtoFixed(1)179 if (read_num lt= (myJSONalt - 2) || read_num gt= (myJSONalt + 2)) 180 myJSONalt = read_num181 sHasChanged += _ALT + myJSONalt + m182 183

184 read_num = Number(OvmsMetricsValue(vbpower))185 myJSONpower = read_numtoFixed(1)186

187 myJSONspeed=Number(OvmsMetricsValue(vpspeed))188 myJSONbatt_temp=Number(OvmsMetricsValue(vbtemp))189 myJSONext_temp=Number(OvmsMetricsValue(vetemp))190 myJSONvoltage=Number(OvmsMetricsValue(vbvoltage))191 myJSONcurrent=Number(OvmsMetricsValue(vbcurrent))192

193 myJSONutc = Mathtrunc(Datenow()1000)194 myJSONutc = OvmsMetricsValue(mtimeutc)195

196 read_bool = Boolean(OvmsMetricsValue(vccharging))197 vccharging is also on when regen =gt not wanted here198 read_str = OvmsMetricsValue(vcstate)199 if ( (read_str == charging) || (read_str == topoff) ) 200 myJSONis_charging = 1201 read_str = OvmsMetricsValue(vcmode)202 if (sHasChanged = ) 203 sHasChanged += _CHRG + read_str + ( + OvmsMetricsValue(vccharging)

rarr˓+ )204 print(Charging in mode + read_str + CR)

(continues on next page)

94 Chapter 3 Plugins

Open Vehicles

(continued from previous page)

205 206 else 207 myJSONis_charging = 0208 209

210 myJSONcar_model = abrp_cfgcar_model211

212 return (sHasChanged == )213 214

215 Show available vehicle data216 function DisplayLiveData(myJSON) 217 var newcontent = 218 newcontent += altitude = + myJSONalt + m + CR GPS altitude219 newcontent += latitude = + myJSONlat + deg + CR GPS latitude220 newcontent += longitude= + myJSONlon + deg + CR GPS longitude221 newcontent += ext temp = + myJSONext_temp + degC + CR Ambient

rarr˓temperature222 newcontent += charge = + myJSONsoc + + CR State of charge223 newcontent += health = + myJSONsoh + + CR State of health224 newcontent += bat temp = + myJSONbatt_temp + degC + CR Main battery

rarr˓momentary temperature225 newcontent += voltage = + myJSONvoltage + V + CR Main battery

rarr˓momentary voltage226 newcontent += current = + myJSONcurrent + A + CR Main battery

rarr˓momentary current227 newcontent += power = + myJSONpower + kW + CR Main battery

rarr˓momentary power228 newcontent += charging = + myJSONis_charging + CR yes = currently

rarr˓charging229 print(newcontent)230 231

232 function InitTelemetry() 233 objTLM = InitTelemetryObj()234 sHasChanged = 235 236

237 function UpdateTelemetry() 238 var bChanged = UpdateTelemetryObj(objTLM)239 if (bChanged) DisplayLiveData(objTLM) 240 return bChanged241 242

243 function CloseTelemetry() 244 objTLM = null245 sHasChanged = 246 247

248 http request callback if successful249 function OnRequestDone(resp) 250 print(response=+JSONstringify(resp)+CR)251 OvmsNotifyRaise(info usrabrpstatus ABRP + sHasChanged)252 253

254 http request callback if failed255 function OnRequestFail(error)

(continues on next page)

31 ABRP abetterrouteplannercom 95

Open Vehicles

(continued from previous page)

256 print(error=+JSONstringify(error)+CR)257 OvmsNotifyRaise(info usrabrpstatus ABRP + JSONstringify(error))258 259

260 Return full url with JSON telemetry object261 function GetUrlABRP() 262 var urljson = abrp_cfgurl263 urljson += 264 urljson += api_key= + OVMS_API_KEY265 urljson += amp266 urljson += token= + abrp_cfguser_token267 urljson += amp268 urljson += tlm= + encodeURIComponent(JSONstringify(objTLM))269 print(urljson + CR)270 return urljson271 272

273 Return config object for HTTP request274 function GetURLcfg() 275 var cfg = 276 url GetUrlABRP()277 done function(resp) OnRequestDone(resp)278 fail function(err) OnRequestFail(err)279 280 return cfg281 282

283 function SendLiveData() 284 if (UpdateTelemetry()) 285 HTTPRequest( GetURLcfg() )286 287 288

289 function Reactivate_MotorsOn() 290 bMotorsOn = true291 SendLiveData()292 293

294 function InitTimer() 295 objTimer = PubSubsubscribe(TIMER_INTERVAL SendLiveData)296 objEvent = PubSubsubscribe(EVENT_MOTORS_ON SendLiveData)297 298

299 function CloseTimer() 300 PubSubunsubscribe(objEvent)301 PubSubunsubscribe(objTimer)302 objEvent = null303 objTimer = null304 305

306 API method abrponetime()307 Read and send data but only once no timer launched308 exportsonetime = function() 309 readConfig()310 InitTelemetry()311 SendLiveData()312 CloseTelemetry()

(continues on next page)

96 Chapter 3 Plugins

Open Vehicles

(continued from previous page)

313 314

315 API method abrpinfo()316 Do not send any data just read vehicle data and writes in the console317 exportsinfo = function() 318 readConfig()319 InitTelemetry()320 UpdateTelemetry()321 CloseTelemetry()322 323

324 API method abrpresetConfig()325 Resets stored config to default326 exportsresetConfig = function() 327 OvmsConfigSetValues(usrabrp DEFAULT_CFG)328 print(JSONstringify(abrp_cfg))329 OvmsNotifyRaise(info usrabrpstatus ABRPconfig changed)330 331

332 API method abrpsend()333 Checks every minut if important data has changed and send it334 exportssend = function(onoff) 335 if (onoff) 336 readConfig()337 if (objTimer = null) 338 print(Already running + CR)339 return340 341 print(Start sending data + CR)342 InitTelemetry()343 SendLiveData()344 InitTimer()345 OvmsNotifyRaise(info usrabrpstatus ABRPstarted)346 else 347 if (objTimer == null) 348 print(Already stopped + CR)349 return350 351 print(Stop sending data + CR)352 CloseTimer()353 CloseTelemetry()354 OvmsNotifyRaise(info usrabrpstatus ABRPstopped)355 356

313 Usage

How to make it run

bull install as described in lsquoInstallationrsquo

bull add to storescriptsovmsmainjs abrp = require(sendlivedata2abrp)

bull script reload

With command lines in the OVMS android or iOS app in the messages part

31 ABRP abetterrouteplannercom 97

Open Vehicles

bull script eval abrpinfo() =gt to display vehicle data to be sent to abrp

bull script eval abrponetime() =gt to launch one time the request to abrp server

bull script eval abrpsend(1) =gt toggle send data to abrp

bull script eval abrpsend(0) =gt stop sending data

bull script eval abrpresetConfig() =gt reset configuration to defaults

Also in the messages part configuration can be updated with

bull config set usr abrpcar_model ltvaluegt

bull config set usr abrpurl ltvaluegt

bull config set usr abrpuser_token ltvaluegt

32 AuxBatMon 12V History Chart

Web chart showing last 24 hours of 12V battery metrics (similar to Android App)

Version 23 by Michael Balzer ltdexterdexters-webdegt

The module plugin records the relevant 12V battery metrics (voltage reference voltage current charger and environ-ment temperatures) once per minute for up to 24 hours by default

The web plugin renders these recordings into a time series chart and continues feeding live updates into the chart Thechart is zoomable and can be panned along the X axis

Since version 20 metrics history data is stored in a file and restored automatically on rebootreload This needsOVMS firmware gt= 32008-235 to work (will fallback to no saving on earlier versions)

98 Chapter 3 Plugins

Open Vehicles

Version 23 changes the file and transfer encoding from JSON to CBOR Upgrading is strongly recommended asthis has a substantial performance gain for both the module (scripting engine) and the web user interface (loading thechart)

321 Installation

1 Save auxbatmonjs as storescriptslibauxbatmonjs

2 Add line to storescriptsovmsmainjs

bull auxbatmon = require(libauxbatmon)

3 Issue script reload or evaluate the require line

4 Install auxbatmonhtm web plugin recommended setup

bull Type Page

bull Page usrauxbatmon

bull Label 12V History

bull Menu Tools

bull Auth Cookie

322 Configuration

No live config currently You can customize the sample interval (default 60 seconds) and the history size (default24 hours) by changing the constants in the code Take care to match a customization in both the module and the webplugin

The persistent history storage file is storeusrauxbatmoncbor by default It needs ~30 kB with the defaultconfiguration If space is tight on your store partition you can change the file location to sd in the sourcecode

323 Plugin API

auxbatmondump(CBOR) -- dump recorded history data in CBOR format (binary)auxbatmondump() -- dump recorded history data in JSON formatauxbatmondump() -- get a copy of the history data object

33 ChgInd Charge State Indicator

Control three LEDs to indicate charging amp SOC level

Version 10 by Michael Balzer ltdexterdexters-webdegt

Following an idea by ldquogreen_foxrdquo on the german Twizy forum (not limited to the Twizy) to implement an externallyvisible charge indicator

Use a red a green and a blue LED to signal charge state

bull OFF = not charging

bull RED = charging SOC below 20

33 ChgInd Charge State Indicator 99

Open Vehicles

bull YELLOW (RED+GREEN) = charging SOC 20 80

bull GREEN = charging SOC above 80

bull BLUE = fully charged (held for 15 minutes)

This plugin uses three EGPIO lines to control the three LEDs (KISS) By using a shift register this could be reducedto two lines by using a serial protocol to one line The latter would need protocol support in the EGPIO (todo)

331 Installation

1 Save chgindjs as storescriptslibchgindjs

2 Add line to storescriptsovmsmainjs

bull chgind = require(libchgind)

3 Issue script reload or evaluate the require line

332 Configuration

EGPIO ports to useconst LED_red = 4 EIO_3const LED_green = 5 EIO_4const LED_blue = 6 EIO_5

Time to hold BLUE state after charge stopconst holdTimeMinutes = 15

333 Plugin API

chgindset(state) -- set LED state (offredyellowgreenblue)

34 Edimax Smart Plug Control

Smart Plug control for Edimax models SP-1101W SP-2101W et al

Version 20 by Michael Balzer ltdexterdexters-webdegt

Note may need HTTPrequest() digest auth support to work with newer Edimax firmware (untested)

The smart plug can be bound to a defined location Automatic periodic recharging or charge stop can be configuredvia main battery SOC level andor 12V battery voltage level The plugin can also switch off power at the charge stopevent of the main andor 12V battery

341 Installation

1 Save edimaxjs as storescriptslibedimaxjs

2 Add line to storescriptsovmsmainjs

bull edimax = require(libedimax)

3 Issue script reload

100 Chapter 3 Plugins

Open Vehicles

4 Install edimaxhtm web plugin recommended setup

bull Type Page

bull Page usredimax

bull Label Edimax Smart Plug

bull Menu Config

bull Auth Cookie

5 Install edimax-statushtm web plugin recommended setup

bull Type Hook

bull Page status

bull Hook bodypost

The edimax-statushtm plugin adds power control to the Status pagersquos vehicle panel

342 Configuration

Use the web frontend for simple configuration

Param Instance Descriptionusr edimaxip Edimax IP addressusr edimaxuser username admin by defaultusr edimaxpass password 1234 by defaultusr edimaxlocation optional restrict auto switch to this locationusr edimaxsoc_on optional switch on if SOC atbelowusr edimaxsoc_off optional switch off if SOC ataboveusr edimaxchg_stop_off optional yes = switch off on vehiclechargestopusr edimaxaux_volt_on optional switch on if 12V level atbelowusr edimaxaux_volt_off optional switch off if 12V level ataboveusr edimaxaux_stop_off optional yes = switch off on vehiclecharge12vstop

343 Usage

script eval edimaxget()script eval edimaxset(on | off)script eval edimaxinfo()

Note get() amp set() do an async update (if the location matches) the result is logged Use info() to show thecurrent state

344 Events

usredimaxonusredimaxoffusredimaxerror

34 Edimax Smart Plug Control 101

Open Vehicles

35 Foglight Speed Adaptive Foglight

Automatic speed adaptive fog light using OVMS GPIO port

bull foglightjs ndash module script

bull foglighthtm ndash web dashboard extension

Details httpsdocsopenvehiclescomenlatestcomponentsovms_scriptdocsfoglighthtml

36 PwrMon Trip Power Chart

Web chart showing average speed power amp energy use on the road

Version 12 by Michael Balzer ltdexterdexters-webdegt

The plugin calculates average speed (kph) power (kW) amp energy use (Wpk = Whkm) from the odometer altitudeand energy counters (metrics vbenergyused amp vbenergyrecd) so the vehicle needs to provide thesewith reasonable precision amp resolution

The optional module plugin continuously records and stores the metrics history so the chart can load the last 20 km(by default) when opened The chart will then continue to add live metrics data Without the module plugin the chartwill only display live data

The chart is zoomable and can be panned along the X axis The four data series can be selected and shownhidden asusual by clicking on the series names in the legend click into the chart to highlight a specific data point

The live data may be more accurate than the data stored by the module plugin as it will react directly to the odometerchange while the module plugin can only check the odometer once per second

Version 12 changes the file and transfer encoding from JSON to CBOR Upgrading is strongly recommended asthis has a substantial performance gain for both the module (scripting engine) and the web user interface (loading thechart)

102 Chapter 3 Plugins

Open Vehicles

361 Installation

1 Install pwrmonhtm web plugin recommended setup

bull Type Page

bull Page usrpwrmon

bull Label Trip Power Chart

bull Menu Tools

bull Auth Cookie

2 Optionally

bull Save pwrmonjs as storescriptslibpwrmonjs

bull Add line to storescriptsovmsmainjs

ndash pwrmon = require(libpwrmon)

bull Issue script reload or evaluate the require line

362 Configuration

No live config currently You can customize the sample interval (default 03 km) and the history size (default 20 km)by changing the constants in the code The storage file and interval (1 km) can also be changed

On the web plugin you can customize the live sample interval (default 03 km doesnrsquot need to match the moduleplugin) and the initial zoom (default 8 km)

The persistent history storage file is storeusrpwrmoncbor by default It needs ~10 kB with the defaultconfiguration If space is tight on your store partition you can change the file location to sd in the sourcecode or disable the file by setting an empty string as the filename

363 Plugin API

pwrmondump(CBOR) -- dump recorded history data in CBOR format (binary)pwrmondump() -- dump (print) recorded history data in JSON formatpwrmondata() -- get a copy of the history data object

37 RegenMon Regen Brake Monitor

Live monitoring for regenerative brakelight amp acceleration level

bull regenmonhtm

Details httpsdocsopenvehiclescomenlatestcomponentsovms_webserverdocsregenmonhtml

38 REPIDScan OBD2 PID Scanner UI

Web UI for the OVMS3 RE toolkitrsquos OBD2 PID scanner

Version 21 by Michael Balzer ltdexterdexters-webdegt

37 RegenMon Regen Brake Monitor 103

Open Vehicles

bull 10 Initial release

bull 20 Highlight differences between scan results

bull 21 PID step support

This is a web frontend for the re obdii scan commands

Some basic usage notes are included but you really should have some knowlegde of how accessing ECU and otheronboard devices via OBD-IIUDS works Some pointers to get started

bull httpsenwikipediaorgwikiOBD-II_PIDs

bull httpsenwikipediaorgwikiUnified_Diagnostic_Services

You will need OVMS firmware release 32015-324 or higher to be able to use all features

The UI allows to easily define and keep multiple scans along with notes Scan results of two successive runs can becompared directly The UI checks if vehicle NONE is loaded and shows a button to switch to that otherwise The CANbuses can be started from the UI as well

Scan results are shown in plain text form as delivered by the underlying commands

Feel free to improve and extend (and submit your results)

381 Installation

1 Install repidscanhtm web plugin recommended setup

104 Chapter 3 Plugins

Open Vehicles

bull Type Page

bull Page usrrepidscan

bull Label RE PID Scanner

bull Menu Tools

bull Auth Cookie

382 Usage

Warning The scanner allows to use any poll type Requests will be sent with PIDs only though but somedevices may fail to validate the request length so be careful not to use any write or control poll types

The OBD2 PID scanner performs a series of OBDUDS requests for a range of PIDs and displays the results OnlyPIDs with positive results (responses) will be shown in the results

Enter all values hexadecimal (case irrelevant) Default RXID is TXID+8 try RXID range 500-7FF if you donrsquot knowthe responding ID To send broadcast requests set TXID to 7DF and RXID to 7E8-7EF The PID range must matchthe poll type PID constraints (816 bit)

Click ldquoStartrdquo to run a scan Only one scan can be active at a time but you donrsquot need to stop a scan to start anotherrun

Scan results will be shown automatically when the scan has been completed Scanning a large range of PIDs may takesome time to get intermediate results click ldquoStatusrdquo You can also start the scan do something else and return to thetool later

Differences between two scans are highlighted in both result tabs with added PIDs being marked green (yellow innight mode) and byte value changes being marked red No highlighting is applied if the scans donrsquot share any PIDs

On the next scanner start the previous results (if any) will be copied to the ldquoPreviousrdquo tab You can switch tabs by themouse or keyboard to compare them and look for differences eg after having changed some control on the car

All inputs and outputs can be saved to and loaded from files on the module or SD card Use this to define your areasof interest so you can easily re-run a previously defined scan the next day File format is plain readable JSON so youcan continue analysis or prepare scans offline

Notes to avoid clashing of scan polls with vehicle polls use the scanner only with the vehicle module NONE TheCAN bus to use needs to have been started in active mode The scanner does not send session or tester presencemessages if you need these use the re obdii tester tool or the obdii canX request command

39 Renault Twizy

391 Dashboard-Tuneslider

Add recuperation control to the dashboard

bull dashboard-tunesliderhtm

Details httpsdocsopenvehiclescomenlatestcomponentsovms_webserverdocsplugin-twizydashboard-tunesliderhtml

39 Renault Twizy 105

Open Vehicles

392 eDriver BMS Monitor

Status monitor for the Twizy custom eDriver BMS by Pascal Ripp

Version 20 by Michael Balzer ltdexterdexters-webdegt

This is a simple web page plugin to display the standard battery cell info along with the additional custom data providedby the eDriver BMS on one page

Additional custom data

bull Main state

bull Error state

bull BMS internal temperature

bull AUX relay state

bull Cell balancing states

Note these are read from their respective custom metrics xrtbms see Custom Metrics

Overall SOC voltage current and coulombenergy counters are also shown to simplify battery capacity and currentsensor calibration

Check out the eDriver BMS Manual for details or contact Pascal in case of questions

Installation

1 Install edrvmonhtm web plugin recommended setup

bull Type Page

bull Page usredrvmon

bull Label eDriver BMS Monitor

bull Menu Vehicle

bull Auth Cookie

106 Chapter 3 Plugins

Open Vehicles

History

bull V20 ndash Added cell balancing time totals + SOC amp voltage usecharge range

bull V10 ndash Initial release

393 Page-Command

only command options as UI

Version 02 Matthias Greiling ltmatthiasgreilingdegt

Details

This view only presents commands to OVMS While driving you can choose between different drive modes Thecoloured area indicates the active drive mode Activate an other mode by touching or clicking the grey bordered areaTo change again simply click or touch again the same or another ares Furthermore you can limit the speed online topredefined values The speed limit signs are common in germany and display kmh Just activate the sign you want tobe limited to - another touch will deactivates the limit of the chosen one

Installation

1 Install page-commandhtml web plugin recommended setup

bull Type Page

bull Page usrcommand

bull Label

bull Menu Main

bull Auth Cookie

39 Renault Twizy 107

Open Vehicles

History

bull V02 ndash Simplfy backgrounds icons of command row

bull V01 ndash Initial release

394 WifiConsole

Backend for WifiConsole hardware extension

bull WifiConsolejs

Details httpsgithubcomdexterbgWifiConsole

310 VW e-Up Mii Citigo

3101 ECUToolkit VW e-Up ECU Access

Library and web UI for diagnostics and configuration of the e-Up Mii Citigo ECUs

bull Library version 05 by Michael Balzer ltdexterdexters-webdegt

bull Web UI version 01 by Michael Balzer ltdexterdexters-webdegt

108 Chapter 3 Plugins

Open Vehicles

You will need OVMS firmware release 32016-226 or higher to be able to use this

The library is meant as a general tool to access the VW ECUs It provides means to simplify sending OBDUDScommands to ECUs by ID and to automate diagnostic session loginlogout It provides methods to set the workshopcode (WSC) do security authorization do scans and codings

The web UI allows to open multiple tools for different ECUs and saveload the current setup including the tool states

Feel free to improve and extend (and submit your results)

Warning

Warning Use at your own risk This ECU toolkit is based on reverse engineering I havenrsquot had access to anyofficial documentation Itrsquos only been used and tested on few vehicles chances are there will be issues with othervehicle configurations

Note If yoursquore interested in a fully featured VW ECU tool consider buying the excellent third party tools VCDS(httpswwwross-techcomvag-com) or OBDeleven (httpsobdelevencom) which fully support all VW vehiclesincluding of course the e-Up These tools also can decode most DTCs and provide detailed information on faultconditions

310 VW e-Up Mii Citigo 109

Open Vehicles

Installation

1 Save xvu-ecujs as storescriptslibxvu-ecujs

bull Add to storescriptsovmsmainjs

ndash xvu = ecu require(libxvu-ecu)

ndash or in case you already have the xvu namespace object just add the ecu part

bull Issue script reload or evaluate the require line

2 Install xvu-ecu-toolhtm web plugin recommended setup

bull Type Page

bull Page xvuecutoolkit

bull Label ECU Toolkit

bull Menu Vehicle

bull Auth Cookie

Usage

You can use the toolkit without ignition on if you just want to review some stored backup or dry run some coding tests

The web UI shows the list of known ECUs on the left side (or upper side on mobile devices) The list can be filteredto only show ECUs installed in the car by clicking the ldquordquo button this will need ignition on so the library can accessthe CAN gateway

Open a tool by selecting the ECU to investigate then clicking the tool button below the list To switch between toolsclick on the tool tab title To close a tool click the cross mark on the tool tabrsquos title

You can save the toolkit state (ie all open tools including their data) to a file on the OVMS SD card or store partitionLoading replaces the current toolkit state by the one loaded so discards any unsaved content

Click the menu box title to collapse or expand the box Loading will automatically collapse the menu box on mobiledevices

Enable the debug log messages to see which OBDUDS commands are performed The log will be shown in the panelfooter The read only mode inhibits OBDUDS commands doing PID changes DTC clearing or security accessesThey will still be logged so you can see what would be done

If you encounter issues send me a debug log

Scan tool

The Scan tool is considered to be safe as no write operations are involved

Scan results include the current hardware amp software versions the codings and DTCs so are useful as a backup forlater reference

To do a scan turn the ignition on select the ECU to scan and click the Scan button A new tab will open and thescan will start immediately Scans take from 5 - 15 seconds depending on the number of subsystems and other systemactivity The results will be shown in the tab

110 Chapter 3 Plugins

Open Vehicles

Coding tool

The Coding tool allows to change the ECU configuration ECUs may accept invalid codings that possibly can causehardware damage so be cautious ECUs will record all your write operations Even though the toolkit reuses the lastworkshop code found in the ECU by default there still will be a log entry carrying the date of the change

Use the full coding input field to copy amp paste codings for backups amp restores eg from a former scan result Afterpasting click outside the field to validate the coding and update the bits

Subsystem codings are included in the ECU coding other than in the scan result where they are shown at the respectivesubsystem You can paste amp write only the main coding the subsystem will then not be changed

Select a byte position to view and change the individual bits of that byte Only labels for bits known to work onthe VW e-Up models have been added up to now source of this is the german GoingElectric forum amp wiki (httpswwwgoingelectricde)

To submit a changed coding to the ECU click ldquoWriterdquo Most codings donrsquot need a security code so leave the fieldempty unless ldquoWriterdquo aborts with a security clearance error Security codes can be found in the forums and officialrepair manuals

Library API

Documentation on the API methods is in preparation

As this is currently an alpha release the API is work in progress and likely to change

If yoursquore interested in using whatrsquos considered stable now or possibly even contribute please read the source andcontact me

311 Installing Module Plugins

A module plugin normally consists of a single Javascript file that needs to be placed in the storescriptslibdirectory The plugin is then loaded by a require() call which can be done manually as needed or automaticallyon boot by adding it to the storescriptsovmsmainjs file

1 Menu Tools rarr Editor

2 Cancel the open dialog

3 Paste the plugin source into the editor

4 Save as rarr storescriptslib using the name as shown in the plugin documentation

5 Open rarr (one level up) rarr ovmsmainjs

6 Add the require() call as shown in the plugin documentation

7 Save

8 Reload JS Engine

The plugin is now installed and activated

Hint you can now try out the commands provided by the plugin directly from the editor Clear the editor fill in thecommand or Javascript snippet click Evaluate JS The output will be shown below the input field

To deactivate a plugin comment out the require() call by prefixing the line with and do another JS enginereload To remove a plugin remove the require() call and delete the file using vfs rm storescriptslib

311 Installing Module Plugins 111

Open Vehicles

312 Installing Web Plugins

A web plugin normally consists of a single HTML file Web plugins can be meant to render new pages or to hook intoan existing page They need an initial registration to work

1 Menu Config rarr Web Plugins

2 (add)

3 Set type and name as suggested in the plugin documentation

4 Save

5 Edit

6 Set attributes as suggested in the plugin documentation

7 Paste the plugin source into the content area

8 Save

The plugin is now installed and activated

Hint you can use the text editor (tools menu) to change or update an already installed web plugin Simply edit theplugin file in folder storeplugin directly the system will reload the plugin as soon as you save it

To deactivate a web plugin set the state to ldquooffrdquo To remove a plugin click rarr Save

112 Chapter 3 Plugins

CHAPTER 4

BMW i3 i3s

Vehicle Type BMWI3

This vehicle type supports the BMW i3 and i3s models All model years should be supported

The OVMS support was developed Jan 2021

It was developed against the authorrsquos 2018 120Ah i3s BEV I would welcome engagement from the owner of a REXtype to further develop metrics related to the REX engine Testing by drivers of LHD models as well as those withthe smaller batteries will also be helpful

As of this release this vehicle support is read-only and cannot send commands to the car

41 Support Overview

ldquotbardquo item are still on the to-do list and are not currently supported

113

Open Vehicles

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable OBD-II cable left-handed cable worked best in my RHD carGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (or any compatible antenna)SOC Display YesRange Display YesCabin Pre-heatcool Control tbaGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display tbaCharge Status Display YesCharge Interruption Alerts YesCharge Control tbaLockUnlock Vehicle tbaValet Mode Control NoOthers 12v battery voltagecurrent battery true SOC etc

42 WARNINGS

421 Alarm behaviour

As standard the i3 will sound the alarm if anything is left connected to the OBD-II port when the car is locked

A tool like Bimmercode will allow you to disable this Alternatively you will need to disconnect the OVMS unit beforelocking the car

A future version may add a command to allow you to disable this alarm directly from your OVMS shell

422 12V Battery drain

The i3 has a small 20Ah AGM 12v battery Whilst care has been taken to minimize OVMSrsquo power usage OVMScould eventually drain this battery if the car is left unplugged and locked OVMS will also send an alert if 12V dropsunder 12V alert threshold (See 12V Calibration section)

HOWEVER If you are going to leave the car for a fews days it is recommended to unplug OVMS

43 Car status

The car is accessible over the OBD-II port when it is running (ignition on) and for a short time (40 seconds or so) afterit is turned off or the car is ldquotweakedrdquo (lock button pushed connected-drive command received etc)

Unfortunately this means that when your car is standing or charging OVMS only has intermittent access to data fromthe car

By observation whilst the car is charging it wakes up now and then (seems to be every 30 minutes) So at those timeswe can update our SOC etc

114 Chapter 4 BMW i3 i3s

Open Vehicles

Metrics ldquoveawakerdquo tells you if the car is awake or not Metric ldquoxi3sagerdquo will tell you how many minutes have passedsince we last received data from the car

You may also refer to metric xi3spollermode as follows

Mode Meaning0 Car is asleep - no OBD-II data traffic1 Car OBD-II is awake - we are seeing data traffic2 Car is ready to drive or driving3 Car is charging

44 Custom metrics

Metric name Example value Descriptionxi3sage 5Min How long since we last got data from the carxi3spollermode 0 OBD-II polling mode as explained abovexi3vbpocvavg 40646V Main battery pack - average open-circuit voltagexi3vbpocvmax 4067V Main battery pack - highest open-circuit voltagexi3vbpocvmin 4063V Main battery pack - lowest open-circuit voltagexi3vbrangebc 245km Available range per trip computer (based on current driving mode and style)xi3vbrangecomfort 217km Available range if you use Comfort modexi3vbrangeecopro 245km Available range if you use EcoPro modexi3vbrangeecoproplus 247km Available range if you use EcoPro+ modexi3vbsocactual 85 Actual physical state-of-charge of the main battery packxi3vbsocactualhighlimit 937 Highest physical charge level permitted (shown as 100 SOC)xi3vbsocactuallowlimit 105 Minimum physical charge level permitted (shown as 0 SOC)xi3vcchargecablecapacity 0A Maximum power capacity of connected charge cable per the charging interfacexi3vcchargeledstate 0 Colour of the ldquoring lightrdquo on the charging interfacexi3vcchargeplugstatus Not connected Charging cable connectedxi3vccurrentdc 0A Power flowing on the DC side of the AC chargerxi3vccurrentdclimit 0100003A Limitxi3vccurrentdcmaxlimit 16A Maximum limitxi3vccurrentphase1 0A Power being drawn on AC phase 1xi3vccurrentphase2 0A Power being drawn on AC phase 2xi3vccurrentphase3 0A Power being drawn on AC phase 3xi3vcdcchargevoltage 0V Voltage seen on the DC charger inputxi3vcdccontactorstatus open DC contactor state (closed implies we are DC charging)xi3vcdccontrolsignals 0 DC charger control signals (always see 0)xi3vcdcinprogress no DC charging in progressxi3vcdcplugconnected no Is DC charger plug connected (doesnrsquot seem to work)xi3vcderatingreasons 0 Reasons why charging rate is deratedxi3vcerror 0 Charging error codesxi3vcfailsafetriggers 0 Failsafe trigger reasonsxi3vcinterruptionreasons 0 Charging interruption reasonsxi3vcpilotsignal 0A Charge rate pilot signal being received from EVSExi3vcreadytocharge no Are we ready to chargexi3vctempgatedriver 40degC Charger gatedrive mosfet temperaturexi3vcvoltagedc 84V Charger output DC voltage being seen (for AC charging not DC)xi3vcvoltagedclimit 420V Maximum permitted DC voltge

Continued on next page

44 Custom metrics 115

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxi3vcvoltagephase1 0V Voltage seen on AC charger input phase 1xi3vcvoltagephase2 0V Voltage seen on AC charger input phase 2xi3vcvoltagephase3 0V Voltage seen on AC charger input phase 3xi3vdchargeportdc no Is the charger port DC cover open (doesnrsquot seem to work)xi3veautorecirc no Ventilation is in ldquoauto-recirculaterdquo modexi3veobdtraffic no Are we seeing OBD-II frames from the carxi3vptripconsumption 127Whkm Average consumption for the current or most recent tripxi3vpwheel1_speed 0kmh Wheel 1 speedxi3vpwheel2_speed 0kmh Wheel 2 speedxi3vpwheel3_speed 0kmh Wheel 3 speedxi3vpwheel4_speed 0kmh Wheel 4 speedxi3vpwheel_speed 0kmh Average wheel speed

45 To be researched

Can we startstop charging

Can we pre-heat

Can we lockunlock the car

Can we disable the OBD-II alarm

Still looking for the trip regen kWh

Can we get the voltage state of each individual cells rather than just the battery min max average

116 Chapter 4 BMW i3 i3s

CHAPTER 5

DBC Based Vehicles

Vehicle Type DBC

The DBC based vehicle reads a specified DBC file describing CAN bus messages and produces vehicle metrics fromthat It is under development experimental and not generally available

51 Support Overview

Function Support StatusHardware This is vehicle specific The DBC vehicle module can be configured to use any or all of

the 3 CAN busesVehicle Cable Vehicle specificGSM Antenna Standard GSM antennaGPS Antenna Vehicle specific Standard OVMS GPS supportedSOC Display Yes if DBC maps itRange Display Yes if DBC maps itGPS Location Yes if DBC maps it otherwise OVMS GPSSpeed Display Yes if DBC maps itTemperature Display Yes if DBC maps itBMS v+t Display Not currently supportedTPMS Display Yes if DBC maps itCharge Status Display Yes if DBC maps itCharge InterruptionAlerts

Yes if DBC maps it

Charge Control Not supported by DBC format maybe by extensionCabin Pre-heatcoolControl

Not supported by DBC format maybe by extension

LockUnlock Vehicle Not supported by DBC format maybe by extensionValet Mode Control Not supported by DBC format maybe by extensionOthers None

117

Open Vehicles

52 Contents

521 DBC Introduction

DBC is a CAN data description file format introduced by Vector Informatik GmbH DBC files are text files so can becreated and edited using a simple text editor like the one built into the OVMS web UI

DBC files can be used to support vehicles that donrsquot have a dedicated native adaption yet This is done using thegeneric DBC vehicle type which can use DBC files to translate CAN data into metrics

This section tries to show you how to create and use a DBC specification on the OVMS Of course yoursquoll need to knowhow to decode your vehiclersquos CAN frames first You can use the OVMS RE (reverse engineering) toolkit to identifywhich messages are on the bus and which changes correlate to actions and status on the car

Therersquos also a very good general introduction to DBC from CSS Electronics including an explanatory video httpswwwcsselectronicscomscreenpagecan-dbc-file-database-introlanguageen

DBC files only specify the passive (reading) part they donrsquot provide a means to define transmissions If you need tosend frames to request certain information you can still use the OVMS DBC engine to decode the results (instead ofdoing the decoding in C++ code) So a DBC file can be used as a base for a real vehicle module To request OBD2data during development you can use the re obdii commands

Basic Example

Warning The DBC support is usable but considered to be an alpha release The way it works may change in thefuture

This example is taken from the Twizy which sends some primary BMS status data at CAN ID 0x155 (341) Note theTwizy module actually does not use DBC this is just an example how you would decode this message if using DBC

Message example 05 96 E7 54 6D 58 00 6F

bull Byte 0 charge current limit [A] scaled by 5 no offset 05rarr 25A

bull Bytes 1+2 momentary battery current [A] big endian lower 12 bits scaled by -025 offset +500 _6 E7 rarr5825A

bull Bytes 4+5 SOC [] big endian scaled by 00025 no offset 6D 58rarr 6998

These can be translated to metrics directly

bull Charge current limit vcclimit

bull Momentary battery current vbcurrent

bull Battery SOC vbsoc

Create DBC File

Copy amp paste the following into a new editor window

VERSION DBC Example 10

BS_ 500000 00

BO_ 341 BMS_1 8 Vector__XXX

(continues on next page)

118 Chapter 5 DBC Based Vehicles

Open Vehicles

(continued from previous page)

SG_ v_c_climit 7|80+ (50) [0|35] A Vector__XXXSG_ v_b_current 11|120+ (-025500) [-500|1000] A Vector__XXXSG_ v_b_soc 39|160+ (000250) [0|100] Vector__XXX

What does this mean

bull BS_ defines the bus speed (500 kbit in this example) and bit timings (unused)

bull BO_ defines the data object a CAN frame of length 8 with ID 341 (0x155) (ldquoBMS_1rdquo is just an arbitrary name)

bull SG_ lines define the signals (values) embedded in the object (see below)

bull Vector__XXX is just a placeholder for any senderreceiver (currently unused by the OVMS)

Signals are defined by their

bull Name (= metric name with replaced by _)

bull Start position (bit position) and bit length (7|8)

bull Endianness 0 = big endian (most significant byte first) 1 = little endian (least significant byte first) (Note theDBC format documentation is wrong on this)

bull Signedness + = unsigned - = signed

bull Scaling and offset (-025500) =gt real value = raw value -025 + 500

bull Minimummaximum [-500|1000] = valid real values are in the range -500 to 1000

bull Unit eg A (ignoredirrelevant defined by the metric)

The metric to set can be given as the name of the signal You may use the metric name directly on the OVMS but toconform to the DBC standard replace the dots by _

Bit positions are counted from byte 0 upwards by their significance regardless of the endianness The first messagebyte has bits 0 7 with bit 7 being the most significant bit of the byte The second byte has bits 8 15 with bit 15being the MSB and so on

[ 7 6 5 4 3 2 1 0 ] [ 15 14 13 12 11 10 9 8 ] [ 23 22 21 20 `----- Byte 0 ----acute `------- Byte 1 --------acute `----- Byte 2

For big endian values signal start bit positions are given for the most significant bit For little endian values the startposition is that of the least significant bit

Note On endianness ldquobig endianrdquo means a byte sequence of 0x12 0x34 decodes into 0x1234 (most significantbyte first) ldquolittle endianrdquo means the same byte sequence decodes into 0x3412 (least significant byte first) ldquoBigendianrdquo is the natural way of writing numbers ie with their most significant digit coming first ldquolittle endianrdquo isvice versa Endianness only applies to values of multiple bytes single byte values are always written naturally ldquobigendianrdquo

Use DBC File

Save the DBC example as storedbctwizy1dbc (the directory will be created by the editor)

Open the shell To see debug logs issue log level debug dbc-parser and log level debug v-dbc

Note the DBC parser currently isnrsquot graceful on errors a wrong DBC file may crash the module So you shouldonly enable automatic loading of DBC files on boot when yoursquore done developing and testing it

52 Contents 119

Open Vehicles

So letrsquos first try if the DBC engine can parse our file The dbc autoload command loads all DBC files from thestoredbc directory

OVMS dbc autoloadAuto-loading DBC filesD (238062) dbc-parser VERSION parsed as DBC Example 10D (238062) dbc-parser BU_ parsed 1 nodesD (238062) dbc-parser BO_ parsed message 341D (238072) dbc-parser SG_ parsed signal v_c_climitD (238072) dbc-parser SG_ parsed signal v_b_currentD (238082) dbc-parser SG_ parsed signal v_b_soc

Looks good dbc list can tell us some statistics

OVMS dbc listtwizy1 DBC Example 10 1 message(s) 3 signal(s) 56 coverage 1 lock(s)

The coverage tells us how much of our CAN data bits are covered by signal definitions

Now letrsquos load the file into the DBC vehicle

OVMS config set vehicle dbccan1 twizy1Parameter has been set

OVMS vehicle module NONEI (1459922) v-none Generic NONE vehicle module

OVMS vehicle module DBCI (249022) v-dbc Pure DBC vehicle moduleI (249022) v-dbc Registering can bus 1 as DBC twizy1

Nice Letrsquos simulate receiving our test frame and check the decoded metrics

OVMS can can1 rx standard 155 05 96 E7 54 6D 58 00 6FOVMS me li vbsocvbsoc 6998OVMS me li vbcurrentvbcurrent 5825AOVMS me li vcclimitvcclimit 25A

So the decoding apparently works

To configure DBC mode for autostart we now just need to set the DBC vehicle mode to be loaded on vehicle startupand to enable autoloading of the DBC files from storedbc You can do so either by using the user interface pageConfig rarr Autostart (check ldquoAutoload DBC filesrdquo and set the vehicle type to ldquoDBCrdquo) or from the shell by

OVMS config set auto dbc yesOVMS config set auto vehicletype DBC

Try a reboot to see if everything works

You can now add more objects and signals to your DBC file

Note During development of a DBC file yoursquoll need to reload the file frequently The DBC engine locks the currentlyused vehicle so yoursquoll need to unload the DBC vehicle (vehicle module NONE) then reload the DBC file (dbcautoload) then reactivate the DBC vehicle (vehicle module DBC)

120 Chapter 5 DBC Based Vehicles

CHAPTER 6

DEMO Vehicle

Vehicle Type DEMO

The demonstration vehicle can be used to verify module functionality but is mostly used for development purposesThe vehicle itself updates system metrics with simulated data It can respond to charge and other similar commands

61 Support Overview

Function Support StatusHardware Demonstration data only no vehicle connectionVehicle Cable None not required (other than power)GSM Antenna Standard GSM antennaGPS Antenna None not requiredSOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display YesBMS v+t Display Not currently supportedTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control YesCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle YesValet Mode Control YesOthers None

121

Open Vehicles

122 Chapter 6 DEMO Vehicle

CHAPTER 7

Fiat 500e

Vehicle Type FT5E

The Fiat 500e vehicle support will be documented here

71 Support Overview

Function Support StatusHardware tbaVehicle Cable tbaGSM Antenna tbaGPS Antenna tbaSOC Display tbaRange Display tbaGPS Location tbaSpeed Display tbaTemperature Display tbaBMS v+t Display tbaTPMS Display tbaCharge Status Display tbaCharge Interruption Alerts tbaCharge Control tbaCabin Pre-heatcool Control tbaLockUnlock Vehicle tbaValet Mode Control tbaOthers tba

123

Open Vehicles

124 Chapter 7 Fiat 500e

CHAPTER 8

Hyundai Ioniq vFL

Hyundai Ioniq Electric (28 kWh)

bull Vehicle Type HIONVFL

bull Log tag v-hyundaivfl

bull Namespace xhi

bull Maintainers Michael Balzer

bull Sponsors Henri Bachmann

bull Credits EVNotify

125

Open Vehicles

81 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display NoGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display PartialBMS v+t Display YesSOH Display YesTPMS Display NoCharge Status Display YesCharge Interruption Alerts YesCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

82 Custom Metrics

Metric name Example value Descriptionxhibsocbms 785 Internal BMS SOCxhicstate 128 Charge state flags

83 Debug Logs

To see all PID poll results in your log set log level verbose for component v-hyundaivfl

126 Chapter 8 Hyundai Ioniq vFL

CHAPTER 9

Jaguar IPace

Vehicle Type IPace

Support for Jaguar IPace is provided by this module (c) 2021 by Didier Ernotte

91 Support Overview

Function Support StatusHardwareVehicle CableGSM AntennaGPS AntennaSOC Display YesRange DisplayGPS Location (not yet)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display (not yet)Charge Interruption AlertsCharge ControlCabin Pre-heatcool ControlLockUnlock Vehicle NoValet Mode Control NoOthers

127

Open Vehicles

92 Custom Metrics

xji_v_bat_capacity_soh_min xji_v_bat_capacity_soh_max xji_v_bat_power_soh xji_v_bat_power_soh_minxji_v_bat_power_soh_max xji_v_bat_max_regen

128 Chapter 9 Jaguar IPace

CHAPTER 10

Kia e-Niro

Vehicle Type KN

The Kia e-Niro vehicle support will be documented here

101 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable 9658635 Kia OBD-II to DB9 Data Cable for OVMSGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display Yes (based on consumption of past 20 trips longer than 1km)GPS Location YesSpeed Display Not currently supportedTemperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control Not currently supportedCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle YesValet Mode Control Not currently supportedOthers ODO Not currently supported

129

Open Vehicles

102 OBD-II cable

The Kia e-Niro have one CAN-bus available on the OBD-II port D-can You can use the standard OBD-II to DB9cable from Fasttech

In case you want to build your own cable herersquos the pinout

J1962-M DB9-F Signal4 3 Chassis Power GND6 7 CAN-0H (C-can High)14 2 CAN-0L (C-can Low)16 9 +12V Vehicle Power

A simple approach is to buy an OBDII (J1962-M) pigtail and solder the DB9-F connector end appropriately

103 Configuration

TODO Configuration is quite similar to the Kia Soul so please check that out Please use the Web based configuration

104 Estimated Range

Currently there is no known way to get the estimated range directly from the car so the estimated range is calculatedby looking at the consumption from the last 20 trips that are longer than 1 km

105 12V battery drain

OVMS will eventually drain the 12V battery but steps have been taken to minimize the drain However if you aregoing to leave the car for a fews days it is recommended to unplug OVMS OVMS will send an alert if 12V dropsunder 12V alert threshold See 12V Calibration section

130 Chapter 10 Kia e-Niro

CHAPTER 11

Kia Soul EV

Vehicle Type KS

The Kia Soul EV vehicle support will be documented here

111 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable 9658635 Kia OBD-II to DB9 Data Cable for OVMSGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display Temperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control Not currently supportedCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle YesValet Mode Control Not currently supportedOthers

131

Open Vehicles

112 OBD-II cable

The Kia Soul EV have two different CAN-busses available on the OBD-II port C-can and M-can

C-can is the main can-bus and M-can is the multimedia bus The latter one is not necessary for OVMS but somemetrics are fetched from the M-bus and these metrics will be empty if you donrsquot have the proper cable The standardOBD-II to DB9 cable from Fasttech supports only C-can so make sure you buy the Kia Soul specific one

In case you want to build your own cable herersquos the pinout

J1962-M DB9-F Signal1 5 CAN-1H (M-can High)4 3 Chassis Power GND6 7 CAN-0H (C-can High)9 4 CAN-1L (M-can Low)14 2 CAN-0L (C-can Low)16 9 +12V Vehicle Power

A simple approach is to buy an OBDII (J1962-M) pigtail and solder the DB9-F connector end appropriately

113 Configuration

There are a few Kia Soul EV specific settings that you have to consider in order to get the most out of OVMS Theseare battery size real life ideal range remote command pincode and charge port remote control

114 Battery size

Up until the 2018 version of Kia Soul all models had a 27kWh battery The 2018-version have a 30kWh batteryOVMS is by default set up with 27000Wh but you can change this configuration to fit your car using this commandin the OVMS-shell

config set xks cap_act_kwh 27000

NB Even though it says cap_act_kwh the number must be in Wh

115 Real life ideal range

Even though the Kia Soul EV is equipped with a pretty good and conservative GOM most experienced drivers knowhow far the car can go on a charge This is what we call the ideal range You can set the ideal range in kilometersexperienced at 20 degrees celsius by using this command

config set xks maxrange 160

This setting is set to 160 km by default and matches the author driving a 2015 Kia Soul Classic in 20 degrees insouthern Norway Your mileage may vary so please set it accordingly

The ideal range as shown in the OVMS APP are then derived from this number multiplied by the state of charge andadjusted using a combination of the outside temperature and the battery temperature

132 Chapter 11 Kia Soul EV

Open Vehicles

116 Open charge port using key fob

By default OVMS listens for the the third button on the key fob and opens the charge port if Pressed If you donrsquotwant this behaviour you can disable it by using this command

config set xks remote_charge_port 0

117 Security pin code for remote commands

Remote commands like lock and unlock doors among others require a pin code This pin code can be set using theweb configuration or using this command

config set password pin 1234

Please set this pin as soon as possible

118 Soul specific metrics

NB Not all metrics are correct or tested properly This is a work in progress

There are a lot of extra metrics from the Kia Soul Herersquos the current ones

Metric Descriptionxksbcellvoltmax The highest cell voltagexksbcellvoltmaxno The cell number with the highest voltagexksbcellvoltmin The lowest cell voltagexksbcellvoltminno The cell number with the lowest voltagexksbcelldetmax The highest registered cell deterioration in percentxksbcelldetmaxno The cell with the highest registered deteriorationxksbcelldetmin The lowest registered cell deterioration in percentxksbcelldetminno The cell with the lowest registered deteriorationxksbmintemp The lowest temperature in the batteryxksbmaxtemp The highest temperature in the batteryxksbinlettemp The air temperature at the air inlet to the batteryxksbheat1temp The temperature of the battery heater 1xksbheat2temp The temperature of the battery heater 2xksbbmssoc The internal state of charge from BMSxkscpower Charge power in kWxkscspeed The charge speed in kilometer per hourxksldcoutvolt The voltage out of the low voltage DC converterxksldcinvolt The voltage into the low voltage DC converterxksldcoutamps The power drawn from the low voltage DC converterxksldctemp The temperature of the LDCxksobcpilotduty The duty cycle of the pilot signalxkselowbeam Low beam onoffxksehighbeam High beam onoffxkseinsidetemp Actual cabin temperaturexkseclimatetemp Climate temperature settingxkseclimatedriveronly Climate is set to driver onlyxkseclimateresirc Climate is set to recirculate

Continued on next page

116 Open charge port using key fob 133

Open Vehicles

Table 1 ndash continued from previous pageMetric Descriptionxkseclimateauto Climate is set to autoxkseclimateac Air condition onoffxkseclimatefanspeed Climate fan speedxkseclimatemode Climate modexksepreheattimer1enabled Preheat timer 1 enableddisabledxksepreheattimer2enabled Preheat timer 2 enableddisabledxksepreheating Preheating onoffxkseposdisttodest Distance to destination (nav unit)xkseposarrivalhour Arrival time hour part (nav unit)xkseposarrivalminute Arrival time minute part(nav unit)xkseposstreet Current street Or Next streetxksvseatbeltdriver Seat belt sensorxksvseatbeltpassenger Seat belt sensorxksvseatbeltbackright Seat belt sensorxksvseatbeltbackleft Seat belt sensorxksvtractioncontrol Traction control onoffxksvcruisecontrolenabled Cruise control enableddisabledxksvemergencylights Emergency lights enableddisabledxksvsteeringmode Steering mode Sport comfort normalxksvpowerusage Power usage of the carxksvtripconsumptionkWh100km Battery consumption for current tripxksvtripconsumptionkmkWh Battery consumption for current trip

Note that some metrics are polled at different rates than others and some metrics are not available when car is off Thismeans that after a restart of the OVMS some metrics will be missing until the car is turned on and maybe driven forfew minutes

Climate and navigation-metrics are fetched from navigation unit and needs the Kia Soul compatible OBDII-cable

119 Soul specific shell commands

There are a few shell commands made for the Kia Soul Some are read only others can enable functions and some areused to write directly to a ECU and must therefore be used with caution

1191 Read only commands

xks trip

Returns info about the last trip from you put the car in drive (D or B) and til you parked the car

xks tpms

Shows the tire pressures

xks aux

Prints out the voltage level of the auxiliary battery

xks vin

134 Chapter 11 Kia Soul EV

Open Vehicles

Prints out some more information taken from the cars VIN-number Not complete

1192 Active Commands

xks trunk ltpin codegt

Opens up the trunk

xks chargeport ltpin codegt

Opens up the charge port

xks ParkBreakService ltonoffgt

Not yet working

xks IGN1 ltonoffgtltpingt

Turn on or off IGN1-relay Can be used to wake up part of the car

xks IGN2 ltonoffgtltpingt

Turn on or off IGN2-relay Can be used to wake up part of the car

xks ACC ltonoffgtltpingt

Turn on or off ACC-relay Can be used to wake up part of the car

xks START ltonoffgtltpingt

Turn on or off START-relay Can be used to wake up part of the car

xks headlightdelay ltonoffgt

Turn onoff the ldquofollow me homerdquo head light delay function

xks onetouchturnsignal lt0=Off 1=3 blinks 2=5 blinks 3=7 blinksgt

Configure one touch turn signal settings

xks autodoorunlock lt1=Off 2=On vehicle off 3=On shift to P 4=On driver doorunlockgt

Configure auto door unlock settings

xks autodoorlock lt0=Off 1=On speed 2=On shiftgt

Configure auto door unlock settings

119 Soul specific shell commands 135

Open Vehicles

1193 ECU-write commands

These commands are for the extra playful people Use with caution

xks sjb ltb1gtltb2gtltb3gt

Send command to smart junction box

xks bcm ltb1gtltb2gtltb3gt

Send command to body control module

1110 12V battery drain

OVMS will eventually drain the 12V battery but steps have been taken to minimize the drain However if you aregoing to leave the car for a fews days it is recommended to unplug OVMS

136 Chapter 11 Kia Soul EV

CHAPTER 12

Maxus eDeliver3

Vehicle Type MED3

The Maxus eDeliver3 will be documented here

121 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display NoTemperature Display Yes (External Temp and Battery)BMS v+t Display NoTPMS Display NoCharge Status Display NoCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

137

Open Vehicles

138 Chapter 12 Maxus eDeliver3

CHAPTER 13

Mercedes-Benz B250E W242

Vehicle Type SE

The Mercedes-Benz B-Klasse Electric Drive will be documented here

131 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display NoRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display NoBMS v+t Display NoTPMS Display NoCharge Status Display NoCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

139

Open Vehicles

132 Contents

1321 Standard Metrics

Metric name Notesms_v_mot_rpmms_v_env_throttle Resolution of 04 ms_v_pos_speed Resolution of 01 kmhms_v_pos_odometerResolution of 01 kmms_v_bat_12v_voltageResolution of 01 Vms_v_bat_power Car reports percents so the kW is just calculated by multiplying by 132 kW Negative side is

saturated to -50 kW This is just guess workms_v_bat_range_estms_v_bat_consumptionInstantious consumption Whkmms_v_tpms__pms_v_env_cabinsetpointThere are two figures left and right Using just one for now

1322 Custom Metrics

Metric name Example value Descriptionxmbvdisplaytripreset 27332km Dashbord Trip value since Resetxmbvdisplaytripstart 175km Dashbord Trip value since Start (today)xmbvdisplayconsumptionstart 259 kWh Dashbord Trip consumption since Start (today)xmbvdisplayaccel 89 Eco score on acceleration over last 6 hoursxmbvdisplayconst 18 Eco score on constant driving over last 6 hoursxmbvdisplaycoast 100 Eco score on coasting over last 6 hoursxmbvdisplayecoscore 69 Eco score shown on dashboard over last 6 hoursxmbvfl_speed 3783 kmh Front Left wheel speedxmbvfr_speed 3785 kmh Front Right wheel speedxmbvrl_speed 3780 kmh Rear Left wheel speedxmbvrr_speed 3782 kmh Rear Right wheel speed

140 Chapter 13 Mercedes-Benz B250E W242

CHAPTER 14

MG EV

Vehicle Types MG EV (UKEU) amp MG EV (TH)

These vehicle types support the MG ZS EV (2019-) MG5 is not yet supported in this build

141 Variants

MG ZS EVs sold in different countries seem to possess different behaviours This is why we have developed 2 differentvehicle types to support the different requirements

1411 Known Countries

Coun-try

Zombiemode

Requires GWM authenti-cation

Poll BCM causesalarm

Suggested vehicle type touse

UKEU Y N Y UKEUThai-land

N Y N TH

Aus-tralia

N N N TH

Zombie mode is when the gateway module (GWM) enters the locked state and no PIDs can be accessed This happens for UKEU cars when

1 Charger is plugged in without power car is locked and goes to sleep

2 Charger is then powered on and car starts charging

GWM authentication is required for Thai cars as GWM will be locked and no PIDs can be accessed (simiarly toZombie mode but this happens all the time rather than just during the above scenario) Note GWM authenticationdoes not work as a mitigation for UKEUrsquos Zombie mode

When the BCM is polled UKEU carsrsquo alarm (horn) can go off so this is disabled in the UKEU code

141

Open Vehicles

1412 Other Countries

For cars from other countries to decide which vehicle type you should use start off by trying the MG EV (TH) typefirst because Zombie mode mitigation has its side effects (see module notes below) and polling the BCM allows theOVMS to get more data from the car

You can follow these steps to see which variant may be suitable for your car

1 Select MG EV (TH) and use the car as you would normally Keep an eye on shell for log prints to see ifany problems occur

2 If the alarm goes off sometimes (like when doors are locked using remote) try switch to MG EV (UKEU)

3 If you do not get any alarm try put the car into Zombie mode

4 If OVMS is unable to get data (like no charging details appear on the app) try switch to MG EV (UKEU)

142 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 2019-Vehicle Cable Right hand OBDII cable (RHD) Left hand OBDII cable (LHD)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (or any compatible antenna)SOC Display YesRange Display Yes (BMS calculated and WLTP range from SoC)Cabin Pre-heatcool Control NoGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control NoLockUnlock Vehicle NoValet Mode Control NoOthers Daytime Running Light Control

143 Shell Commands

softver Get software version of ECUsdrl [on | off] Turn onoff daytime running lightsdrln [on | off] Turn onoff daytime running lights without doing BCM authentication first (for de-

bugging purposes)auth [all | gwm |bcm]

Authenticate with specified ECU lsquoauth allrsquo will authenticate GWM then BCM

142 Chapter 14 MG EV

Open Vehicles

144 Module notes

The code for each vehicle type has these behaviours

Vehicle type Zombie mode mitigation GWM authentication Poll BCMUKEU Y N NTH N Y Y

The MG EV module now monitors (and automatically calibrates) the 12V status and will automatically start pollingthe car for data when the 12V battery voltage is equal to or greater than 129V When it is below 129V it willautomatically stop polling (after a 50s delay) to not drain the 12V battery

Poll states

0 Lis-tenOnly

the OVMS module is quiet and stops sending polls

1 Charg-ing

the OVMS module sends charging specific queries

2 Driving the OVMS module sends driving specific queries3 Backup the OVMS module cannot get data from the car when it is charging so just retries SoC queries

This is unused in TH code

1441 UKEU spec

The car is accessible over the OBD port when it is running (ignition on) and for around 40 seconds after it is turnedoff or the car is ldquotweakedrdquo (lock button pushed etc)

The OBD port may be kept awake by using the ldquotester presentrdquo message to the gateway ECU This keeps a lot ofsystems awake and draws roughly 5A on the 12V bus so itrsquos not a good idea to do

The Gateway (GW GWM) is the keeper of all the data of the car and will enter a locked state when it is woken by thecar starting charging and the car is locked This we have called ldquoZombie Moderdquo and we have developed an overridefor this

This override however causes a few strange things to happen

bull If Zombie mode override is active the car will not unlock the charge cable To fix this dusrupt the chargeand wait 50s for OVMS to go back to sleep and the cable should release (or unplug OVMS)

bull Zombie mode override resets the ldquoAccumulated Total Triprdquo on the Cluster

bull Zombie mode override sets the gearshift LEDs switch on

145 Development notes

Developers welcome Follow the developerrsquos guide on httpswwwopenvehiclescomdevelopers to get started Joinour slack group (see below) to discuss the nerdy details

146 Community channels

Forum httpswwwmgevscom

144 Module notes 143

Open Vehicles

Slack httpsmgevhackersslackcom

144 Chapter 14 MG EV

CHAPTER 15

Mitsubishi Trio

Vehicle Type MI

This should be used to support the Mitsubishi i-Miev (Citroen C-Zero Peugeot iOn) vehicles

151 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display NoBMS v+t Display YesTPMS Display Not currently supportedCharge Status Display YesCharge Interruption Alerts YesCharge Control NoCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle Not currently supportedValet Mode Control Not currently supportedOthers

145

Open Vehicles

152 Trio specific metrics

NB Not all metrics are correct or tested properly This is a work in progress

Metric Descriptionxmibpowermin The battery minimum power usagexmibpowermax The battery maximum power usagexmielowbeam Low beam light statusxmiehighbeam High beam light statusxmiefrontfog Front fog light statusxmierearfog Rear fog light statusxmierightblinker Right blinker statusxmieleftblinker Left blinker statusxmiewarninglight Warning light statusxmickwhdc Charge energy on DC side in kWhxmickwhac Charge energy on AC side in kWhxmicefficiency Charge efficiency (DCAC)xmicpowerac Charge power on AC side in kWxmicpowerdc Charge power on DC side in kWxmictime Charge time (hmmss)xmicsocstart Charge start soc in xmicsocstop Charge stop soc in xmieheatingamp Heating energy usage in Axmieheatingwatt Heating energy usage in Wxmieheatingtempreturn Heater return water temperaturexmieheatingtempflow Heater flow water temperaturexmieacamp AC energy usage in Axmieacwatt AC energy usage in Wxmietrippark Trip start odometer in kmxmietripparkenergyused Energy used in kWhxmietripparkenergyrecuperated Recuperated energy in kWhxmietripparkheatingkwh Heater energy usage on trip in kWhxmietripparkackwh AC energy usage on trip in kWhxmietripparksocstart Trip start socxmietripparksocstop Trip stop socxmietripcharge Trip start odometer in km since chargexmietripchargeenergyused Energy used in kWh since chargexmietripchargeenergyrecuperated Recupe energy in kWh since chargexmietripchargeheatingkwh Heating usage in kWh since chargexmietripchargeackwh AC energy usage in kWh since chargexmietripchargesocstart Trip start soc since chargexmietripchargesocstop Trip stop soc since charge

Note that some metrics are polled at different rates than others and some metrics are not available when car is off Thismeans that after a restart of the OVMS some metrics will be missing until the car is turned on and maybe driven forfew minutes

146 Chapter 15 Mitsubishi Trio

Open Vehicles

153 Custom Commands

1531 Read only commands

xmi trip

Returns info about the last trip from you start the car with key

xmi tripc

Returns info about the trip since last charge

xmi aux

Prints out the voltage level of the auxiliary battery

xmi vin

Prints out some more information taken from the cars VIN-number

154 Trio Regen Brake Light Hack

1541 Parts required

bull 1x DA26 Sub-D 26HD Plug amp housing Note housings for Sub-D 15 fit for 26HD eg Assmann-WSW-A-HDS-26-LL-Z Encitech-DPPK15-BK-K-D-SUB-Gehaeuse

bull 1x 12V Universal Car Relay + Socket eg Song-Chuan-896H-1CH-C1-12V-DC-Kfz-Relais GoodSky-Relaissockel-1-St-GRL-CS3770

bull 1x 1 Channel 12V Relay Module With Optocoupler Isolation 12V 1 channel relay module with OptocouplerIsolation

Car wire-tap connectors car crimp connectors 05 mm2 wires zipties shrink-on tube tools

Note if you already use the switched 12V output of the OVMS for something different you can use one of the freeEGPIO outputs That requires additionally routing an EGPIO line to the DA26 connector at the expansion slot (egusing a jumper) and using a relay module (2b relay shield) with separate power input instead of the standard carrelay

I use 2b (relay shield) variant Be aware the MAX71317 outputs are open drain so you need a pull up resistor to eg+33 According to the data sheet the current should stay below 6 mA

Inside OVMS Box Connect JP1 Pin10 (GEP7) to Pin12 (EGPIO_8) with jumper

In DA26 connector

pin 24(+33) ----- [ 680 Ohms ] ---+--- [ Relay board IN ]|

pin 21 (EGPIO_8)pin 9 ----- [Relay board DC+]pin 8 ----- [Relay board DC-][Relay board COM] ----- Brake pedal switch one side[Relay board NO] ----- Brake pedal switch other side

153 Custom Commands 147

Open Vehicles

1542 Configuration

See OVMS web user interface menu Trio rarr Brake Light

Set the port as necessary and the checkbox to enable the brakelight

For monitoring and fine tuning use the bdquoregenmonldquo web plugin httpsgithubcomopenvehiclesOpen-Vehicle-Monitoring-System-3blobmastervehicleOVMSV3componentsovms_webserverdevregenmonhtm

148 Chapter 15 Mitsubishi Trio

Open Vehicles

154 Trio Regen Brake Light Hack 149

Open Vehicles

150 Chapter 15 Mitsubishi Trio

CHAPTER 16

Nissan Leafe-NV200

Vehicle Type NL

This vehicle type supports the Nissan Leaf (24kWh amp 30kWh) and Nissan e-NV200 (24kWh amp 40kWh)

161 Support Overview

1611 Hardware

Item Support StatusModule Any OVMS v3 (or later) module Vehicle support 2011-2017 (24kWh amp 30kWh LEAF 24kWh amp

40KWh e-Nv200 amp custom battery eg Muxsan)VehicleCable

1779000 Nissan Leaf OBD-II to DB9 Data Cable for OVMS

GSM An-tenna

1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)

GPS An-tenna

1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)

1612 Controls

Function Support StatusCharge Control Start and stop chargeCabin Pre-heatcool Control Yes1 (see info below)LockUnlock Vehicle Yes3 (see info below)Valet Mode Control Not currently supported

1 OVMS currently supports 2011-2017 Nissan LEAF and all models of Nissan e-NV2003 LockUnlock will work if CAR can bus is awake this can be activated by turning on AC

151

Open Vehicles

1613 Additional Features

Fea-ture

Description

BMSCellMon-itor

Allows to monitor individual battery cells in a configurable chart Can be accessed from web user interfaceaccessible over WiFi

ChargetoLimit

Allows to automatically stop the charge when target SOC (state of charge) andor range is reached Allparameters can be controlled trough metrics or web user interface Meanwhile Range and SOC can becontrolled from the app as well by adjusting fields 10 (SOC) and 11 (range) in feature section accessibletrough app settings

1614 Metrics

Item Support StatusSOC Yes (by default based on GIDS)4

Range Yes (by default based on GIDS)GPS Location Yes (from modem module GPS)Speed Yes (from vehicle speed PID)Cabin Temperature Yes (from vehicle temperature PIDs)Ambient Temperature Yes (from vehicle temperature PIDs)SetPoint Temperature Yes (from vehicle hvac PIDs)2

HVAC Fan Speed Yes (from vehicle hvac PIDs)2

HVAC HeatingCooling Status Yes (from vehicle hvac PIDs)2

HVAC On Status Yes (from vehicle hvac PIDs)2

HVAC Temperature Setpoint Yes (from vehicle hvac PIDs)2

HVAC Ventilation Mode Yes (from vehicle hvac PIDs)2

BMS v+t YesTPMS Yes (If hardware available)Charge Status YesCharge Interruption Alerts Yes

162 Remote Climate Control

1621 2014-2022 e-NV200 models

OVMS remote climate support will lsquojust workrsquo on e-Nv200 VisiaAcenta which donrsquot have a Nissan satnav headunitFor Tekna models which are fitted with a Nissan satnav headunit follow the instructions below for a 2013-2016 LEAFto unplug the TCU

IMPORTANT for remote climate to work on the e-NV200 the model year in OVMS should be set to 2015 regardlessof the the actual model year of the vehicle CAN writing also needs to be enabled

The model year can be set in the web interface or via the command

4 ZE0 (2011-2013) vehicles are required to choose SoC display from ldquorelative to fixed valuerdquo ldquodashboard displayrdquo SoC method does not workwith these vehicles

2 Some HVAC Status Items have been only verified with 2013-2016 MY cars and will only work if the year is set in configuraiton Also HVACneeds to be in ON position before powering down the vehicle for the metrics to work during pre-heat

152 Chapter 16 Nissan Leafe-NV200

Open Vehicles

config set xnl modelyear 2015

1622 2011-2012 LEAF models (ZE0)

Gen1 LEAFs (ZE0 2011-2012) require a hardware modification to enable remote climate control if the vehicle is notplugged in and charging If you are ok with this you donrsquot need to do anything further

If you want to to enable remote climate control once the charge has finished or if the vehicle is not plugged in youneed to do the following hardware modification A cable wired to the pin 11 of Nissan TCU (Telematics Control Unit)needs to receive +12V so that ldquoEV System Activation Request Signalrdquo can be generated which in turn allows to triggerclimate control independently This can be achieved by wiring the pin 18 (Ext 12V) from the OVMS DA26 socket tothe cable going to pin 11 of the TCU by using a standard single conductor wire The connection on the OVMS DA26side can be made by using dedicated DA26 connector or a standard round 1mm jumper cable Herersquos how to wire itup

Meanwhile on the TCU side the cable can be soldered or spliced in to by using a connector of your choice Whendone the original TCU can be left unplugged See this page for additional pictures

162 Remote Climate Control 153

Open Vehicles

If you have a ldquosmartrdquo EVSE (or one connected to a ldquosmartrdquo outlet you can sometimes wake up the EV system byturning it off then back on This obviously only helps if your vehicle is plugged in but may be useful for some users

1623 2013-2016 LEAF models (AZE0-01)

To use OVMS to activate remote climate the Nissan TCU (Telematics Control Unit) module must be unplugged iffitted eg satnav headunit (only on Acenta and Tekna models) The TCU is located behind the glovebox on LHD carsor on the right hand side of the drivers foot well on RHD cars The large white plug on the rear of the TCU should beunplugged push down tab in the middle and pull to unplug see video for RHD cars and this page for LHD cars

Note Unplugging the TCU will disable Nissan EV connect CARWINGS features eg Nissan mobile app All othercar functions will not be effected eg GPS maps radio Bluetooth microphone all work just the same as beforeOVMS can be used to more than substitute the loss of Nissan Connect features The TCU can be plugged back in atany point in the future if required

OVMS remote climate support will lsquojust workrsquo on LEAF Visia models and VisiaAcenta e-NV200 since these modelsdo not have a TCU fitted In the US these base models are called S

Note If you prefer not to unplug the Nissan TCU all OVMS functions appart from remote climate will function justfine alongside the Nissan TCU

1624 2016-2017 LEAF models (AZE0-2)

Remote climate control will only work when plugged in and actively charging on LEAF 2016-2017 models Thisis because in 2016 Nissan moved the TCU from the EV CAN bus to the CAR CAN bus

Set the model year as follows and if necessary configure 30 kWh model

config set xnl modelyear 2016

or

154 Chapter 16 Nissan Leafe-NV200

Open Vehicles

config set xnl modelyear 2017

Note in latest OVMS fimware version model year and battery size can be set via the web config interface

1625 2018+ models (ZE1)

2018+ 4062kWh LEAF is not yet supported Please get in touch if your interested in helping to add support Relevant2018 CANbus messages have already been decoded and documented see MyNissanLEAF thread

1626 Specific battery configs

For models with a 30 kWhr battery pack set the capacity manually with

config set xnl maxGids 356 config set xnl newCarAh 79

For models with a 40 kWhr battery pack set the capacity manually with

config set xnl maxGids 502 config set xnl newCarAh 115

For models with a 62 kWhr battery pack set the capacity manually with

config set xnl maxGids 775 config set xnl newCarAh 176

Note In latest OVMS firmware version model year and battery size can be set via the web config interface This iseasier and also the preferred method

Note 2 OVMS fully supports battery upgraded LEAFs just set the capacity according to what battery is currentlyinstalled

163 Range Calculation

The OVMS uses two configuration options to calculate remaining range whPerGid (default 80Whgid) and km-PerKWh (default 71kmkWh) The range calculation is based on the remaining gids reported by the LBC and atthe moment does not hold 5 in reserve like LeafSpy Feedback on this calculation is welcomed

164 Resources

bull Nissan LEAF support added by Tom Parker see his wiki for lots of documentation and resources Some info isoutdated eg climate control now turns off automatically

bull Nissan LEAF features are being added by Jaunius Kapkan see his github profile to track the progress

bull MyNissanLEAF thread for Nissan CANbus decoding discussion

bull Database files (DBC) for ZE0 and AZE0 Leaf can be found here Github LEAF Canbus database files

Assistance is appreciated as I havenrsquot had time to try to override the TCU using the OVMS or find an alternativesolution to prevent the TCU overriding the messages while still allowing the hands free microphone to work

163 Range Calculation 155

Open Vehicles

156 Chapter 16 Nissan Leafe-NV200

CHAPTER 17

OBDII Vehicles

Vehicle Type O2

Support for generic OBDII is provided by this module

157

Open Vehicles

171 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support Not widely tested but should be all that

support OBDII standard PIDs over CAN busVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display Yes (based on fuel level PID)Range Display NoGPS Location Yes (from modem module GPS)Speed Display Yes (from vehicle speed PID)Temperature Dis-play

Yes (from vehicle temperature PIDs)

BMS v+t Display NoTPMS Display NoCharge Status Dis-play

No

Charge Interrup-tion Alerts

No

Charge Control NoCabin Pre-heatcool Control

No

LockUnlockVehicle

No

Valet Mode Con-trol

No

Others VIN and RPMs should be available

158 Chapter 17 OBDII Vehicles

CHAPTER 18

Renault Twizy

Vehicle Type RT

159

Open Vehicles

181 Support Overview

Function Support StatusHardware No specific requirements (except for regen brake light

control see below)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right

or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any

compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or

any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display YesBMS v+t Display YesTPMS Display NoCharge Status Display YesCharge Interruption Alerts YesCharge Control Current limit stop SOCrange limitCabin Pre-heatcool Control NoLockUnlock Vehicle Mapped to dynamic speed lockValet Mode Control Mapped to odometer based speed lockOthers

bull Battery amp motor power amp energy monitoringbull Battery health amp capacitybull SEVCON monitoring amp tuning (Note tuning

only SC firmware lt= 07120002 ~072016)bull Kickdownbull Auto power adjustbull Regen brake lightbull Extended trip amp GPS logging

Note regarding the Twizy V3 works very similar to V2 All telemetry data tables and tuning profiles are fullycompatible and the commands are very similar Therefore the basic descriptions and background info from the V2manual are valid for V3 as well

bull V2 FAQ (english)

bull V2 FAQ (german)

bull V2 documents directory

bull V2 user manual (PDF)

182 Hints on V3 commands vs V2

bull V3 commands need to be in lower case

bull When accessing via USB terminal first issue enable (login)

bull V3 commands are similar to V2 commands just structured slightly different

160 Chapter 18 Renault Twizy

Open Vehicles

bull Try help and xrt Twizy commands are subcommands of xrt

bull TAB only works via USB SSH Shortcuts can be used generally eg mo t instead of module tasks

bull A usage info is shown if a command syntax is wrong or incomplete

183 Contents

1831 Configuration

The Twizy configuration is stored in the OVMS config parameter (section) xrt To list the current values issue

config list xrt

For reference the following table includes the equivalent OVMS V2 feature or parameter number amp bit value whereapplicable You may use the parameter amp feature editors on the App (values are mapped) the commands have beenmerged into the config command in V3

183 Contents 161

Open Vehicles

Config instancename

Examplevalue

V2FP

Description

autopower yes F158 Bool SEVCON automatic power level adjustment (Default yes)autoreset yes F152 Bool SEVCON reset on error (Default yes)aux_charger_port 0 ndash EGPIO port to control auxiliary charger (Default 0 = disabled)aux_fan_port 0 ndash EGPIO port to control auxiliary charger fan (Default 0 = disabled)canwrite yes F151 Bool CAN write enabled (Default no)cap_act_prc 822288 F13 Battery actual capacity level [] (Default 1000)cap_nom_ah 108 ndash Battery nominal capacity [Ah] (Default 1080)chargelevel 0 F7 Charge power level [1-7] (Default 0=unlimited)chargemode 0 F6 Charge mode 0=notify 1=stop at sufficient SOCrange (Default 0)console no F1516 -unused- (reserved for possible V3 SimpleConsole presence)dtc_autoreset no ndash Reset DTC statistics on every drivecharge start (Default no)gpslogint 5 (F8) Seconds between RT-GPS-Log entries while driving (Default 0 =

disabled)kd_compzero 120 F2 Kickdown pedal compensation (Default 120)kd_threshold 35 F1 Kickdown threshold (Default 35)kickdown yes F154 Bool SEVCON automatic kickdown (Default yes)lock_on 6 ndash Speed limit [kph] to engage lock mode at (Default undefined = off)maxrange 55 F12 Maximum ideal range at 20 degC [km] (Default 80)motor_rpm_rated 2050 ndash Powermap V3 control rated speed [RPM] (Default 0 = V2)mo-tor_trq_breakdown

210375 ndash Powermap V3 control breakdown torque [Nm] (Default 0 = V2)

profileNN XaZwt5ehZQ (P16-21)

Tuning profile NN [NN=01 99] base64 code

profileNNlabel PWR ndash button labelprofileNNtitle Power ndash titleprofile_buttons 0123 ndash Tuning drivemode button configurationprofile_cfgmode 2 ndash Tuning profile last loaded in config (pre-op) modeprofile_user 2 P15 Tuning profile last loaded in user (op) modesuffrange 0 F11 Sufficient range [km] (Default 0=disabled)suffsoc 80 F10 Sufficient SOC [] (Default 0=disabled)type ndash ndash Twizy custom SEVCONGearbox type [SC80GB45SC45GB80]

(Default - = auto detect)valet_on 123456 ndash Odometer limit [km] to engage valet mode at (Default undefined =

off)

1832 Custom Metrics

Metric name Example value Descriptioncocan1nd1emcycode SEVCON emergency codecocan1nd1emcytype SEVCON emergendy typecocan1nd1state Operational SEVCON state (preopop)xrtbusocmax 7052 Current tripcharge pack SOC maxxrtbusocmin 508 Current tripcharge pack SOC minxrtbutempmax 20degC Current tripcharge pack temp maxxrtbutempmin 181429degC Current tripcharge pack temp minxrtbuvoltmax 55V Current tripcharge pack volt maxxrtbuvoltmin 502V Current tripcharge pack volt min

Continued on next page

162 Chapter 18 Renault Twizy

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxrtbmsbalancing 248101314 Custom BMS cell balancing statusxrtbmserror 0 Custom BMS error statusxrtbmsstate1 4 Custom BMS main statexrtbmsstate2 1 Custom BMS auxiliary statexrtbmstemp 52degC Custom BMS internal temperaturexrtbmstype 1 Custom BMS type (0=VirtualBMS 1=eDriver BMS 7=Standard)xrtcfgapplied yes Tuning working set has been applied to SEVCONxrtcfgbase 2 Tuning base profile (preop mode params)xrtcfgprofile 144110111182 Tuning profile paramsxrtcfgtype Twizy80 Tuning vehicle typexrtcfgunsaved yes Tuning working set has unsaved changesxrtcfguser 2 Tuning userlive profile (op mode params)xrtcfgws 0 Tuning profile last loaded into working setxrticuract 0A SC monitor motor current levelxrtifrqoutput 0 SC monitor motor output frequencyxrtifrqslip 0 SC monitor motor slip frequencyxrtipwract 0kW SC monitor motor power levelxrtitrqact 0 SC monitor motor torque levelxrtitrqdemand 0 SC monitor motor torque demandxrtitrqlimit 0 SC monitor motor torque limitxrtivltact 0V SC monitor output voltage level (motor)xrtivltbat 0 SC monitor input voltage level (battery)xrtivltcap 0A SC monitor capacitor voltage levelxrtivltmod 0 SC monitor motor modulation factorxrtmversion 124 Sep 17 2019 OVMS Twizy component versionxrtpstatsaccdist 06267km Power stats accelerating distancexrtpstatsaccrecd 130133e-05kWh Power stats accelerating energy recoveredxrtpstatsaccspdavg 27kmhs Power stats accelerating speed averagexrtpstatsaccused 017692kWh Power stats accelerating energy usedxrtpstatscstdist 05331km Power stats coasting distancexrtpstatscstrecd 423289e-05kWh Power stats coasting energy recoveredxrtpstatscstspdavg 2618kmh Power stats coasting speed averagexrtpstatscstused 009703kWh Power stats coasting energy usedxrtpstatsdecdist 05436km Power stats decelerating distancexrtpstatsdecrecd 00140886kWh Power stats decelerating energy recoveredxrtpstatsdecspdavg 26kmhs Power stats decelerating speed averagexrtpstatsdecused 00379027kWh Power stats decelerating energy usedxrtpstatsldndist 02km Power stats downwards distancexrtpstatsldnhsum 3m Power stats downwards height sumxrtpstatsldnrecd 000300565kWh Power stats downwards energy recoveredxrtpstatsldnused 00356104kWh Power stats downwards energy usedxrtpstatslupdist 131km Power stats upwards distancexrtpstatsluphsum 66m Power stats upwards height sumxrtpstatsluprecd 0010866kWh Power stats upwards energy recoveredxrtpstatslupused 0263831kWh Power stats upwards energy usedxrtsbpwrdrv SC monitor virtual dyno drive power levelsxrtsbpwrrec SC monitor virtual dyno recup power levelsxrtsmtrqdrv SC monitor virtual dyno drive torque levelsxrtsmtrqrec SC monitor virtual dyno recup torque levels

Continued on next page

183 Contents 163

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxrtvbalert12v no Display service indicator 12V alertxrtvbalertbatt no Display service indicator Battery alertxrtvbalerttemp no Display service indicator Temperature alertxrtvbstatus 0 Internal BMS status (CAN frame 628)xrtvcstatus 0 Internal Charger status (CAN frame 627)xrtvistatus 0 Internal SEVCON status (CAN frame 629)xrtvelockedspeed 0 Speed limit [kph] set for Twizy lock modexrtvevaletodo 0 Odometer limit [km] set for Twizy valet mode

1833 Events

The Renault Twizy module emits these specific events additionally to the general OVMS events

Event Data Purposevehiclechargesubstatescheduledstop Charge stopped by user request (command)vehiclectrlcfgmode SEVCON in configuration mode (preop)vehiclectrlloggedin SEVCON session establishedvehiclectrlrunmode SEVCON in normal mode (op)vehicledrivemodechanged SEVCON tuning profile changedvehicledtcpresent ltdtc_descrgt OBD2 DTC (diagnostic trouble code) presentvehicledtcstored ltdtc_descrgt OBD2 DTC storedvehiclefaultcode ltcodegt SEVCON fault code receivedvehiclekickdownengaged Kickdown detected drive power changedvehiclekickdownreleased Kickdown mode end normal power restoredvehiclekickdownreleasing Kickdown mode about to end

1834 Custom Commands

Note This is currently just a brief overview to feed the search engine See each commandrsquos usage info and whereapplicable corresponding V2 manual entries on details

bull V3 commands need to be in lower case

bull When accessing via USB terminal first issue enable (login)

bull V3 commands are similar to V2 commands just structured slightly different

bull Try help and xrt Twizy commands are subcommands of xrt

bull TAB only works via USB SSH Shortcuts can be used generally eg mo t instead of module tasks

bull A usage info is shown if a command syntax is wrong or incomplete

OVMS xrt batt Battery monitorca Charge attributescfg SEVCON tuningdtc Show DTC report clear DTCmon SEVCON monitoringobd OBD2 toolspower Powerenergy info

164 Chapter 18 Renault Twizy

Open Vehicles

Battery Monitor

OVMS xrt batt data-cell Output cell recorddata-pack Output pack recordreset Reset alerts amp watchesstatus Status reporttdev Show temperature deviationstemp Show temperaturesvdev Show voltage deviationsvolt Show voltages

Note Also see standard BMS commands (bms )

Charge Attributes

OVMS xrt ca Usage xrt ca [R] | [ltrangegt] [ltsocgt] [Llt0-7gt] [S|N|H]

Note Also see standard charge control commands (charge )

SEVCON Tuning

OVMS xrt cfg brakelight Tune brakelight trigger levelsclearlogs Clear SEVCON diag logsdrive Tune drive power levelget Get tuning profile as base64 stringinfo Show tuning profileload Load stored tuning profileop Leave configuration mode (go operational)power Tune torque power amp current levelspre Enter configuration mode (pre-operational)querylogs Send SEVCON diag logs to serverramplimits Tune max pedal reactionramps Tune pedal reactionread Read registerrecup Tune recuperation power levelsreset Reset tuning profilesave Save current tuning profileset Set tuning profile from base64 stringshowlogs Display SEVCON diag logssmooth Tune pedal smoothingspeed Tune max amp warn speedtsmap Tune torquespeed mapswrite Read amp write registerwriteonly Write register

183 Contents 165

Open Vehicles

Show DTC Report Clear DTC

OVMS xrt dtc clear Clear stored DTC in carreset Reset OVMS DTC statisticsshow Show DTC report

SEVCON Monitoring

OVMS xrt mon reset Reset monitoringstart Start monitoringstop Stop monitoring

OBD2 Tools

OVMS xrt obd request Send OBD2 request output responseOVMS xrt obd request bms Send OBD2 request to BMSbroadcast Send OBD2 request as broadcastcharger Send OBD2 request to charger (BCB)cluster Send OBD2 request to cluster (display)device Send OBD2 request to a device

PowerEnergy Info

OVMS xrt power report Trip efficiency reportstats Generate RT-PWR-Stats entrytotals Power totals

1835 Notifications

The Renault Twizy module sends the custom or customized notifications described here additionally to the systemnotifications

See Notifications for general info on notifications

166 Chapter 18 Renault Twizy

Open Vehicles

Type Subtype Purpose Contentalert batterystatus Battery packcell alert status report (alerts amp watches)alert bmsstatus Battery management system alert (for custom BMS only)info chargestatussufficient Sufficient charge reached (SOCrange as configured)alert valetmodeodolimit Odometer limit reached speed reduction engagedalert vehicledtc OBD2 DTC (diagnostic trouble code) alertdata xrtbatterylog Battery packcell monitoring logdata xrtgpslog Extended GPS logdata xrtobdclusterdtc OBD2 DTC log for cluster (displayUCH)data xrtpowerdyno SEVCON live monitoring (virtual dyno) datadata xrtpowerlog Power statisticsinfo xrtpowertotals Current usage cycle power totalsdata xrttriplog Trip history loginfo xrttripreport Trip energy usage reportalert xrtsevconfault SEVCON fault condition detecteddata xrtsevconlog SEVCON faults amp events logsinfo xrtsevconprofilereset A tuning RESET has been performedinfo xrtsevconprofileswitch Tuning profile switch result

Trip history log

The trip history log can be used as a source for long term statistics on your trips and typical trip power usages as wellas your battery performance in different environmental conditions and degradation over time

Entries are created at the end of a trip and on each change in the charge state so you can also see where chargesstopped or how long they took and how high the temperatures got

bull Notification subtype xrttriplog

bull History record type RT-PWR-Log

bull Format CSV

bull Maximum archive time 365 days

bull Fieldscolumns

ndash odometer_km

ndash latitude

ndash longitude

ndash altitude

ndash chargestate

ndash parktime_min

ndash soc

ndash soc_min

ndash soc_max

ndash power_used_wh

ndash power_recd_wh

ndash power_distance

183 Contents 167

Open Vehicles

ndash range_estim_km

ndash range_ideal_km

ndash batt_volt

ndash batt_volt_min

ndash batt_volt_max

ndash batt_temp

ndash batt_temp_min

ndash batt_temp_max

ndash motor_temp

ndash pem_temp

ndash trip_length_km

ndash trip_soc_usage

ndash trip_avg_speed_kph

ndash trip_avg_accel_kps

ndash trip_avg_decel_kps

ndash charge_used_ah

ndash charge_recd_ah

ndash batt_capacity_prc

ndash chg_temp

Extended GPS log

The extended GPS log contains additional details about power and current levels the BMS power limits and theautomatic power level adjustments done by the OVMS You can use this to create detailed trip power charts and toverify your auto power adjust settings

The log frequency is once per minute while parkingcharging and controlled by config xrt gpslogint (web UITwizy rarr Features) while driving Logging only occurs if logged metrics have changed

bull Notification subtype xrtgpslog

bull History record type RT-GPS-Log

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash odometer_mi_10th

ndash latitude

ndash longitude

ndash altitude

ndash direction

ndash speed

168 Chapter 18 Renault Twizy

Open Vehicles

ndash gps_fix

ndash gps_stale_cnt

ndash gsm_signal

ndash current_power_w

ndash power_used_wh

ndash power_recd_wh

ndash power_distance

ndash min_power_w

ndash max_power_w

ndash car_status

ndash max_drive_pwr_w

ndash max_recup_pwr_w

ndash autodrive_level

ndash autorecup_level

ndash min_current_a

ndash max_current_a

Battery packcell monitoring log

The extended GPS log contains additional details about power and current levels the BMS power limits and theautomatic power level adjustments done by the OVMS You can use this to create detailed trip power charts and toverify your auto power adjust settings

The standard log frequency is once per minute logging only occurs if logged metrics have changed Additionalrecords are created on battery alert events Note an entry consists of a pack level record (RT-BAT-P) and up to 16(for LiFePO4 batteries) cell entries (RT-BAT-C)

bull Notification subtype xrtbatterylog

bull History record type RT-BAT-P (pack status)

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash packnr

ndash volt_alertstatus

ndash temp_alertstatus

ndash soc

ndash soc_min

ndash soc_max

ndash volt_act

ndash volt_min

183 Contents 169

Open Vehicles

ndash volt_max

ndash temp_act

ndash temp_min

ndash temp_max

ndash cell_volt_stddev_max

ndash cmod_temp_stddev_max

ndash max_drive_pwr

ndash max_recup_pwr

ndash bms_state1

ndash bms_state2

ndash bms_error

ndash bms_temp

bull Notification subtype xrtbatterylog

bull History record type RT-BAT-C (cell status)

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash cellnr

ndash volt_alertstatus

ndash temp_alertstatus

ndash volt_act

ndash volt_min

ndash volt_max

ndash volt_maxdev

ndash temp_act

ndash temp_min

ndash temp_max

ndash temp_maxdev

ndash balancing

ndash been_balancing

ndash balancetime

Power statistics

The power statistics are the base for the trip reports and can be used to analyze trip sections regarding speed andaltitude changes and their respective effects on power usage The log is also written when charging that data can beused to log changes in the charge current for example triggered externally by some solar charge controller

Log frequency is once per minute logging only occurs if metrics have changed

170 Chapter 18 Renault Twizy

Open Vehicles

bull Notification subtype xrtpowerlog

bull History record type RT-PWR-Stats

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash speed_const_dist

ndash speed_const_use

ndash speed_const_rec

ndash speed_const_cnt

ndash speed_const_sum

ndash speed_accel_dist

ndash speed_accel_use

ndash speed_accel_rec

ndash speed_accel_cnt

ndash speed_accel_sum

ndash speed_decel_dist

ndash speed_decel_use

ndash speed_decel_rec

ndash speed_decel_cnt

ndash speed_decel_sum

ndash level_up_dist

ndash level_up_hsum

ndash level_up_use

ndash level_up_rec

ndash level_down_dist

ndash level_down_hsum

ndash level_down_use

ndash level_down_rec

ndash charge_used

ndash charge_recd

OBD2 cluster DTC log

This server table stores DTC occurrences for one week This is mostly raw data and the DTCs are internal Renaultvalues that have not yet been decoded

See httpswwwtwizy-forumdeovms86362-liste-df-codes-dtc

bull Notification subtype xrtobdclusterdtc

183 Contents 171

Open Vehicles

bull History record type RT-OBD-ClusterDTC

bull Format CSV

bull Maximum archive time 7 days

bull Fieldscolumns

ndash EntryNr

ndash EcuName

ndash NumDTC

ndash Revision

ndash FailPresentCnt

ndash G1

ndash G2

ndash ServKey

ndash Customer

ndash Memorize

ndash Bt

ndash Ef

ndash Dc

ndash DNS

ndash Odometer

ndash Speed

ndash SOC

ndash BattV

ndash TimeCounter

ndash IgnitionCycle

SEVCON faults amp events

These logs are created on request only eg by the SEVCON logs tool in the Android App or by using the xrt cfgquerylogs command The command queries the SEVCON (inverter) alerts faults events and statistics (SEVCONneeds to be online) The results are then transmitted to the server using the following records

bull Notification subtype xrtsevconlog

bull History record type RT-ENG-LogKeyTime

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash KeyHour

ndash KeyMinSec

bull Notification subtype xrtsevconlog

172 Chapter 18 Renault Twizy

Open Vehicles

bull History record type RT-ENG-LogAlerts

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash Code

ndash Description

ndash TimeHour

ndash TimeMinSec

ndash Data1

ndash Data2

ndash Data3

bull Notification subtype xrtsevconlog

bull History record type RT-ENG-LogSystem

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash Code

ndash Description

ndash TimeHour

ndash TimeMinSec

ndash Data1

ndash Data2

ndash Data3

bull Notification subtype xrtsevconlog

bull History record type RT-ENG-LogCounts

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash Code

ndash Description

ndash LastTimeHour

ndash LastTimeMinSec

ndash FirstTimeHour

ndash FirstTimeMinSec

ndash Count

bull Notification subtype xrtsevconlog

183 Contents 173

Open Vehicles

bull History record type RT-ENG-LogMinMax

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash BatteryVoltageMin

ndash BatteryVoltageMax

ndash CapacitorVoltageMin

ndash CapacitorVoltageMax

ndash MotorCurrentMin

ndash MotorCurrentMax

ndash MotorSpeedMin

ndash MotorSpeedMax

ndash DeviceTempMin

ndash DeviceTempMax

SEVCON live monitoring

These records store the measurement results of the virtual dyno included in the SEVCON live monitor (Twizy rarrSEVCON Monitor) The virtual dyno records a torquepower profile from the actual car performance during drivingThe profile has four data sets

bull Maximum battery drive power over speed (metric xrtsbpwrdrv unit kW)

bull Maximum battery recuperation power over speed (metric xrtsbpwrrec unit kW)

bull Maximum motor drive torque over speed (metric xrtsmtrqdrv unit Nm)

bull Maximum motor recuperation torque over speed (metric xrtsmtrqrec unit Nm)

Power is measured at the battery so you can derive the efficiency Speed is truncated to integer the value arrays takeup to 120 entries (0 119 kph)

These datasets are visualized by the web UI using a chart and transmitted to the server on any monitoring ldquostoprdquo orldquoresetrdquo command in the following records

bull Notification subtype xrtpowerdyno

bull History record types RT-ENG-BatPwrDrv RT-ENG-BatPwrRec RT-ENG-MotTrqDrvRT-ENG-MotTrqRec

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns max 120 values for speed levels beginning at 0 kph

1836 Twizy Regen Brake Light Hack

174 Chapter 18 Renault Twizy

Open Vehicles

Why

The Twizy recuperation levels are very low by default regenerative braking is so weak it doesnlsquot need to trigger thebrake light ndash so a regen braking indication has been omitted by Renault The Twizy can be tuned to one pedal drivingthough with high neutral braking power

The SEVCON normally can generate a regen braking signal itself That signal can be configured using the xrt cfgbrakelight tuning command Pin 11 on the SEVCON main connector will go to GND on activation The problemis that pin is not connected on the Twizy using it needs modification of the connector To my knowledge this hasnlsquotbeen done successfully up to now so we donlsquot even know if the Twizy SEVCON firmware includes that functionality

How does it work

The OVMS generates a secondary regen braking signal itself That signal is used to control a relay to provide powerto the brake light independant of the brake pedal

Integration is simple and does not require to change the existing connections

The Twizy UCHdisplay recognizes the regen brake light activation despite the foot brake being pushed and turns onthe SERV indicator Depending on your preferences you may see this as a problem or as an indicator for the regenbraking

Switching the 65A line does not avoid the SERV indicator (tested) Most probably the brake light is monitored by thecurrent flowing at the fuse box so the SERV indicator cannot be avoided without changing that system

Parts required

1 1x DA26 Sub-D 26HD Plug amp housing

bull Note housings for Sub-D 15 fit for 26HD

bull eg Assmann-WSW-A-HDS-26-LL-Z

183 Contents 175

Open Vehicles

bull Encitech-DPPK15-BK-K-D-SUB-Gehaeuse

2 1x 12V Universal Car Relay + Socket

bull eg Song-Chuan-896H-1CH-C1-12V-DC-Kfz-Relais

bull GoodSky-Relaissockel-1-St-GRL-CS3770

3 Car wire-tap connectors car crimp connectors 05 mm2 wires zipties shrink-on tube tools

Note if you already use the switched 12V output of the OVMS for something different you can use one of the freeEGPIO outputs That requires additionally routing an EGPIO line to the DA26 connector at the expansion slot (egusing a jumper) and using a relay module (relay shield) with separate power input instead of the standard car relay

Build

1 Solder ~ 40 cm two-core wire to the DA26 plug pins 8 (GND) and 18 (+12V switched) use shrink-on tubes toprotect the terminals mount the housing

2 Crimp 63mm sockets to the other ends of the wire isolate using shrink-on tube crimp 63mm plugs to the relaycoil (pins 85 + 86) isolate using shrink-on tube

176 Chapter 18 Renault Twizy

Open Vehicles

3 Extend the relay switch terminals by ~ 30 cm wires crimp on plugs for the tap connectors

4 Unmount the Twizy glovebox locate the red wire on the right above the parking brake

183 Contents 177

Open Vehicles

5 Crimp a tap connector onto the red wire and connect it to the relay (pin 30)

178 Chapter 18 Renault Twizy

Open Vehicles

6 Connect switched +12V likewise to pin 87 of the relay

bull +12V may be taken from the radio or 12V aux socket to simplify things

bull the dedicated brake light supply is fuse no 23 which is very hard to reach without dismounting the whole fuseholder

7 Place the relay in the free area on the upper left of the fuse holder (not below the door dampener that may crushthe relay) secure the relay using a ziptie

8 Pull the OVMS DIAG cable through the glovebox bottom hole and connect it to the relay inputs (pins 8586polarity doesnlsquot matter)

9 Do a test plug in the OVMS (Note the relay switches on during the first OVMS boot) switch on the Twizyissue commands

bull egpio output 1 1 should activate the brakelight

bull egpio output 1 0 should deactivate the brakelight

bull Note if youlsquore using another EGPIO port use the according port number (3-9) instead

10 Mount the glovebox and youlsquore done

Configuration

See OVMS web user interface menu Twizy rarr Brake Light

183 Contents 179

Open Vehicles

Set the port as necessary and the checkbox to enable the brakelight

For monitoring and fine tuning use the regenmon web plugin

httpsgithubcomopenvehiclesOpen-Vehicle-Monitoring-System-3blobmastervehicleOVMSV3componentsovms_webserverdevregenmonhtm

1837 Auxiliary Charge Fan

The builtin Elips 2000W chargerrsquos officially specified temperature operation range is -20+50 degC This is exceededby the Twizy easily even on moderate summer days The charger temperature can easily rise above 60 degC and this is

180 Chapter 18 Renault Twizy

Open Vehicles

possibly the main reason why Twizy chargers eventually die It also leads to the Twizy reducing the maximum chargepower available resulting in charges taking much longer than usual

A counter measure can be to add an additional fan to cool the charger and switch that fan on as necessary (seebelow) The fan can be controlled using one of the OVMS EGPIO output ports (see EGPIO) The easiest way is to usethe switched 12V supply available at the DA26 expansion plug without additional hardware The 12V port can delivera nominal output of 25W or 18A and up to 40W or 29A short term so can be used to power many auxiliary fansdirectly

To enable the auxiliary fan simply configure the EGPIO to be used in config parameter xrt aux_fan_port Forexample to use the switched 12V port = EGPIO port 1 do

OVMS config set xrt aux_fan_port 1

Set the port to 0 to disable the feature

Mode of operation

bull The OVMS continously monitors the charger temperature It turns on the fan when the charger temperaturerises above 45 degC (gt= 46 degC) and off when the temperature drops below 45 degC (lt= 44 degC)

bull After end of charge (Twizy system switched off) the OVMS does not get temperature updates so it keeps thefan running for another 5 minutes

The fan control works during charging and driving as during driving the charger also has to supply +12V by thebuiltin DCDC converter (heating up the charger) and a trip may start with an already hot charger

1838 Auxiliary Charger

The Elips 2000W (as the name says) does only charge with ~2 kW thus needing 3-35 hours to charge the originalTwizy battery Thatlsquos quite slow and gets worse when replacing the battery by a larger one

The Elips is running a special Renault firmware and also taking a crucial role in the Twizy system communication forexample to control the BMS So it cannot easily be replaced by a third party charger

But a third party charger can run in parallel to the Elips to boost the charge power This can be done best fromthe ldquorear endrdquo ie using the battery main connector as the power input (like the SEVCON does during regenerativebraking)

Some documented examples of additional chargers

bull httpswwwtwizy-forumdewerkstatt-twizy84935-twizy-schnelllader

bull httpswwwtwizy-forumdeprojekte-twizy83603-schnell-lader-extern

bull httpswwwtwizy-forumdetipps-und-tricks-twizy80814-twizy-schnellladen-die-wave-kann-kommen

The caveat to avoid damaging the battery additional charge power should not be supplied when the battery is nearlyfull So the additional charger needs to be switched off before the main charger finishes

The OVMS can automate switching the additional charger both on and off Any of the available EGPIO output ports(see EGPIO) can be used for this task If the charger has no digital power control input a convenient way is to use theswitched 12V supply available at the DA26 expansion plug without additional hardware The 12V port can deliver anominal output of 25W or 18A and up to 40W or 29A short term so can be used to power a standard automotiverelay directly

Configuration

Simply set the EGPIO to be used in config parameter xrt aux_charger_port For example to use the switched12V port = EGPIO port 1 do

183 Contents 181

Open Vehicles

OVMS config set xrt aux_charger_port 1

Set the port to 0 to disable the feature

Mode of operation

bull The port is switched ON when the Twizy charges is below 94 SOC is still within the CC phase (ie nottopping off balancing) and the charge current is not under user control

bull The port is switched OFF when the Twizy stops charging reaches 94 SOC or enters the topping off phase(whichever comes first) or when you set a custom charge current

Charge current control

If you set the charge current to level 7 (35 A) only the original charger will run but at full power You can set levels6 1 (30 5 A) to reduce the charge power only using the Elips charger Setting the current to level 0 (no chargethrottling) will allow maximum charge current from the Elips charger and additionally enable the second charger

182 Chapter 18 Renault Twizy

CHAPTER 19

Renault Zoe

Vehicle Type RZ

This vehicle type supports the Renault Zoe(PH1) and Kangoo(2011 - ~2019) The newer Zoe ph2 and Kangoo are notsupported yet

191 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display Yes (External Temp and Battery)BMS v+t Display YesTPMS Display Zoe Yes (pressure only)TPMS Display Kangoo NoCharge Status Display YesCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

After selecting the Renault ZoeKangoo vehicle module the corresponding settings have to be made in the web inter-face via the ldquoRenault ZoeKangoordquo menu under ldquoFeaturesrdquo

183

Open Vehicles

184 Chapter 19 Renault Zoe

CHAPTER 20

Smart ED Gen3

Vehicle Type SE

The Smart ED will be documented here

201 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display NoCharge Status Display YesCharge Interruption Alerts YesCharge Control Current limitCabin Pre-heatcool Control When charging and CAN-Bus ActiveLockUnlock Vehicle NoValet Mode Control NoOthers

185

Open Vehicles

202 Contents

2021 Custom Metrics

Metric name Example value DescriptionxsemybmsHWrev 12380 BMS hardware-revision year week patchlevelxsemybmsSWrev 12351 BMS soft-revision year week patchlevelxsemybmsadccvoltsmax 4171 maximum cell voltages in mV add offset +1500xsemybmsadccvoltsmean 4165 average cell voltage in mV no offsetxsemybmsadccvoltsmin 4145 minimum cell voltages in mV add offset +1500xsemybmsadcvoltsoffset 103 calculated offset between RAW cell voltages and ADCref about 90mVxsemybmsamps 65483A battery current in ampere (x32) reported by by BMSxsemybmsamps2 204634A battery current in ampere read by live data on CAN or from BMSxsemybmsbattvin WME4513901K661441 VIN stored in BMSxsemybmsdcfault 0 Flag to show DC-isolation faultxsemybmshv total voltage of HV system in Vxsemybmshvcontactcyclesleft 281991 counter related to ONOFF cyles of the carxsemybmshvcontactcyclesmax 300000 static seems to be maxiumum of contactor cyclesxsemybmsisolation 10239 Isolation in DC path resistance in kOhmxsemybmspower 794186kW power as product of voltage and amps in kWxsevbccapacity 184911853618536 Cell capacity [As]xsevbccapacitydevmax 451901901 Cell maximum capacity deviation observed [As]xsevbccapacitymax 184911853618536 Cell maximum capacity [As]xsevbccapacitymin 184911853618536 Cell minimum capacity [As]xsevbenergyusedreset 1634kWh Energy used Reset (Dashbord)xsevbenergyusedstart 169kWh Energy used Start (Dashbord)xsevbhvactive no HV Batterie Statusxsevbpcapacityasaverage 18625 cell capacity statistics from BMS measurement cyclexsevbpcapacityasmaximum 19193 cell capacity statistics from BMS measurement cyclexsevbpcapacityasminimum 18843 cell capacity statistics from BMS measurement cyclexsevbpcapacityavg 184459 Cell capacity - pack average [As]xsevbpcapacitycombinedquality 0515328 some sort of estimation factor constantly updatedxsevbpcapacitymax 18670 Cell capacity - strongest cell in pack [As]xsevbpcapacitymaxcell 9 Cell capacity - number of strongest cell in packxsevbpcapacitymin 18229 Cell capacity - weakest cell in pack [As]xsevbpcapacitymincell 59 Cell capacity - number of weakest cell in packxsevbpcapacityquality 0742092 some sort of estimation factor after measurement cyclexsevbpcapacitystddev 908 Cell capacity - current standard deviation [As]xsevbpcapacitystddevmax 908 Cell capacity - maximum standard deviation observed [As]xsevbphvlowcurrent 0Sec counter time of no current reset eg with PLC heater or drivingxsevbphvofftime 0Sec HighVoltage contactor off time in secondsxsevbplastmeasdays 13 days elapsed since last successful measurementxsevbpocvtimer 2676Sec counter time in seconds to reach OCV statexsevbpvoltagemaxcell 1 Cell volatage - number of strongest cell in packxsevbpvoltagemincell 5 Cell volatage - number of weakest cell in packxsevbrealsoc 978 real state of chargexsevbusawake no CAN-Bus Statusxsevcactive no Charging Statusxsevdisplaytime 738Min Dashbord Timexsevdisplaytripreset 27332km Dashbord Trip value at Reset

Continued on next page

186 Chapter 20 Smart ED Gen3

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxsevdisplaytripstart 175km Dashbord Trip value at Startxsevnlg6ampscablecode 0A Onboard Charger Ampere Cablexsevnlg6ampschargingpoint 0A Onboard Charger Ampere xsevnlg6ampssetpoint 41A Onboard Charger Ampere setpointxsevnlg6dccurrent 0A Onboard Charger LV current Amperexsevnlg6dchv 0V Onboard Charger HV Voltagexsevnlg6dclv 135V Onboard Charger LV Voltagexsevnlg6mainamps 000A Onboard Charger main Phasen Amperexsevnlg6mainvolts 000V Onboard Charger main Phasen Voltagexsevnlg6pnhw 4519820621 Onboard Charger Hardware Serial Noxsevnlg6present no Onboard Charger OBL or NLG6 presentxsevnlg6tempcoolingplate 0degC Onboard Charger coolingplate Temperaturexsevnlg6tempreported 0degC Onboard Charger reported Temperaturexsevnlg6tempsocket 0degC Onboard Charger socket Temperaturexsevnlg6temps Onboard Charger Temperaturesxsevposodometerstart 41940km Odo at last Ignition on For Trip calc Valuexsevdisplayaccel 89 Eco score on acceleration over last 6 hoursxsevdisplayconst 18 Eco score on constant driving over last 6 hoursxsevdisplaycoast 100 Eco score on coasting over last 6 hoursxsevdisplayecoscore 69 Eco score shown on dashboard over last 6 hours

2022 Custom Commands

xse trip

show last Trip value

xse recu up

xse recu down

set Rekuperation up or down Works only if Rekuperation is enabled in car

xse charge

set charge and leave Time

Example

xse charge 7 15 off

set Time at 715 clock with pre climate off

xse charge 9 55 on

set Time at 955 clock with pre climate on

2023 BMS Diagnose Tool

xse rptdata get a Battery Status Report

xse bmsdiag get Battery Diagnose Report

Original Tool ED BMSdiag

description DE

description EN

202 Contents 187

Open Vehicles

188 Chapter 20 Smart ED Gen3

CHAPTER 21

Smart EDEQ Gen4 (453)

Vehicle Type SQ

The Smart EDEQ Gen4 will be documented here

211 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display Yes (External Temp and Battery)BMS v+t Display only Cell Volts atmTPMS Display NoCharge Status Display YesCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

189

Open Vehicles

190 Chapter 21 Smart EDEQ Gen4 (453)

CHAPTER 22

Tesla Model 3

Vehicle Type T3

At present support for the Tesla Model 3 in OVMS is experimental and under development This vehicle type shouldnot be used by anyone other than those actively involved in development of support for this vehicle

221 Support Overview

Function Support StatusHardware tbaVehicle Cable tbaGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna tbaSOC Display tbaRange Display tbaGPS Location tbaSpeed Display tbaTemperature Display tbaBMS v+t Display tbaTPMS Display tbaCharge Status Display tbaCharge Interruption Alerts tbaCharge Control tbaCabin Pre-heatcool Control tbaLockUnlock Vehicle tbaValet Mode Control tbaOthers tba

191

Open Vehicles

192 Chapter 22 Tesla Model 3

CHAPTER 23

Tesla Model S

Vehicle Type TS

At present support for the Tesla Model S in OVMS is experimental and under development This vehicle type shouldnot be used by anyone other than those actively involved in development of support for this vehicle

231 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support Not widely tested but should be

allVehicle Cable 9665972 OVMS Data Cable for Early TeslasGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna None not requiredSOC Display YesRange Display YesGPS Location Yes (from carrsquos built in GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display Not currently supportedCharge Status Display YesCharge Interruption Alerts YesCharge Control Not currently supportedCabin Pre-heatcool Con-trol

Not currently supported

LockUnlock Vehicle Not currently supportedValet Mode Control Not currently supportedOthers Adhesive velcro strips useful for vehicle attachment

193

Open Vehicles

232 TPMS Option

Reading and writing TPMS wheel sensor IDs fromto the Baolong TPMS ECU is supported by OVMS in Tesla ModelS cars using the Baolong system (vehicles produced up to around August 2014) You can easily tell if you have thisTesla Model S Baolong TPMS system as Tesla doesnrsquot support displaying tyre pressures in the instrument cluster Bycontrast the later Continental TPMS system does show the pressures in the instrument cluster

OVMS directly supports the Baolong TPMS in Tesla Model S cars without any extra hardware required You simplyneed the usual OVT1 cable

To read the current wheel sensor IDs from the Baolong TPMS ECU ensure that the car is ON (simplest is to wake thecar up and put in drive) and issue the lsquotpms readrsquo command in OVMS

Similarly to write wheel sensor IDs to the Baolong TPMS ECU ensure that the car is ON and issue the lsquotpms writersquocommand in OVMS

194 Chapter 23 Tesla Model S

CHAPTER 24

Tesla Roadster

Vehicle Type TR

The Tesla Roadster support in OVMS is perhaps the most mature in the project All versions (1x 2x and 3x) aresupported for both North American and other variants

241 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 1x 2x and 30 roadsters (all

markets)Vehicle Cable 9665972 OVMS Data Cable for Early TeslasGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna None not requiredSOC Display YesRange Display YesGPS Location Yes (from carrsquos built in GPS)Speed Display YesTemperature Display YesBMS v+t Display Not currently supportedTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control YesCabin Pre-heatcool Con-trol

Not currently supported

LockUnlock Vehicle YesValet Mode Control YesOthers Adhesive velcro strips useful for vehicle attachment

195

Open Vehicles

242 Module Installation in the vehicle

The OVMS module is connected to your Roadster via the CAN bus diagnostic port connector which is located in thepassenger footwell It is made of plastic that is wrapped in grey foam as shown in the photo Typically the connectoris wedged into the front wall near the center console so it wonrsquot rattle Pull the connector out and note the orientationof the pins especially the void above the +12V and Ground pins

The OVMS Data Cable for Tesla Roadster can then be plugged in connecting the car to the OVMS module Makesure to tighten the screws holding the module-side DB9 connector

At this point check the car Tap on the VDS in the centre console and make sure it turns on Insert the key turn on thecar and make sure everything works as expected If you see any problems at all with the car disconnect the OVMSmodule and contact Open Vehicles support for assistance

WarningIf when you plug the OVMS into the car you see any interference to or strange behaviour of car systemsimmediately unplug the module and contact Open Vehicles for assistance Never leave a module connected in suchcircumstances

The OVMS Module is best secured to the front wall of the passenger footwell using adhesive velcro tape With themodule connected to the car diagnostics port connector experiment with various placements until you find a suitablespot For the velcro attachment to work yoursquoll want to choose a spot on the front wall thatrsquos flat for the entire size ofthe module (hint avoid the big round black plastic plug)

Mounting is straightforward

1 Ensure that both velcro strips are fixed together

2 Remove the adhesive backing from one side fasten it to the back of the OVMS module

3 Using a clean dry cloth clean the area of the car passenger footwell wall to which you are going to attach themodule

4 Remove the adhesive backing from the side of the velcro strip facing the car and then firmly push the OVMSmodule into place - holding it still for a few seconds to allow the adhesive to work

5 You can then remove and reinstall the OVMS module as desired via the velcro

196 Chapter 24 Tesla Roadster

Open Vehicles

243 Antenna Installation

You will find the performance of this antenna fantastic - and much better than even your cellphone but proper place-ment is essential Since it has a very long cable you can place the antenna just about wherever you want but pleaseensure it is high-up on the car and away from any metal objects that might interfere with the signal

Possible areas include the bottom of the windscreenwindshield on the passenger side the top of the windscreen onthe passenger side (hidden by the sun visor) behind the passenger on the side pillar in the rear window or under thedashboard (for the brave and experienced at dismantling Tesla Roadster dashboards)

The antenna is connected to the port marked GSM on the OVMS v3 module The GPS port is not used on the TeslaRoadster (as your car already has GPS installed and we can read that positioning information off the CAN bus directly)

2431 Antenna beside rear passenger headrest

The antenna cable is long enough to reach back to the area around the left side seat head This approach is generallyeasiest The module is placed in the left seat footwell near the diagnostic port connector From there the antennacable is routed through the base of the waterfall under the door sill and up the side of the door frame

The door sill is held in place by velcro and is easily removed You may have to loosen the waterfall (held in place byfour screws around the fuse box area) The antenna cable can then be placed on top of the metal of the chassis sillbetween the velcro strips and routed up through the existing plastic trunking At this point the door sill can then beput back in place

2432 Antenna on windshieldwindscreen

To route the antenna cable up to the front windshieldwindscreen you will need to remove the fuse-box cover (onescrew that needs to be turned 90 degrees) then two screws from the box below the fuse box (these screws should becompletely removed in order to be able to remove the box and access the compartment beneath) You do not need toadjust anything in the fuse box - you only need the cover removed to make it easier to route the cable

Start with the cable at the windscreenwindshield and route it down the side of the left side door front pillar Theplastic corner can be pulled back slightly and you can push the cable through into the open bottom compartmentPull the cable through there so that the antenna is where you want it and there is no loose cable outside the box Theantenna itself can be mounted to the windscreenwindshield by first cleaning the area with a clean dry cloth removingthe adhesive backing tape then firmly pushing the antenna against the glass and waiting a few seconds for the adhesiveto stick

Now for the tricky bit You need to get the cable through to the passenger footwell but it is tight It is much easier toget a guide wire up into the fuse box compartment than to get the antenna cable down into the passenger footwell Sowe recommend you use a small (12 inches 30 cm or so) piece of stiff wire to use as a guide and push it up from thearea marked by the green arrow on the bottom right of the picture below Once the guide wire is in the fuse box pushit down into the lower compartment you opened and wrap it around the antenna cable You can then pull the guidewire back down into the passenger footwell bringing the antenna cable with it

The antenna cable can then be screwed in to the OVMS module You can then tidy up any loose cable and screw-backthe lower compartment box (two screws) and fuse box cover (one screw 90 degrees to lock)

244 Configuration Options

The Tesla Roadster specific configuration options are in configuration parameter xtr

243 Antenna Installation 197

Open Vehicles

Instance Default Descriptiondigitalspeedo no Set to yes to enable digital speedometer (2x cars only)digitalspeedoreps 3 Number of CAN bus repeat transmissionscooldowntimelimit 60 Number of minutes after which cooldown is stoppedcooldowntemplimit 31 Temperature (in Celcius) after which cooldown is stoppedprotectlock yes Refuse to lock vehicle when switched on

245 Tesla Roadster Notes

1 In general the OVMS module in a Tesla Roadster acts exactly like the little VDS screen We should be able todo anything that screen can do but no more Here are some notes

2 The lockunlock and valet functions rely on a PIN code This is the same PIN code you enter into the vehicleusing the VDS screen when activating valet mode If you donrsquot know the PIN code either try the default 1234or contact Tesla for assistance

3 While OVMS can lockunlock the doors of all Tesla Roadster models cars outside North America are fitted withan immobiliser and neither OVMS nor the VDS will disarmarm that The OVMS lockunlock functionality onlyapplies to the doors not the alarm in vehicles sold outside North America

4 OVMS v3 can calculate an overall battery health metric This metric is calculated using our own algorithm andis in no way approved by Tesla Battery health is dependent on many factors and hard to bring down to just onesimple number

5 The Tesla Roadster requires the ignition key to be on and manual switches turned to coolheat the cabin It isnot technically possible to do this remotely via OVMS

The digital speedometer function replaces the AMPS display in the dashboard instrument cluster with the vehiclespeed It is only supported on v2x cars (not v15) This is an experimental feature and works 99 of the time butsometimes the car wins and displays AMPS for a split second A better solution is to use the HUD functionality ofOVMS v3 and install an external Heads Up Display in the car

246 TPMS Option

Reading and writing TPMS wheel sensor IDs fromto the Baolong TPMS ECU is supported in v2x Tesla Roadstersusing the optional OVMS K-Line Expansion Board You will need a v32 module (or v31 module labelled on boardas July 2018 or later with K-line pin connected) and an OVT1 vehicle cable (clearly labelled with ldquoOVT1rdquo on thecable)

The optional OVMS K-line Expansion Board should be configured with SW1 set to position 2 (LDO 5v) and S1 into OFF position (away from the ON label)

To read the current wheel sensor IDs from the Baolong TPMS ECU ensure that the ignition switch is ON (so instru-ment panel lights are on) and issue the lsquotpms readrsquo command in OVMS

Similarly to write wheel sensor IDs to the Baolong TPMS ECU ensure that the ignition switch is ON (so instrumentpanel lights are on) and issue the lsquotpms writersquo command in OVMS

Note that this functionality will not work with v15 Tesla Roadsters (that use a different TPMS ECU to the v2x cars)

198 Chapter 24 Tesla Roadster

Open Vehicles

247 Thanks

There are so many people to thank for Tesla Roadster support in OVMS WPetefish for sourcing the car connectorFuzzylogic for the original hardware and software design and demonstration of it working Scott451 for figuring outmany of the Roadster CAN bus messages Tom Saxton for v15 Roadster testing Michael Thwaite for pictures ofantenna installation Bennett Leeds for wordsmithing the manual Mark Webb-Johnson for CAN bus hacking andwriting the vehicle module support Sonny Chen for beta testing and tuning and many others for showing that thiskind of thing can work in the real world

247 Thanks 199

Open Vehicles

200 Chapter 24 Tesla Roadster

CHAPTER 25

Toyota RAV4 EV

Vehicle Type TYR4

At present support for the 2012-2014 Toyota RAV4 EV in OVMS is experimental and under development Thisvehicle type can be used by early adopters as long as you understand the limitations The current release only showsinformation from the Tesla CAN bus not the Toyota CAN bus and is read-only

201

Open Vehicles

251 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support All 2012-2014 RAV4 EV are identical

and no other years are supportedVehicle Cable A custom cable is required to connect at the left rear of the vehicle Tesla and Toyota CAN

buses are available at the Gateway ECUGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA)SOC Display Yes (Tesla BMS value)Range Display Not currently supportedGPS Location YesSpeed Display YesTemperature Dis-play

Yes

BMS v+t Display YesTPMS Display Not currently supportedCharge Status Dis-play

Yes

Charge InterruptionAlerts

Yes

Charge Control Not currently supportedCabin Pre-heatcool Control

Not currently supported

LockUnlock Vehi-cle

Not currently supported

Valet Mode Control Not currently supportedOthers

The Tesla CAN bus already had decodes available so those were implemented already The primary focus goingforward will be decoding the Toyota CAN bus to replicate SafetyConnect connected features like Remote Climatebefore the 3G shutdown ends that manufacturer provided functionality

The file xr4monhtm should be installed as a Page type Web Plugin to display detailed information about the carrsquosstatus

202 Chapter 25 Toyota RAV4 EV

CHAPTER 26

Tracking Vehicles

Vehicle Type XX

The track vehicle will be documented here

261 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support Not widely tested but should be allVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left) or any cable

proving powerGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display NoRange Display NoGPS Location Yes (from modem module GPS)Speed Display Yes (from modem module GPS)Temperature Display NoBMS v+t Display NoTPMS Display NoCharge Status Display NoCharge InterruptionAlerts

No

Charge Control NoCabin Pre-heatcoolControl

No

LockUnlock Vehicle NoValet Mode Control NoOthers None

203

Open Vehicles

204 Chapter 26 Tracking Vehicles

CHAPTER 27

VW e-Up

Vehicle Type VWUP

This vehicle type supports the VW e-UP (2013- 2020-) Skoda Citigo E IV and the Seat MII electric (2020-) Con-nection can be made via the OBD2 port to the top left of the driving pedals andor the Comfort CAN bus eg belowthe passenger seat (T26 connector instead of the VW OCU there)

The main difference currently is that the OBD connection enables access to way more metrics (eg down to cellvoltages) while the Comfort CAN connection is necessary if write access is needed eg for remote climate controlThe Comfort CAN also provides data in more cases without turning on the car or charging as the bus wakes on manyevents (eg opening of doors) and can also be woken via OVMS

For the full experience making both connections is recommended

271 Using OBD2

Connection to OBD2 is done with the standard OVMS OBD2-cable just below the fuses left of the driving pedals

205

Open Vehicles

272 Using Comfort CAN

Connection to Comfort CAN can be done by removing the OCU below the passenger seat using a custom 26-pinadapter cable to the T26A plug (advantage the connections for the GSM amp GPS-antennas of the car can be used usinga Fakra-SMA adapter)

206 Chapter 27 VW e-Up

Open Vehicles

272 Using Comfort CAN 207

Open Vehicles

The passenger seat doesnrsquot need to be removed completely you can access the OCU connection from the back whentilting the unscrewed seat to the front To unscrew the seat yoursquoll need an XZN (triple-square german ldquoVielzahnrdquo)M10 bit Hint raise the seat to gain access to the rear screws

The T26a plug is secured by the white clamp open it fully to the left to unplug

273 Using both Connections

This document shows two options to use both connections

1 Variant 1 connects to the Comfort CAN using the OCU T26A connector

2 Variant 2 connects to the Comfort CAN by tapping the Comfort CAN cables

Both variants allow keeping the OCU in place If you intend to replace the OCU by the OVMS and reuse the OCUantennas for the OVMS variant 1 will probably be the better choice

2731 Variant 1

Connecting to the Comfort CAN using the OCU T26A connector

You need to establish a connection between the OBD2 and the OCU ports If installing the OVMS near the OBD2port you need to make a cable to connect to the T26A plug (or tap into the T26A cable there) If installing the OVMSreplacing the OCU you need to connect the OBD2 CAN bus from there

An adapter cable has to be made with the following connections

208 Chapter 27 VW e-Up

Open Vehicles

The cable used between the OBD plug and the DB9-F plug needs to be twisted to avoid transmission problems Agood cable to use here is a CAT-5 or CAT-6 double shielded network cable Be sure to not only connect CAN hi andCAN lo but also connect ground

T26 OBD DB9-F Signal26 4 3 Chassis Power GND 14 2 can1 L (OBD2 CAN Low) 6 7 can1 H (OBD2 CAN High) 4 can2 L (not used) 5 can2 H (not used)2 6 can3 L (Comfort-CAN Low)14 8 can3 H (Comfort-CAN High)1 9 +12V Vehicle Power

Important note the VW T26a pin numbering scheme does not follow the IT standard (zig zag) but instead has pins1-13 left to right on the top and 14-26 left to right on the bottom row See image above

2732 Variant 2

Connecting to the Comfort CAN by tapping the Comfort CAN cables

Description amp images by courtesy of GE user donaldduck8

This approach installs the OVMS near the OBD2 port and keeps the OCU in place Advantages

1 The OCU remains untouched and can be switched onoff as needed (fuse SD1)

2 No need to unmount the passenger seat

3 The OVMS can be disabledenabled any time simply via the OBD2 plug

The OVMS will be mounted on the driver side behind the footwell panel near the OBD2 port The Comfort CANsignal will be taken by tapping the cables behind the passengerrsquos footwell panel

The cable used needs to be twisted to avoid transmission problems A good cable to use here is a CAT-5 or CAT-6double shielded network cable A network cable has four pairs you will only need one pair here We recommendconnecting the shielding as well to avoid issues

273 Using both Connections 209

Open Vehicles

To connect to the OVMS you can use either a custom DB9 plug or add a DA26 connector You need to connect toCAN3

Comfort CAN OBD DB9-F DA26 Signal 4 3 8 Chassis Power GND 14 2 5 can1 L (OBD2 CAN Low) 6 7 15 can1 H (OBD2 CAN High) 12 4 7 can2 L (not used) 13 5 17 can2 H (not used)orangebrown 6 6 can3 L (Comfort-CAN Low)orangegreen 8 16 can3 H (Comfort-CAN High) 16 9 9 +12V Vehicle Power

Step 1 Remove the passenger footwell panel

Step 2 Tap into the Comfort CAN

Comfort CAN is on cables orangegreen (rarrCAN3-H) and orangebrown (rarrCAN3-L) Carefully remove a part of theisolation solder on your twisted pair cables then restore the isolation (eg by applying PlastiDip)

210 Chapter 27 VW e-Up

Open Vehicles

Step 3 Lay the cable towards the fuse box amp OBD2 port on the left

273 Using both Connections 211

Open Vehicles

Step 4 Use velcro tape to mount the OVMS on the side wall

Step 5 Stick the GPS antenna eg onto the air vent pipe To disable the OCU unplug fuse SD1

212 Chapter 27 VW e-Up

Open Vehicles

Step 6 Stick the GSM antenna eg on the lower panelrsquos rear side

Finally Refit all panels

273 Using both Connections 213

Open Vehicles

274 Basic Configuration

After selecting the VW e-Up vehicle module the corresponding settings have to be made in the web interface via theldquoVW e-Uprdquo menu under ldquoFeaturesrdquo

214 Chapter 27 VW e-Up

Open Vehicles

By default both connections are activated

For more details on the two connection types please see the corresponding projects

VW e-Up via Comfort CAN (T26A)

VW e-Up via OBD2

The initial code is shamelessly copied from the original projects for the Comfort CAN by Chris van der Meijden andfor the OBD2 port by SokoFromNZ

List of (possible) metrics via OBD2 httpswwwgoingelectricdewikiListe-der-OBD2-Codes

If OBD is selected a sample page with some charging metrics is shown in the web interface

274 Basic Configuration 215

Open Vehicles

216 Chapter 27 VW e-Up

Open Vehicles

Beware obviously these values have great uncertainties (in my car the DC output voltage of the charger is alwayslower than the voltage of the battery ) But eg the internal energy counters are very informative )

Additional custom web pages (code for the example above is below) can be defined as described here httpsdocsopenvehiclescomenlatestpluginREADMEhtmlhighlight=web20plugininstalling-web-plugins

274 Basic Configuration 217

Open Vehicles

275 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 2013-Vehicle Ca-ble

Comfort CAN T26A (OCU connector cable located under front passenger seat) to DB9 Data Cablefor OVMS using pin 6 and 8 for can3 _AND_ OBD-II to DB9 Data Cable for OVMS (1441200right or 1139300 left) for can1

GSMAntenna

T4AC - R205 with fakra_sma adapter cable or 1000500 Open Vehicles OVMS GSM Antenna (orany compatible antenna)

GPS An-tenna

T4AC - R50 with fakra_sma adapter cable or 1020200 Universal GPS Antenna (or any compatibleantenna)

SOC Dis-play

Yes

Range Dis-play

Yes

Cabin Pre-heatcoolControl

Yes

GPS Loca-tion

Yes (from modem module GPS)

Speed Dis-play

Yes

Tempera-ture Display

Yes (see list of metrics below)

BMS v+tDisplay

Yes

TPMS Dis-play

tba

Charge Sta-tus Display

Yes

ChargeInterruptionAlerts

Yes (per notification on the charging state)

ChargeControl

tba

LockUnlockVehicle

No

Valet ModeControl

No

Others See list of metrics below

276 Supported Standard Metrics

The second column specifies the bus from which the metrics are obtained Metrics via OBD are only updated when thevehicle is on (ignition started) or some in charging mode Metrics via T26 (Comfort CAN) can be updated on demandby waking the Comfort CAN from the OVMS module During charging the Comfort CAN automatically wakes every5 of SoC

218 Chapter 27 VW e-Up

Open Vehicles

Metric name bus Example value Descriptionvb12vvoltage direct 129 V Current voltage of the 12V batteryvbconsumption OBD 0Whkm Main battery momentary consumptionvbcurrent OBD 232 A Current current into (negative) or out of (positive) the main batteryvbenergyrecdtotal OBD 578323 kWh Energy recovered total (life time) of the main battery (charging and recuperation)vbenergyusedtotal OBD 540342 kWh Energy used total (life time) of the main batteryvbpower OBD 23234 kW Current power into (negative) or out of (positive) the main batteryvbrangeest T26 99km Estimated rangevbrangeideal T26 48km Ideal rangevbsoc OBD T26 882 Current usable State of Charge (SoC) of the main batteryvbtemp OBD 225 degC Current temperature of the main batteryvbvoltage OBD 3202 V Current voltage of the main batteryvc12vcurrent OBD 78A Output current of DCDC-convertervc12vpower OBD 0123kW Output power of DCDC-convertervc12vtemp OBD 345degC Temperature of DCDC-convertervc12vvoltage OBD 123V Output voltage of DCDC-convertervccharging T26 true Is vehicle charging (true = ldquoVehicle CHARGINGrdquo state veon=false if this is true)vcclimit fixed 1632A Maximum charger output currentvccurrent OBD 125A Momentary charger output currentvcefficiency OBD 913 Charging efficiency calculated by vbpower and vcpowervckwh OBD 26969kWh Energy sum for running chargevcmode T26 standard standard range performance storagevcpilot T26 no Pilot signal presentvcpower OBD 7345 kW Input power of chargervcstate T26 done charging topoff done prepare timerwait heating stoppedvcsubstate T26 scheduledstop scheduledstart onrequest timerwait powerwait stopped interruptedvctemp OBD 16degC Charger temperaturevctime T26 0Sec Duration of running chargevcvoltage OBD 0V Momentary charger supply voltagevdcp T26 yes yes = Charge port openvdfl T26 yes = Front left door openvdfr T26 yes = Front right door openvdhood T26 yes = Hoodfrunk openvdrl T26 yes = Rear left door openvdrr T26 yes = Rear right door openvdtrunk T26 yes = Trunk openveawake T26 no yes = Vehiclebus awake (switched on)vecabintemp T26 20degC Cabin temperaturevedrivetime T26 0Sec Seconds driving (turned on)veheadlights T26 yes = Headlights onvehvac T26 yes = HVAC activevelocked T26 yes = Vehicle lockedveon T26 true Is ignition on and drivable (true = ldquoVehicle ONrdquo false = ldquoVehicle OFFrdquo state)veparktime T26 49608Sec Seconds parking (turned off)veservrange OBD 12345km Distance to next scheduled maintenanceservice [km]veservtime OBD 1572590910Sec Time of next scheduled maintenanceservice [UTC]vetemp OBD T26 Ambient temperaturevitemp OBD Inverter temperaturevmtemp OBD 0degC Motor temperaturevpodometer OBD T26 2340 km Total distance traveledvpspeed T26 0kmh Vehicle speed

Continued on next page

276 Supported Standard Metrics 219

Open Vehicles

Table 1 ndash continued from previous pageMetric name bus Example value Descriptionvvin T26 VF1ACVYB012345678 Vehicle identification number

277 Custom Metrics

In addition to the standard metrics above the following custom metrics are read from the car or internally calculatedby OVMS using read values

Metricname

bus Examplevalue

Description

xvubcelldeltaOBD 0012 V Delta voltage between lowest and highest cell voltagexvubsocabs OBD 853 Current absolute State of Charge (SoC) of the main batteryxvucsocnormOBD 805 Current normalized State of Charge (SoC) of the main battery as reported by

charge management ECUxvucaci1 OBD 59 A AC current of AC charger phase 1xvucaci2 OBD 70 A AC current of AC charger phase 2 (only for model 2020+)xvucacp OBD 7223 kW Current charging power on AC side (calculated by ECUrsquos AC voltages and

AC currents)xvucacu1 OBD 223 V AC voltage of AC charger phase 1xvucacu2 OBD 233 V AC voltage of AC charger phase 2 (only for model 2020+)xvucdci1 OBD 12 A DC current of AC charger 1xvucdci2 OBD 12 A AC current of AC charger 2 (only for model 2020+)xvucdcp OBD 6500 kW Current charging power on DC side (calculated by ECUrsquos DC voltages and

DC currents)xvucdcu1 OBD 380 V DC voltage of AC charger 1xvucdcu2 OBD 375 V DC voltage of AC charger 2 (only for model 2020+)xvuceffcalc OBD 900 Charger efficiency calculated by AC and DC powerxvuceffecu OBD 923 Charger efficiency reported by the Charger ECUxvuclosscalc OBD 0733 kW Charger power loss calculated by AC and DC powerxvuclossecu OBD 0620 kW Charger power loss reported by the Charger ECUxvueservdaysOBD 78 days Time to next scheduled maintenanceservice [days]xvumsocabs OBD 853 Current absolute State of Charge (SoC) of the main battery as reported by

motor electronics ECUxvumsocnormOBD 805 Current normalized State of Charge (SoC) of the main battery as reported by

motor electronics ECU

278 Example Code for Web Plugin with some custom metrics

ltdiv class=panel panel-primarygtltdiv class=panel-headinggtCustom Metricsltdivgtltdiv class=panel-bodygt

lthrgt

ltdiv class=receivergtltdiv class=clearfixgtltdiv class=metric progress data-metric=vbsoc data-prec=1gtltdiv class=progress-bar value-low text-left role=progressbar

(continues on next page)

220 Chapter 27 VW e-Up

Open Vehicles

(continued from previous page)

aria-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoCltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=xvubsocabs data-prec=1gtltdiv class=progress-bar progress-bar-info value-low text-left role=progressbar

rarr˓aria-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoC (absolute)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbenergyusedtotal data-prec=2gtltspan class=labelgtTOTALSampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbsp

rarr˓ampnbspampnbspampnbspUsedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vbenergyrecdtotal data-prec=2gtltspan class=labelgtChargedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vpodometer data-prec=0gtltspan class=labelgtOdoltspangtltspan class=valuegtltspangtltspan class=unitgtkmltspangt

ltdivgtltdiv class=metric number data-metric=veservrange data-prec=0gtltspan class=labelgtSERVICEampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbspamp

rarr˓nbspampnbspampnbspampnbspRangeltspangtltspan class=valuegtltspangtltspan class=unitgtkmltspangt

ltdivgtltdiv class=metric number data-metric=xvueservdays data-prec=0gtltspan class=labelgtDaysltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

lth4gtBatterylth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=vbvoltage data-prec=1gtltdiv class=progress-bar value-low text-left role=progressbararia-valuenow=0 aria-valuemin=300 aria-valuemax=420 style=width0gtltdivgt

(continues on next page)

278 Example Code for Web Plugin with some custom metrics 221

Open Vehicles

(continued from previous page)

ltspan class=labelgtVoltageltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbcurrent data-prec=1gtltdiv class=progress-bar progress-bar-danger value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-200 aria-valuemax=200 style=width0gtltdivgtltspan class=labelgtCurrentltspangtltspan class=valuegtltspangtltspan class=unitgtAltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbpower data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-70 aria-valuemax=70 style=width0gtltdivgtltspan class=labelgtPowerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgtltdivgt

ltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbtemp data-prec=1gtltspan class=labelgtTempltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangtltdivgtltdiv class=metric number data-metric=xvubcelldelta data-prec=3gtltspan class=labelgtCell deltaltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangtltdivgt

ltdivgt

lth4gtTemperatureslth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=vetemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtAmbientltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vecabintemp data-prec=1gt

(continues on next page)

222 Chapter 27 VW e-Up

Open Vehicles

(continued from previous page)

ltdiv class=progress-bar progress-bar-warning value-low text-left role=rarr˓progressbar

aria-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtCabinltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbtemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtBatteryltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vctemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtChargerltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vc12vtemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtDCDC-Converterltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vitemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtInverterltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vmtemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbar(continues on next page)

278 Example Code for Web Plugin with some custom metrics 223

Open Vehicles

(continued from previous page)

aria-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtMotorltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgt

ltdivgtltdivgt

ltdivgtltdivgt

ltdivgt

279 Custom Data Logs

2791 SOC Monitoring Log

The SOC monitoring log provides detailed data about the correlations and connections between the various SOCsvoltage level amp energycoulomb chargedischarge amounts

You need to enable this log explicitly by configuring a storage time via config param xvu logsocmonstoretime (in days) Set to 0empty to disable the log Already stored log entries will be kept on the serveruntil expiry or manual deletion

Log entries are created on SOC changes while charging and every 10 seconds while driving

bull Notification subtype xvulogsocmon

bull History record type XVU-LOG-SOCMon

bull Format CSV

bull Archive time config xvu logsocmonstoretime (days 0=off)

bull Fieldscolumns

ndash temp ndash battery temperature [degC]

ndash charging ndash 01

ndash soc_abs_bms ndash absolute SOC from BMS (ECU 8C PID 028C) []

ndash soc_abs_eng ndash absolute SOC from engine (ECU 01 PID F45B) []

ndash soc_norm_cmg ndash normalized user SOC from charge manager (ECU BD PID 1DD0) []

ndash soc_norm_eng ndash normalized user SOC from engine (ECU 01 PID 1164) []

ndash soc_norm ndash previously selected soc_norm_eng while driving now always soc_norm_cmg []

ndash voltage ndash momentary total battery voltage [V]

ndash current ndash momentary battery current negative = charging [A]

ndash soh ndash state of health sourced as configured []

ndash cac ndash battery capacity sourced as configured [Ah]

ndash energy_used ndash total car energy discharge counter [kWh]

ndash energy_recd ndash total car energy charge counter [kWh]

224 Chapter 27 VW e-Up

Open Vehicles

ndash coulomb_used ndash total car coulomb discharge counter [Ah]

ndash coulomb_recd ndash total car coulomb charge counter [Ah]

ndash pack_vavg ndash average cell voltage [V]

ndash pack_vmin ndash minimum cell voltage [V]

ndash pack_vmax ndash maximum cell voltage [V]

ndash pack_vstddev ndash cell voltage standard deviation [V]

ndash pack_vgrad ndash cell voltage series quality (gradient)

ndash energy_range ndash remaining usable energy from MDF range estimation (ECU 17 PID 22E4) [kWh]

279 Custom Data Logs 225

Open Vehicles

226 Chapter 27 VW e-Up

CHAPTER 28

VW e-Up via OBD2

Vehicle Type VWUPOBD

This vehicle type supports the VW e-UP (new model from year 2020 onwards) Untested (so far) but probably workingThe older models of the e-Up as well as Skoda Citigo E IV and Seat MII electric

Connection is via the standard OBD-II port (above the drivers left foot)

All communication with the car is read-only For changing values (ie climate control) see the T26A connection tothe Comfort CAN bus

281 Support Overview

Function Support StatusHardware No specific requirementsVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display YesBMS v+t Display Yes (including cell details)TPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers See list of metrics below

227

Open Vehicles

282 Vehicle States

Warning For proper state detection the 12V calibration is crucial Calibrate using the OVMS Web UI Configrarr Vehicle rarr 12V Monitor

Three vehicle states are supported and detected automatically

Vehicle ON The car is on It is drivable

Vehicle CHARGING The car is charging The carrsquos Charger ECU is responsive and reports charging activity

Vehicle OFF The car is off It hasnrsquot drawn (or charged) any current into the main battery for a period of time andthe 12V battery voltage is smaller than 129V

283 Supported Standard Metrics

Metrics updated in state ldquoVehicle ONrdquo or ldquoVehicle CHARGINGrdquo

Metric name Examplevalue

Description

veon yes Is ignition on and drivable (true = ldquoVehicle ONrdquo false = ldquoVehicle OFFrdquostate)

vccharging yes Is vehicle charging (true = ldquoVehicle CHARGINGrdquo state veon=false if thisis true)

vclimitsoc 100 Sufficient SOC timer mode SOC destination or user CTP configuration (seebelow)

vcmode range ldquorangerdquo = charging to 100 SOC else ldquostandardrdquovctimermode no Yes = currentnext charge under timer controlvcstate done charging stopped donevcsubstate scheduledstop scheduledstop scheduledstart onrequest timerwait stopped interruptedvb12vvoltage1 129 V Current voltage of the 12V batteryvbvoltage 3202 V Current voltage of the main batteryvbcurrent 232 A Current current into (negative) or out of (positive) the main batteryvbpower 23234 kW Current power into (negative) or out of (positive) the main batteryvbenergyusedtotal 540342 kWh Energy used total (life time) of the main batteryvbenergyrecdtotal 578323 kWh Energy recovered total (life time) of the main battery (charging and recu-

peration)vbtemp 225 degC Current temperature of the main batteryvpodometer 2340 km Total distance traveled

Metrics updated only in state ldquoVehicle ONrdquo

Metric name Example value Descriptionvbsoc2 882 Current usable State of Charge (SoC) of the main batteryvedrivemode 2 1=STD 2=ECO 3=ECO+vegear 1 1=forward 0=neutral -1=reverse (2020 model only)

Metrics updated only in state ldquoVehicle CHARGINGrdquo1 Also updated in state ldquoVehicle OFFrdquo2 Restriction by the ECU Supplied when the ignition is on during charging Use xvubsoc as an alternative when charging with ignition off

228 Chapter 28 VW e-Up via OBD2

Open Vehicles

Metric name Example value Descriptionvcpower 7345 kW Input power of chargervcefficiency 913 Charging efficiency calculated by vbpower and vcpower

284 Custom Metrics

In addition to the standard metrics above the following custom metrics are read from the car or internally calculatedby OVMS using read values

State metrics

Metric name Example value Descriptionxvuehvchgmode 0 High voltage charge mode 0=off 1=Type2 4=CCSxvuelvautochg 1 Auxiliary battery (12V) auto charge mode (01)xvuelvpwrstate 0 Low voltage (12V) power state (0=off 4=12V 8=HVAC 15=on)

Timed charge metrics

Metric name Example value Descriptionxvuclimitsocmax 80 Charge schedule maximum SOCxvuclimitsocmin 20 Charge schedule minimum SOCxvuctimermodedef yes Charge timer defined amp default

xvuctimermodedef tells if a charge schedule has been configured and enabled If so the car uses timedcharging by default (the charge mode button will be lit) vctimermode tells if the charge timer is or will actuallybe used for the current or next charge ie reflects the mode selected by pushing the button

With timed charging the car first charges to the minimum SOC as soon as possible (when connected) If the maximumSOC configured for the schedule hasnrsquot been reached by then it will then wait for the timer to signal the second phaseto charge up to the maximum SOC The ldquosufficient SOCrdquo vclimitsoc will be the maximum SOC if less than100 If the timer is disabled or set to charge up to 100 the sufficient SOC is set to the user configured charge timeprediction SOC limit (config xvu ctpsoclimit)

Charging above vclimitsoc is classified as the ldquotopping offrdquo charge phase When crossing that SOC thresholdan intermediate charge status notification is sent

Note xvuclimitsocmin will show the configured minimum SOC also if no schedule is currently enabledxvuclimitsocmax shows the maximum for the currentnext schedule to apply If no schedule is enabled itwill be zero

Metrics updated in state ldquoVehicle ONrdquo or ldquoVehicle CHARGINGrdquo

Metric name Example value Descriptionxvubcelldelta 0012 V Delta voltage between lowest and highest cell voltagexvubsoc 853 Current absolute State of Charge (SoC) of the main battery

Metrics updated only in state ldquoVehicle CHARGINGrdquo

284 Custom Metrics 229

Open Vehicles

Metric name Examplevalue

Description

xvuceffecu3 923 Charger efficiency reported by the Charger ECUxvuclossecu3 0620 kW Charger power loss reported by the Charger ECUxvucacp 7223 kW Current charging power on AC side (calculated by ECUrsquos AC voltages and AC

currents)xvucdcp 6500 kW Current charging power on DC side (calculated by ECUrsquos DC voltages and DC

currents)xvuceffcalc 900 Charger efficiency calculated by AC and DC powerxvuclosscalc 0733 kW Charger power loss calculated by AC and DC powerxvucccsu4 3315V CCS charger supplied voltage [V]xvucccsi4 622A CCS Charger supplied current [A]xvucccsp4 206193kW CCS Charger supplied power [kW]

285 Battery Capacity amp SOH

e-Up Model Total capacity Usable capacityGen 1 (2016) 187 kWh 50 Ah 164 kWh 439 Ah (877)Gen 2 (2020) 368 kWh 120 Ah 323 kWh 1053 Ah (877)

There are currently two ways to get an estimation of the remaining capacity of the e-Up

1 By deriving a usable energy capacity from the MFD range estimation

2 By deriving a total coulomb capacity from the coulombs charged

You can configure which of the estimations you want to use as the standard SOH from the ldquoFeaturesrdquo web page or bysetting the config parameter xvu batsohsource to either charge (default) or range

Note Consider the capacity estimations as experimental preliminary We need field data to optimize thereadings If yoursquod like to help us see below

The MFD range estimation seems to include some psychological factors with an SOC below 30 so we onlyprovide this and the derived capacity in two custom metrics The capacity derivation is only calculated with SOC gt=30 (initial value needs SOC gt= 70) but if so is available immediately after switching the car on This can serve asa quick first estimation relate it to the usable capacity of your model

The range based SOH is taken at itrsquos maximum peaks observed and copied if higher than the previously observedvalue or added smoothed if lower So to take the next reading directly set metric xvubsohrange to 0 beforeswitching on the car

The charge coulomb based estimation provides a better estimation but will need a little more time to settle Usablemeasurements need charges of at least 30 SOC the more the better Estimations are only calculated if a charge hasexceeded 30 SOC and results are smoothed over multiple charges to provide stable readings

bull To get a rough capacity estimation charge at least 30 normalized SOC difference

3 Only supplied by ECU when the car ignition is on during charging4 These are not measurements by the car but provided as is by the charger and typically deviate from the battery metrics According to IEC

61851 CCS currents may be off by +- 3 and voltages by +- 5 The power figures displayed by some chargers also typically wonrsquot match thesevalues possibly because the charger displays the power drawn from the grid (including losses)

230 Chapter 28 VW e-Up via OBD2

Open Vehicles

bull To get a good capacity estimation do at least three charges with each covering 60 or more normalized SOCdifference

Charging by CCS (DC) apparently yields higher results especially on the energy estimations We donrsquot know yet thereason or if we need to compensate this

Note the SOH (state of health) is currently coupled directly and solely to the calculated amp-hour capacity CAC

To log your capacity data on a connected V2 server do

OVMS config set xvu logchargecapstoretime 30

30 is the number of days to keep the data set to 0 to disable The counters will be stored in tableXVU-LOG-ChargeCap with one entry every 24 absolute SOC difference Resulting CACSOH updates willbe logged in table XVU-LOG-ChargeCapSOH You can also extract the data from your module log file by filteringlines matching ChargeCap

2851 Capacity and SOH metrics

Metric name Example value Descriptionxvubsohcharge 9923 SOH based on charge energy sumxvubsohrange 9889 SOH based on MFD range estimationxvubcapahabs 12271Ah Total coulomb capacity estimationxvubcapahnorm 11363Ah Usable coulomb capacity estimationxvubcapkwhabs 391kWh Total energy capacity estimationxvubcapkwhnorm 3621kWh Usable energy capacity estimationxvubcapkwhrange 328947kWh Usable energy capacity estimation from MFD rangexvubenergyrange 185kWh Current energy used by MFD range estimation

2852 Provide Data to the Developers

To help us with optimizing the capacity estimations first of all enable file logging if not already enabled Then enableextended polling and logging before a charge by

OVMS config set xvu dc_interval 30OVMS log level verbose v-vweup

After the charge disable the extended polling and logging

OVMS config set xvu dc_interval 0OVMS log level info v-vweup

Then download all log files written during the charge (archived and current) zip them and mail the zip to MichaelBalzer ltdexterdexters-webdegt The log data will only be used for technical analysis and deleted afterwards

Note if you forgot enabling the local log but still have chargecap logs on the server these can help as well

Thanks

286 Configuration Variables

The main configuration variables can be set through the web configuration page

286 Configuration Variables 231

Open Vehicles

bull VW e-Up rarr Features

Some configuration variables are kept ldquounder the hoodrdquo as these will normally not need to be changed except forsome special use cases or for development debugging

Configuration variables can be listed using command config list xvu and changed using command configset xvu ltvariablegt ltvaluegt

Configuration variable Default value Descriptionbatsohsource charge SOH source ndash see abovebmsautoreset no Reset BMS statistics on use phase transitionscanwrite no Allow CAN write accesscell_interval_awk 60 BMS cell query interval in awake state [s]cell_interval_chg 60 BMS cell query interval in charge state [s]cell_interval_drv 15 BMS cell query interval in drive state [s]con_obd yes Enable OBDII connectioncon_t26 yes Enable T26 connectionctpmaxpower 0 Charge time prediction fallback power limit [kW] (0=none)ctpsoclimit 80 Charge time prediction fallback SOC limit []dc_interval 0 Development additional DC charge PID query interval [s] (0=off)logchargecapcpstep 24 Charge capacity checkpoint interval [110]logchargecapminvalid 272 Charge capacity min SOC hub for SOH change [110]logchargecapstoretime 0 Charge capacity server log archive time [days] (0=off)modelyear 2012 Vehicle model yearnotifychargestartdelay 24 Charge start notification delay [s]5

287 Shell Commands

bull xvu polling ltstatus|pause|continuegt ndash control OBD2 polling

The OBD2 polling is normally continuously active as long as the vehicle module is loaded To free the CANbus from this load during an extended OBD2 diagnostics or modification (coding adaptation) session you cantemporarily pause the polling using this command

There is no time limit for a pause keep in mind you need to explicitly continue the polling when yoursquore doneDuring a polling pause no vehicle state changes can be detected

288 Custom Status Page for Web UI

Note This plugin is obsolete use the standard page VW e-Up rarr Charging Metrics instead We keep the sourcehere as a base for user customization

The easiest way to display custom metrics is using the Web Plugins feature of OVMS (see Installing Web Plugins)

This page plugin content shows the metrics in a compact form which can be displayed on a phone in landscape modeon the dashboard of the car Best approach is to connect the phone directly to the OVMS AP-WiFi and access the webUI via the static IP (19216841) of OVMS

5 Charge start needs some time to ramp up the charge current which implies charge speed amp time estimations If you want the start notificationas fast as possible reduce the value

232 Chapter 28 VW e-Up via OBD2

Open Vehicles

ltdiv class=panel panel-primarygtltdiv class=panel-headinggtVW eUpltdivgtltdiv class=panel-bodygt

lthrgt

ltdiv class=receivergtltdiv class=clearfixgtltdiv class=metric progress data-metric=vbsoc data-prec=2gtltdiv class=progress-bar value-low text-left role=progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoCltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=xvubsoc data-prec=2gtltdiv class=progress-bar progress-bar-info value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoC (absolute)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

(continues on next page)

288 Custom Status Page for Web UI 233

Open Vehicles

(continued from previous page)

ltdivgtltdivgt

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbenergyusedtotal data-prec=3gtltspan class=labelgtTOTALSampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbspamp

rarr˓nbspampnbspampnbspampnbspUsedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vbenergyrecdtotal data-prec=3gtltspan class=labelgtChargedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vpodometer data-prec=0gtltspan class=labelgtDistanceltspangtltspan class=valuegtltspangtltspan class=unitgtkmltspangt

ltdivgtltdivgt

lth4gtBatterylth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=vbvoltage data-prec=1gt

ltdiv class=progress-bar value-low text-left role=progressbararia-valuenow=0 aria-valuemin=300 aria-valuemax=350 style=width0gtltdivgtltspan class=labelgtVoltageltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbcurrent data-prec=1gtltdiv class=progress-bar progress-bar-danger value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-200 aria-valuemax=200 style=width0gtltdivgtltspan class=labelgtCurrentltspangtltspan class=valuegtltspangtltspan class=unitgtAltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbpower data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-70 aria-valuemax=70 style=width0gtltdivgtltspan class=labelgtPowerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgt

(continues on next page)

234 Chapter 28 VW e-Up via OBD2

Open Vehicles

(continued from previous page)

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbtemp data-prec=1gtltspan class=labelgtTempltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdiv class=metric number data-metric=xvubcelldelta data-prec=3gtltspan class=labelgtCell deltaltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangt

ltdivgtltdivgt

lth4gtChargerlth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=xvucacp data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=8 style=width0gtltdivgtltspan class=labelgtAC Powerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=xvucdcp data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=8 style=width0gtltdivgtltspan class=labelgtDC Powerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgt

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vcefficiency data-prec=1gt

ltspan class=labelgtEfficiency (total)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdiv class=metric number data-metric=xvuceffcalc data-prec=1gtltspan class=labelgtEfficiency (charger)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdiv class=metric number data-metric=xvuclosscalc data-prec=3gtltspan class=labelgtLoss (charger)ltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgt(continues on next page)

288 Custom Status Page for Web UI 235

Open Vehicles

(continued from previous page)

ltdivgtltdivgtltdivgt

ltdivgt

236 Chapter 28 VW e-Up via OBD2

CHAPTER 29

VW e-Up via Comfort CAN (T26A)

Vehicle Type integrated in VWUP

This part was the initial code for the OVMS VWUP vehicle module Development started in January 2020 by Chrisvan der Meijden

It supports the VW e-UP (2013- 2020-) Skoda Citigo E IV and the Seat MII electric (2020-) directly connected tothe comfort can bus through the lsquoT26Arsquo socket

237

Open Vehicles

291 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 2020- (2013- VW e-Up as well)Vehicle Cable Comfort CAN T26A (OCU connector cable located under front passenger seat) to DB9 Data

Cable for OVMS using pin 6 and 8 for can3GSM Antenna T4AC - R205 with fakra_sma adapter cable or 1000500 Open Vehicles OVMS GSM Antenna

(or any compatible antenna)GPS Antenna T4AC - R50 with fakra_sma adapter cable or 1020200 Universal GPS Antenna (or any com-

patible antenna)SOC Display YesRange Display YesCabin Pre-heatcool Control

Yes

GPS Location Yes (from modem module GPS)Speed Display YesTemperature Dis-play

Yes (outdoor cabin)

BMS v+t Display NoTPMS Display NoCharge Status Dis-play

Yes

Charge Interrup-tion Alerts

Yes (per notification on the charging state)

Charge Control tbaLockUnlockVehicle

No

Valet Mode Con-trol

No

Others Odometer trip VIN status of lock plug lights doors trunk and bonnet

292 Pinout OCU T26A - OVMS DB9 adapter

For the T26A approach we directly tap into the comfort can bus via the original OCU cable

The OCU connector is located under the passenger seat

238 Chapter 29 VW e-Up via Comfort CAN (T26A)

Open Vehicles

Advantage is the direct write access to the comfort can bus

Disadvantage is that we wonrsquot be able to access all control units of the car

OCU DB9-F Signal26 3 Chassis Power GND 2 can1 L (Can Low not used) 7 can1 H (Can High not used) 4 can2 L (Can Low not used) 5 can2 H (Can High not used)2 6 can3 L (Comfort-can Low)14 8 can3 H (Comfort-can High)1 9 +12V Vehicle Power

For confectioning the T26A adapter cable you can use a standard 26 pin ribbon cable (2x13 pins 254mm grid dimen-sion) and a DB9 female D-Sub connector You will need to grind down the rim of the socket of the ribbon cable

To make a GSMGPS adapter cable to connect to the original VW fakra socket you can use a double fakra maleconnector with two SMA male connectors attached

292 Pinout OCU T26A - OVMS DB9 adapter 239

Open Vehicles

293 User notes

bull Remove the passenger seat (on right hand drive cars the driverrsquos seat)

bull Open the carpet lid

bull Disconnect the T26A cable and the fakra cable from the OCU (online communication unit)

bull Remove the OCU

bull Connect the confectioned T26A adapter DB9 cable attached to the OVMS to the VW T26A connector of thecar

bull Connect your GMSGPS fakra adapter to the VW fakra cable

bull Fit OVMS in the compartment

bull Close the carpet lid

bull Reinstall the passenger seat

bull Configure OVMS as described in the OVMS user manual

bull Configure lsquoModel yearrsquo lsquoCan write accessrsquo and lsquoConnection typersquo under VW e-Up -gt Features

bull lsquoModel yearrsquo and lsquoCan write accessrsquo can also be set from within the app (FEATURES 20 and 15)

bull Register and connect OVMS to a server (as guided within the OVMS setup)

bull Turn the ignition in the car on and off to receive initial values (also needed after updates)

bull Install the OVMS app on your smartphone or tablet and configure it to connect to the server

240 Chapter 29 VW e-Up via Comfort CAN (T26A)

Open Vehicles

bull Enjoy -)

294 Climate control

Climate control works as long as write access to the comfort can has been enabled in the app or in the OVMSwebinterface (VW e-Up -gt Features)

To turn on or off the AC from within the Android app just press the ldquoACrdquo button Within the iOS app press ldquoHomelink1rdquo for AC on and ldquoHomelink 2rdquo for AC off

Once the AC is turned on by the app there will be a delay of about 17 seconds untill the AC actually starts in the carFurther 10 seconds all communication from the app to the car is blocked

The communication from the app to the car is also blocked for 10 seconds after the ldquoAC offrdquo command from the appto the car There is no delay between the ldquoAC offrdquo signal of the app and the actually turning off in the car

In rare cases lsquoAC offrsquo does not respond There will be a delay of 40 seconds before you can try again

The cabin target temperature can be set from the OVMS webinterface (VW e-Up (Komfort CAN) -gt Climate control)or via the app under FEATURES 21

294 Climate control 241

Open Vehicles

295 IDs on Comfort CAN Bus

ID Conversion Unit Function61A d72 State of Charge (relative)320 (d4ltlt8+d3-1)190 kmh Speed65F 3 Msg d5-7d1-7d1-7 String VIN number571 5+(05d0) Volt 12 Volt battery voltage65D d3ampfltlt12|d2ltlt8|d1 km Odometer3E3 (d2-100)2 degC Cabin temperature527 (d52)-50 degC Outdoor temperature531 d0 00 Headlights off52D d0 +255 if d1 41 km Calculated range381 d0 02 Status doors locked470 d1 12482010 Integer Doors trunk hood opened or closed3E1 d4 Integer Blower speed(57667D98BBDEFA)575 d0 00 to 0F Integer Key position575 d3 00 or 10 windshield heater (off or on)569 b07 ldquoACrdquo-LED69C d110+10 degC temperature setpoint for remote AC (only in message D2 ltd1gt 00 1E 1E

0A 00 00)61C d2 lt 07 bool Charging detection43D d1 01 or 11 TX Working or sleeping in the ring5A7 d1 16 TX OCU AC blocking signal5A9 all 00 TX OCU heartbeat69E multiple msg d0 C1 d6

xxdegC TX AC on off signals TX set cabin temperature for 69C

242 Chapter 29 VW e-Up via Comfort CAN (T26A)

Open Vehicles

296 Development notes

Under this vehicle component part we use the original T26A approach which can write to the comfort can and is ableto manage the climate control of the car

You will normally use the OVMS binaries provided ie here

The VWUP T26A component part with working climate control is publicly available within the OVMS binary version3215 lsquoedgersquo and upwards (lsquomainrsquo lsquoeaprsquo and lsquoedgersquo) The Android app version has to be 3171 or higher to haveaccess to the climate control functions for this vehicle component

If you want to compile the binary yourself you will need to read the OVMS development documentation on how to setup the tool chain check out the repository and the submodules and copy the file

sdkconfigdefaulthw31

from the OVMSV3support folder to the OVMSV3 folder and rename it to

sdkconfig

297 Vehicle log files

To be able to implement the VWUP vehicle component for OVMS the CAN logging of the VW e-UP provided bylsquosharkcowrsquo was of tremendous help

The implementation of this vehicle component could not have been done without these great files

They can be found here

httpsgithubcomsharkcowVW-e-UP-OBD-CAN-logs

296 Development notes 243

Open Vehicles

244 Chapter 29 VW e-Up via Comfort CAN (T26A)

CHAPTER 30

Command Line Interpreter

The command line interpreter or command parser presented by the OVMS async serial console is constructed as a treeof command word tokens Enter a single question mark followed by RETURN to get the root command list like this

OVMS Run a scriptbms BMS frameworkboot BOOT frameworkcan CAN framework

A root command may be followed by one of a list of additional tokens called subcommands which in turn may befollowed by further subcommands down multiple levels forming a tree The command and subcommand tokens maybe followed by parameters Use question mark at any level in the command sequence to get the list of subcommandsapplicable at that point If the next item to be entered is a parameter rather than a subcommand then a usage mes-sage will be displayed to indicate the required or optional parameters The usage message will also be shown if thecommand as entered is not valid The usage message is described in further detail below

Command tokens can be abbreviated so long as enough characters are entered to uniquely identify the command Op-tionally pressing TAB at that point will auto-complete the token If the abbreviated form is not sufficient to be unique(in particular if no characters have been entered yet) then TAB will show a concise list of the possible subcommandsand retype the portion of the command line already entered so it can be completed Pressing TAB is legal at any pointin the command if there is nothing more that can be completed automatically then there will just be no response tothe TAB

301 OvmsCommand API

Each command word token in the tree is represented by an OvmsCommand object TheOvmsCommandRegisterCommand() function is used to create and add a command or subcommand to-ken object into the tree returning an OvmsCommand pointer to the new object New commands are added to theroot of the tree using the global MyCommandAppRegisterCommand() Subcommands are added as childrenof a command by calling RegisterCommand() using the OvmsCommand pointer to the parent object thusbuilding the tree For example

245

Open Vehicles

OvmsCommand cmd_wifi = MyCommandAppRegisterCommand(wifiWIFI framework wifi_rarr˓status)cmd_wifi-gtRegisterCommand(statusShow wifi statuswifi_status)cmd_wifi-gtRegisterCommand(reconnectReconnect wifi clientwifi_reconnect)

The RegisterCommand() function takes the following arguments

bull const char name ndash the command token

bull const char title ndash one-line description for the command list

bull void (execute)() ndash does the work of the command

bull const char usage ndash parameter description for ldquoUsagerdquo message

bull int min ndash minimum number of parameters allowed

bull int max ndash maximum number of parameters allowed

bull bool secure ndash true for commands permitted only after enable

bull int (validate)() ndash validates parameters as explained later

The RegisterCommand() function tolerates duplicate registrations of the same name at the same node of the treeby assuming that the other arguments are also the same and returning the existing object This allows mulitple modulesthat can be configured independently to share the same top-level command For example the obdii command is sharedby the vehicle and obd2ecu modules

Modules that can be dynamically loaded and unloaded must remove their commands from the tree usingUnregisterCommand(const char name) before unloading

Itrsquos important to note that many of the arguments to RegisterCommand() can and should be defaulted The defaultvalues are as follows

execute = NULLusage = min = 0max = 0secure = truevalidate = NULL

For example for secure non-terminal commands (those with child subcommands) such as the top-level frameworkcommands like bms in the list of root commands shown earlier the model should simply be

RegisterCommand(name Title)

For secure terminal subcommands (those with no children) that donrsquot require any additional parameters the modelshould be

RegisterCommand(name Title execute)

This model also applies if the command has children but the command itself wants to execute a default operation if nosubcommand is specified It is incorrect to specify min = 0 max = 1 to indicate an optional subcommand that isindicated by the presence of the execute function along with a non-empty array of child subcommands

Any command with required or optional parameters should provide a ldquousagerdquo string hinting about the parameters inaddition to specifying the minimum and maximum number of parameters allowed

RegisterCommand(name Title execute usage min max)

246 Chapter 30 Command Line Interpreter

Open Vehicles

The usage argument only needs to describe the parameters that follow this (sub)command because the full usagemessage is dynamically generated The message begins with the text ldquoUsage rdquo followed by the names of the ancestorsof this subcommand back to the root of the tree plus the name of this subcommand itself That is the message startswith all the tokens entered to this point The message continues with a description of subcommands andor parametersthat may be entered next as specified by the usage string

Note The usage message is not resricted to a single line the usage string can include additional lines of explana-tory text separated by n (newline) characters to help convey the meaning of the paramters and the purpose of thecommand

The usage string syntax conventions for specifying alternative and optional parameters are similar to those of usagemessages in Unix-like systems The string can also include special codes to direct the dynamic generation of themessage

bull $C expands to the list of children commands as child1|child2|child3

bull [$C] expands to list optional children as [child1|child2|child3]

bull $G$ expands to the usage string of the first child this would typically used after $C so the usage message showsthe list of children and then the parameters or next-level subcommands that can follow the children This isuseful when the usage string is the same for all or most of the children as in this example

Usage power adc|can1|can2|can3|egpio|esp32|sdcard|simcom|spi|wifirarr˓deepsleep|devel|off|on|sleep|status

bull $Gfoo$ expands to the usage of the child named ldquofoordquo this variant would be used when not all the childrenhave the same usage but it would still be helpful to show the usage of one thatrsquos not first

bull $L lists a full usage message for each of the children on separate lines This provides more help than justshowing the list of children but at the expense of longer output

For subcommands that take parameters the usage string contains explicit text to list the parameters

bull Parameter names or descriptions are enclosed in angle brackets to distinguish the them from command tokensfor example ltmetricgt ltvaluegt Since the angle brackets demarcate each parameter spaces may be in-cluded in the description

bull Parameters that are optional are further enclosed in square brackets like ltidgt ltnamegt [ltvaluegt]

bull When there are alternative forms or meanings for a parameter the alternatives are separated by vertical bar asin lttask names or idsgt||= which indicates that the parameter can be either of the characters or =instead of a list of task names or ids A variant form encloses the alternatives in curly braces as in ltparamgtltinstancegt |

bull One or more additional lines of explanatory text can be included like this

ltidgtnUse ID from connection list 0 to close all

For non-terminal commands (those with children subcommands) the usage argument can be omitted because thedefault value of is interpreted as $C For commands that have children subcommands that are optional (because anexecute function is included) the default usage argument is interpreted as [$C]

3011 Execute Function

The execute function performs whatever work is required for the command Its signature is as follows

301 OvmsCommand API 247

Open Vehicles

void (execute)(int verbosity OvmsWriter writer OvmsCommand cmd int argc constrarr˓char const argv)

bull int verbosity ndash tells how much output is appropriate (eg shell vs SMS)

bull OvmsWriter writer ndash object to which output is delivered eg console

bull OvmsCommand cmd ndash the command that held the execute function pointer

bull int argc ndash how many parameters are being supplied to the function

bull const char const argv ndash the parameter list

Any output appropriate for the command is accomplished through puts() or printf() calls on the writerobject The cmd pointer may allow sharing one execute function among multiple related command objects andprovides access to members of the command object such as GetName()

The argc count will be constrained to the min and max values specified for the cmd object so if the minimum andmaximum are the same then the execute function does not need to check However if parameters are expected thentheir values must be validated

3012 Validate Function

Most commands do not need to specify a validate function It supports extensions of the original command parserdesign for two use cases

1 For commands that store the possible values of a parameter in a NameMapltTgt or CNameMapltTgt thevalidate function enables TAB auto-completion when entering that parameter

2 The original design only allowed parameters to be collected by the terminal subcommand That forced anunnatural word order for some commands The validate function enables non-terminal subcommands totake one or more parameters followed by multiple levels of children subcommands The parameters may bestrings looked up in a NameMapltTgt or CNameMapltTgt or they could be something else like a number that canbe validated by value The validate function must indicate success for parsing to continue to the childrensubcommands The return value is the number of parameters validated if successful or -1 if not

The signature of the validate function is as follows

int (validate)(OvmsWriter writer OvmsCommand cmd int argc const char constrarr˓argv bool complete)

bull OvmsWriter writer ndash object to which output is delivered eg console

bull OvmsCommand cmd ndash the command that held the validate function pointer

bull int argc ndash how many parameters are being supplied to the function

bull const char const argv ndash the parameter list

bull bool complete ndash true for TAB completion of the last parameter (case 1) false when validating intermediateparameters before calling execute on the terminal descendant command (case 2)

The writer and cmd arguments are the same as for the execute function The argc count is never more than maxand if complete is false never less than min However when complete is true to request TAB auto-completionand max is greater than 1 argc will be at least 1 but may be less than min because it indicates how many parametershave been entered so far The TAB auto-completion is performed on the last parameter entered after validating anypreceding parameters If min and max are both 1 then it is not necessary to check argc

If the acceptable values of a parameter are stored in a NameMapltTgt or CNameMapltTgt those maps implement aValidate() function that will perform the validation needed for the validate function covering both the true

248 Chapter 30 Command Line Interpreter

Open Vehicles

and false cases of complete Those maps also implement a FindUniquePrefix() function that may be used tovalidate preceding parameters for commands that take multiple parameters

The config_validate() function for the config command in mainovms_configcpp is an example imple-mentation of use case 1 for a command taking three parameters with TAB auto-completion on the first two

int config_validate(OvmsWriter writer OvmsCommand cmd int argc const charrarr˓const argv bool complete)if (MyConfigismounted())return -1

argv[0] is the ltparamgtif (argc == 1)return MyConfigm_mapValidate(writer argc argv[0] complete)

argv[1] is the ltinstancegtif (argc == 2)OvmsConfigParam const p = MyConfigm_mapFindUniquePrefix(argv[0])if (p) ltparamgt was not valid so cant check ltinstancegtreturn -1

return (p)-gtm_mapValidate(writer argc argv[1] complete)

argv[2] is the value which we cant validatereturn -1

The location command in componentsovms_locationsrcovms_locationcpp is an example of usecase 2 as it includes an intermediate parameter and also utilizes the $L form of the usage string

OVMS location action enter Usage location action enter ltlocationgt acc ltprofilegtUsage location action enter ltlocationgt homelink 1|2|3Usage location action enter ltlocationgt notify lttextgt

The following excerpt shows the implementation of the location_validate() function and a subset of theRegisterCommand() calls to build the command subtree This example shows how simple the validation codecan be ndash sometimes just one line to call Validate() In this case the code does need to check argc because thefunction is shared by multiple subcommand objects taking 1 or 2 parameters

int location_validate(OvmsWriter writer OvmsCommand cmd int argc const charrarr˓const argv bool complete)if (argc == 1)return MyLocationsm_locationsValidate(writer argc argv[0] complete)

return -1

OvmsCommand cmd_location = MyCommandAppRegisterCommand(locationLOCATIONrarr˓framework)OvmsCommand cmd_action = cmd_location-gtRegisterCommand(actionSet an action for

rarr˓a location)OvmsCommand cmd_enter = cmd_action-gtRegisterCommand(enterSet an action upon

rarr˓entering a location NULL ltlocationgt $L 1 1 true location_validate)OvmsCommand enter_homelink = cmd_enter-gtRegisterCommand(homelinkTransmit

rarr˓Homelink signal)enter_homelink-gtRegisterCommand(1Homelink 1 signallocation_homelink 0 0

rarr˓true)enter_homelink-gtRegisterCommand(2Homelink 2 signallocation_homelink 0 0

rarr˓true) (continues on next page)

301 OvmsCommand API 249

Open Vehicles

(continued from previous page)

enter_homelink-gtRegisterCommand(3Homelink 3 signallocation_homelink 0 0rarr˓true)cmd_enter-gtRegisterCommand(accACC profilelocation_accltprofilegt 1 1

rarr˓true)cmd_enter-gtRegisterCommand(notifyText notificationlocation_notifylttextgt 1

rarr˓ INT_MAX true)

250 Chapter 30 Command Line Interpreter

CHAPTER 31

CAN Bus Data Logging

OVMS can be used as CAN bus datalogging tool

311 Physical Connections

OVMS hardware V3 supports up to three CAN bus connections The connections to OVMS are as follows

DB9-F Signal----- ------

2 CAN1-L7 CAN1-H

4 CAN2-L5 CAN2-H

6 CAN3-L8 CAN3-H

Note the board schematics refer to CAN012 These correspond to CAN123 here in the documentation and sourcecode The first is handled by ESP32 io lines directly and CAN23 are handled by MCP2515 ICs via SPI from theESP

CAN1 is the fastest bus use this one if possible The CAN logging tool is able to log all buses at the same time to thesame file or stream

Vehicle CAN bus(s) are usually accesable via the vehiclersquos OBD2 port Most modern cars have multiple CAN bussesThe OBD2 lsquostandardrsquo CAN will be available on OBD2 pin 6 CAN-H and pin 14 CAN-L However modern vehicles(especially EVrsquos) often have other CAN buses available on non-standard OBD2 pins

A voltmeter (ideally oscilloscope) can be used to determine which OBD2 pins contain CAN data

bull Can high pins should normally be between 25 and 35 volts (to ground) - maybe 27 to 33 volts if there istraffic

bull Can low pins should normally be between 15 and 25 volts (to ground) - maybe 17 to 23 volts if there is traffic

251

Open Vehicles

Pre-fabricated OBD2 gt DB9-F for several specific vehicles can be purchased via OpenVehicles

312 Enable OVMS CAN bus

Once physical connections has been made and OVMS is up and running connect to OVMS shell via web browser SSH or serial

If a specific vehicle module is loaded the CAN bus will already be enabled in OVMS To check which CAN buses areenabled use

OVMS can list

If no vehicle module is selected the CAN bus must be started eg

OVMS can can1 start listen 500000

This will enable CAN1 in listen mode (read only) at 500k baud active can be used instead of listen to enableread-write mode To stop a CAN1 bus

OVMS can can1 stop

OVMS supports the following CAN bauds rates 100000 125000 250000 500000 1000000

313 Logging to SD card

It is possible to view CAN data directly in OVMS monitor shell however since modern cars have very busy CANbuses there is often too much data which swamps the monitor or exceeds the logging queue resulting in droppedmessages Logging to SD card is the better option

If using a good quality SD card with a current OVMS V3 module (ie PCB revision 32 20190523 or later) increasethe SD card speed for best performance with

config set sdcard maxfreqkhz 20000

Start logging all CAN messages using CRTD log file format with

ovms can log start vfs crtd sdcancrtd

or log specific CAN packets by applying a filter eg 0x55b the Nissan LEAF SoC CAN message

ovms can log start vfs crtd sdcancrtd 55b

Other CAN log file formats are supported eg crtd gvret-a gvret-b lawricel pcap raw

Check CAN logging satus with

ovms can log status

To Stop CAN logging

ovms can log stop

Note the can logging must be stopped before the file can be viewed

To View the CAN log

ovms vfs head sdcancrtd

tail and cat commands can also be used However be careful the log file can quickly become very large cat mayoverwhelm the shell

The log file can also be viewed in a browser with httpltovms-ipaddressgtsdcancrtd

252 Chapter 31 CAN Bus Data Logging

Open Vehicles

The logfiles can then be imported into a tool like SavvyCan for analysis

314 Network Streaming

CAN data can be streamed directly to SavvyCan (or other compatible application) using the OVMS tcpserver CANlogging feature over a local network Start tcpserver CAN logging with

OVMS can log start tcpserver discard gvret-b 23

This will start a tcpserver on port 23 (as required by SavvyCan) using the GVRET format supported by SavvyCAN

Once OVMS CAN logging tcpserver is running open up SavvyCan and select

Connection gt Add New Device Connection gt Network Connection

then enter the OVMS WiFi local network IP address (no port number required) CAN packets should now appearstreaming into SavvyCan

Note CAN tcpserver network streaming is a beta feture currently in edge firmware and may be buggy

315 Optimizing the Performance

On can log stop the system will output some statistics Check especially the dropped frame count Framedrops can occur because the system was busy with other tasks like handling network traffic There are two options tooptimize this

a) Reduce background activities ie stop all services not needed for the logging If possible do the loggingwithout an active vehicle module (eg set the ldquoemptyrdquo vehicle via vehicle module NONE)

b) Raise the log queue size The default queue size has a capacity of 100 frames To eg allow 200 frames doconfig set can logqueuesize 200

314 Network Streaming 253

Open Vehicles

254 Chapter 31 CAN Bus Data Logging

CHAPTER 32

CRTD CAN Log Format

321 Introduction

The CRTD CAN Log format is a textual log file format designed to store information on CAN bus frames and eventsIt was introduced as a human readable file format capable of supporting data dumps from multiple CAN buses

Files or network data streams in CRTD format contain only textual data in UTF-8 with each record being on anindividual line terminated by a single linefeed (ascii 10) character or CRLF (ascii 13 ascii 10)

Each line is made up from the following fields separated by single spaces (ASCII 32)

bull Timestamp Julian timestamp seconds and millisecondsmicroseconds separated by a decimal point

bull Record Type Mnenomic to denote the record type

bull Record Data The remaining data is dependant on the record type

Here are some examples

1542473901020305 1R11 1542473901020305 2T11 1542473901020305 R11 1542473901021 1R11

322 History

bull 10 Initial version supporting CXX R11 R29 T11 and T29 messages only

bull 20 Add optional bus ID prefix to record types

bull 30 Add support for comment commands and clarify documentation inconsistencies

255

Open Vehicles

323 Specification

CRTD files are UTF-8 text files using LF or CR+LF line termination to separate each record

ltcrtd-filegt = ltcrtd-recordgt [CR] LF

The records are formatted as follows

ltcrtd-recordgt = lttimestampgt ltspacegt ltcrtd-typegt lttimestampgt = ltjuliansecondsgt [ ltmillisecondsgt| ltmicrosecondsgt ] ltjuliansecondsgt = ltdigtigt ltdigitgt ltmillisecondsgt = ltdigitgt ltdigitgt ltdigitgtltmicrosecondsgt = ltdigitgt ltdigitgt ltdigitgt ltdigitgt ltdigitgt ltdigitgt ltdigitgt = [ 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |8 | 9 ] lthexdigitgt = [ ltdigitgt

A | B | C | D | E | F | a | b | c | d | e | f ]

ltspacegt = ASCII character 32 decimal (0x20 hex)

ltcrtd-typegt = [ ltcrtd-commentgt | ltcrtd-transmitgt | ltcrtd-receivegt ]

ltcrtd-commentgt = CXX ltspacegt lttextual-commentgt

ltcrtd-receivegt = R11 ltspacegt ltrxtx-datagt

ltbusgtR11 ltspacegt ltrxtx-datagtR29 ltspacegt ltrxtx-datagtltbusgtR29 ltspacegt ltrxtx-datagt

ltcrtd-transmitgt = T11 ltspacegt ltrxtx-datagt

ltbusgtT11 ltspacegt ltrxtx-datagtT29 ltspacegt ltrxtx-datagtltbusgtT29 ltspacegt ltrxtx-datagt

ltbusgt = ltdigitgt ltdigitgt

ltrxtx-datagt = ltcan-idgt ltspacegt ltcan-bytegt ltcan-idgt = lthexdigitgt lthexdigitgt ] ltcan-bytegt =lthexdigitgt [ lthexdigitgt ]

324 Timestamps

Timestamps can be provided in either millisecond or microsecond precision It is recommended that they be based onthe julian seconds in UTC but there is no specific requirement for that It is suggested that a comment may optionallybe placed at the start of the file to describe the timezone The timestamps should however increase monotonically inthe file (ie time flows forward with subsequent records)

If the timestamp contains 3 digits after the decimal point it should be consider millisecond precision and handledappropriately Similarly if the timestamp contains 6 digits after the decimal point it should be considered microsecondprecision

325 Case Independence

CAN IDs and data bytes are in case-independent hex and may or may not be padded with leading zeros CRTDprocessors should be as flexible as possible in their handling of this

256 Chapter 32 CRTD CAN Log Format

Open Vehicles

326 CAN Bus Designation

Record types may optionally be prefixed by the CAN bus number (1 n) If no bus number is provided 1 shouldbe assumed

327 Data bytes

The number of data bytes is limited by the CAN specification to a maximum of 8 bytes Similarly the range ofacceptable CAN IDs is limited by the 11bit 29bit encoding in the CAN protocol specification

328 Record Types

Each record can be one of a comment receive or transmit data Other record types should be discarded to allow newrecord types to be introduced without breaking existing processors

3281 Comment Records

Comment records start with the letter lsquoCrsquo and the record type has two characters following to denote the sub-typeThe rest of the record is to be considered a comment (or data for the command)

The following comment record types are defined

bull CXX General textual comment

bull CER An indication of a (usually recoverable) error

bull CST Periodical statistics

bull CEV An indication of an event

bull CVR Version of CRTD protocol adhered to (with version number as text comment)

and the following command record types are defined

bull CBC A command to configure a CAN bus

bull CDP A command to pause the transmission of messages

bull CDR A command to resume the transmission of messages

bull CFC A command to clear all filters for this connection

bull CFA A command to add a filter for this connection

Here are some examples

169971289 CXX Info Typecrtd Pathsdcan3crtd Filter30-ffffffffrarr˓VehicleTSHK19292299819 CEV vehiclealert this is a textual vehicle alert198923283738 CST intr=0 rxpkt=0 txpkt=0 errflags=0 rxerr=0 txerr=0 rxovr=0 txovr=0rarr˓txdelay=0 wdgreset=02783384726 CER intr=0 rxpkt=0 txpkt=0 errflags=0 rxerr=0 txerr=0 rxovr=0 txovr=0rarr˓txdelay=0 wdgreset=0

326 CAN Bus Designation 257

Open Vehicles

3282 Command Record CBC - Configure a CAN bus

The CBC command is used to configure a CAN bus It should be prefixed with the bus ID in the usual way or defaultto bus 1 if not defined

The command should have the following space separated parameters

bull mode either L for listen or A for active

bull speed the baud rate of the CAN bus

3283 Command Record CDP - Pause transmission

The CDP command is used to pause transmission of messages for this connection Upon receiving this commandthe device producing CRTD logs should henceforth discard those logs and not transmit them to this connection untilresumed

3284 Command Record CDR - Resume transmission

The CDR command is used to resume transmission of messages for this connection It clears the condition previouslyset by the CDP command

3285 Command Record CFC - Clear filters

The CFC command is used to clear the message filters for this connection

By default connections receive all messages for all CAN buses and that is indicated by the filter list being initiallyempty This command resets the filters to this default condition

Note that external to the per-message filters CAN data sources may also have incoming filters that apply to all incom-ing data (regardless of the logging destination) These incoming filters are not affected by this

3286 Command Record CFA - Add a filter

The CFA command is used to add a filter to the list of message filters for this connection If one or more filters aredefined only messages matching those filters will be forwarded

The command should have the filter passed as a single parameter

bull filter the filter to add

Filters are formatted as

Filter = ltbusgt | ltidgt[-ltidgt] | ltbusgtltidgt[-ltidgt]

For example

bull 22a0-37f for bus 2 IDs 0x2a0 - 0x37f

bull 10-37f for bus 1 IDs 0x000 - 0x37f

bull 3 for bus 3 all messages

bull 100-200 for bus 1 IDs 0x100 - 0x200

258 Chapter 32 CRTD CAN Log Format

Open Vehicles

3287 Received Frame Record

Received frame records describe a frame received from the CAN bus and start with the letter lsquoRrsquo Two types aredefined

bull R11 A standard 11bit ID CAN frame

bull R29 An extended 29bit ID CAN frame

The record type is followed by the frame ID (in hexadecimal) and then up to 8 bytes of CAN frame data

Here are some examples

1542473901020305 1R11 213 00 00 00 00 c0 01 00 001542473901020970 2R11 318 92 0b 13 10 11 3a 00 001542473901021259 2R11 308 00 ff f6 a6 06 03 80 001542473901021560 2R11 408 001542473901030341 1R11 358 18 08 20 00 00 00 00 201542473901034872 2R11 418 801542473901035514 1R11 408 101542473901036694 3R11 41C 101542473901040289 R11 428 00 301542473901042516 2R11 168 e0 7f 70 00 ff ff ff1542473901042809 2R11 27E c0 c0 c0 c0 00 00 00 001542473901043073 1R11 248 29 29 0f bc 01 10 00

3288 Transmitted Frame Record

Transmitted frame records describe a frame transmitted onto the CAN bus and start with the letter lsquoTrsquo Two types aredefined

bull T11 A standard 11bit ID CAN frame

bull T29 An extended 29bit ID CAN frame

The record type is followed by the frame ID (in hexadecimal) and then up to 8 bytes of CAN frame data

Here are some examples

1542473901020305 1T11 213 00 00 00 00 c0 01 00 001542473901020970 2T11 318 92 0b 13 10 11 3a 00 001542473901021259 2T11 308 00 ff f6 a6 06 03 80 001542473901021560 2T11 408 001542473901030341 1T11 358 18 08 20 00 00 00 00 201542473901034872 2T11 418 801542473901035514 1T11 408 101542473901036694 3T11 41C 101542473901040289 T11 428 00 301542473901042516 2T11 168 e0 7f 70 00 ff ff ff1542473901042809 2T11 27E c0 c0 c0 c0 00 00 00 001542473901043073 1T11 248 29 29 0f bc 01 10 00

329 Conclusions

The CRTD format is intended to be very simple to process either by automated code or humans manually It can beloaded into text editors for manipulation (search replace etc) and easily processed by command line tools such aslsquocutrsquo lsquogreprsquo lsquoawkrsquo etc

329 Conclusions 259

Open Vehicles

260 Chapter 32 CRTD CAN Log Format

CHAPTER 33

Web Framework amp Plugins

331 TLDR Examples

The following examples include their documentation in the HTML page and source Read the source and install themas plugins (see below) to see how they work

3311 Metric Displays

OVMS V3 is based on metrics Metrics can be single numerical or textual values or complex values like sets and arraysThe web framework keeps all metrics in a global object which can be read simply by eg metrics[vbsoc]

Metrics updates (as well as other updates) are sent to all DOM elements having the receiver class To hook intothese updates simply add an event listener for msgmetrics

Listening to the event is not necessary though if all you need is some metrics display This is covered by the metricwidget class family as shown here

261

Open Vehicles

Single Values amp Charts

The following example covers

bull Text (String) displays

bull Number displays

bull Progress bars (horizontal light weight bar charts)

bull Gauges

bull Charts

Gauges amp charts use the HighCharts library which is included in the web server The other widgets are simple standardBootstrap widgets extended by an automatic metrics value update mechanism

Highcharts is a highly versatile charting system For inspiration have a look at

bull httpswwwhighchartscomdemo

bull httpswwwhighchartscomdocs

Wersquore using styled mode so some options donrsquot apply but everything can be styled by standard CSS

Install the example as a web page plugin

metricshtm (hint right click save as)

262 Chapter 33 Web Framework amp Plugins

Open Vehicles

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltdiv class=panel panel-primarygt6 ltdiv class=panel-headinggtMetrics Displays TestDemoltdivgt7 ltdiv class=panel-bodygt8

9 ltpgtOVMS V3 is based on metrics Metrics can be single numerical or textual valuesrarr˓or complex values

10 like sets and arrays The web framework keeps all metrics in a global objectrarr˓which can be read

11 simply by eg ltcodegtmetrics[vbsoc]ltcodegtltpgt12

13 ltpgtMetrics updates (as well as other updates) are sent to all DOM elements havingrarr˓the

14 ltcodegtreceiverltcodegt class To hook into these updates simply add an eventrarr˓listener for

15 ltcodegtmsgmetricsltcodegt Listening to the event is not necessary if all yourarr˓need is some metrics

16 display This is covered by the ltcodegtmetricltcodegt class family as shown hererarr˓ltpgt

17

18 ltpgt19 ltbutton type=button class=btn btn-default action-gendatagtGenerate random

rarr˓dataltbuttongt20 ltbutton type=button class=btn btn-default action-showsrcgtShow page sourcelt

rarr˓buttongt21 ltpgt22

23 lthrgt24

25 ltdiv class=receivergt26

27 lth4gtBasic usagelth4gt28

29 ltpgtAll elements of class ltcodegtmetricltcodegt in a ltcodegtreceiverltcodegt arerarr˓checked for the

30 ltcodegtdata-metricltcodegt attribute If no specific metric class is given therarr˓metric value

31 is simply set as the element text ltspan class=metric data-metric=mnetrarr˓providergtltspangt

32 is your current network providerltpgt33

34 lth4gtText ampamp Numberlth4gt35

36 ltpgtltcodegtnumberltcodegt ampamp ltcodegttextltcodegt displays get the metric valuerarr˓set in their child of

37 class ltcodegtvalueltcodegt They may additionally have labels and units ltcodegtrarr˓data-precltcodegt can

38 be used on ltcodegtnumberltcodegt to set the precision ltcodegtdata-scaleltcodegtrarr˓to scale the raw

39 values by a factor They have fixed min widths and float by default so yourarr˓can simply put

40 multiple displays into the same containerltpgt41

42 ltdiv class=clearfixgt

(continues on next page)

331 TLDR Examples 263

Open Vehicles

(continued from previous page)

43 ltdiv class=metric number data-metric=vethrottle data-prec=0gt44 ltspan class=labelgtThrottleltspangt45 ltspan class=valuegtltspangt46 ltspan class=unitgtltspangt47 ltdivgt48 ltdiv class=metric number data-metric=vb12vvoltageref data-prec=1gt49 ltspan class=valuegtltspangt50 ltspan class=unitgtVltsubgtrefltsubgtltspangt51 ltdivgt52 ltdiv class=metric text data-metric=mnetprovidergt53 ltspan class=labelgtNetworkltspangt54 ltspan class=valuegtltspangt55 ltdivgt56 ltdivgt57

58 lth4gtProgress Barlth4gt59

60 ltpgtBootstrap ltcodegtprogressltcodegt bars can be used as lightweight graphicalrarr˓indicators

61 Labels and units are available also ltcodegtdata-precltcodegt and ltcodegtdata-rarr˓scaleltcodegt

62 Again all you need is a bit of markupltpgt63

64 ltdiv class=clearfixgt65 ltdiv class=metric progress data-metric=vethrottle data-prec=0gt66 ltdiv class=progress-bar progress-bar-success value-low text-left role=

rarr˓progressbar67 aria-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gt68 ltdivgt69 ltspan class=labelgtThrottleltspangt70 ltspan class=valuegtltspangt71 ltspan class=unitgtltspangt72 ltdivgt73 ltdivgt74 ltdivgt75 ltdiv class=metric progress data-metric=vb12vvoltageref data-prec=1gt76 ltdiv class=progress-bar progress-bar-info value-low text-left role=

rarr˓progressbar77 aria-valuenow=0 aria-valuemin=5 aria-valuemax=15 style=width0gt78 ltdivgt79 ltspan class=labelgt12V refltspangt80 ltspan class=valuegtltspangt81 ltspan class=unitgtVltspangt82 ltdivgt83 ltdivgt84 ltdivgt85 ltdivgt86

87 lth4gtGauges ampamp Chartslth4gt88

89 ltpgtThe OVMS web framework has builtin support for the highly versatile ltbgtrarr˓Highcharts libraryltbgt

90 with loads of chart types and options ltcodegtchartltcodegt metric examplesltpgt91

92 ltdiv class=rowgt93 ltdiv class=col-sm-6gt94 ltdiv class=metric chart data-metric=vethrottle style=height220pxgt

(continues on next page)

264 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

95 ltdiv class=chart-box gaugechart id=throttle-gaugegt96 ltdivgt97 ltdivgt98 ltdiv class=col-sm-6gt99 ltdiv class=metric chart data-metric=vbcvoltagevbcvoltagemin

rarr˓style=height220pxgt100 ltdiv class=chart-box barchart id=cell-voltagesgt101 ltdivgt102 ltdivgt103 ltdivgt104

105 ltpgtltbutton type=button class=btn btn-default action-gendatagtGenerate randomrarr˓dataltbuttongtltpgt

106

107 ltpgtFor charts a little bit of scripting is necessary108 The scripts for these charts contain the chart configuration part of which

rarr˓is the update109 function you need to define The update function translates metrics data into

rarr˓chart data110 This is trivial for single values like the throttle the cell voltage chart

rarr˓is an example111 on basic array processingltpgt112

113 ltpgtAlso while charts ltemgtcanltemgt be defined with few options youll ltemgtloverarr˓ltemgt to explore

114 all the features and fine tuning options provided by Highcharts Forrarr˓inspiration

115 have a look at the lta target=_blank href=httpswwwhighchartscomdemogtrarr˓Highcharts demosltagt

116 and the lta target=_blank href=httpswwwhighchartscomdocsgtHighchartsrarr˓documentationltagt

117 Were using lta target=_blank href=httpswwwhighchartscomdocschart-rarr˓design-and-stylestyle-by-cssgt

118 styled modeltagt so some options dont apply but everything can be styled byrarr˓standard CSSltpgt

119

120 ltdivgt121

122 ltdivgt123 ltdivgt124

125 ltscriptgt126 (function()127

128 Get page source before chart rendering 129 var pagesrc = $(main)html()130

131 Init throttle gauge 132 $(throttle-gauge)chart(133 chart 134 type gauge135 spacing [0 0 0 0]136 margin [0 0 0 0]137 animation duration 500 easing easeOutExpo 138 139 title text Throttle verticalAlign middle y 75 140 credits enabled false

(continues on next page)

331 TLDR Examples 265

Open Vehicles

(continued from previous page)

141 tooltip enabled false 142 plotOptions 143 gauge dataLabels enabled false overshoot 1 144 145 pane [146 startAngle -125 endAngle 125 size 100 center [50 60]147 ]148 yAxis [149 title text 150 className throttle151 reversed false152 min 0 max 100153 plotBands [154 from 0 to 60 className green-band 155 from 60 to 80 className yellow-band 156 from 80 to 100 className red-band 157 ]158 minorTickInterval auto minorTickLength 5 minorTickPosition inside159 tickPixelInterval 40 tickPosition inside tickLength 13160 labels step 2 distance -28 x 0 y 5 zIndex 2 161 ]162 series [163 name Throttle data [0]164 className throttle165 animation duration 0 166 pivot radius 10 167 dial radius 88 topWidth 1 baseLength 20 baseWidth 10

rarr˓rearLength 20 168 ]169 Update method 170 onUpdate function(update) 171 Create gauge data set from metric172 var data = [ metrics[vethrottle] ]173 Update chart174 thisseries[0]setData(data)175 176 )177

178 Init cell voltages chart 179 $(cell-voltages)chart(180 chart 181 type column182 animation duration 500 easing easeOutExpo 183 184 title text Cell Voltages 185 credits enabled false 186 tooltip 187 enabled true188 shared true189 headerFormat Cell pointkeyltbrgt190 pointFormat seriesname ltbgtpointyltbgtltbrgt191 valueSuffix V192 193 legend enabled true 194 xAxis 195 categories []196

(continues on next page)

266 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

197 yAxis [198 title text null 199 labels format value2fV 200 tickAmount 4 startOnTick false endOnTick false201 floor 33 ceiling 42202 minorTickInterval auto203 ]204 series [205 name Current data []206 className cell-voltage207 animation duration 0 208 209 name Minimum data []210 className cell-voltage-min211 animation duration 0 212 ]213 Update method 214 onUpdate function(update) 215 Note the update parameter contains the actual update set216 You can use this to reduce chart updates to the actual changes217 For this demo we just use the global metrics object218 var219 m_vlt = metrics[vbcvoltage] || []220 m_min = metrics[vbcvoltagemin] || []221 Create categories (cell numbers) amp rounded values222 var cat = [] val0 = [] val1 = []223 for (var i = 0 i lt m_vltlength i++) 224 catpush(i+1)225 val0push(Number((m_vlt[i]||0)toFixed(3)))226 val1push(Number((m_min[i]||0)toFixed(3)))227 228 Update chart229 thisxAxis[0]setCategories(cat)230 thisseries[0]setData(val0)231 thisseries[1]setData(val1)232 233 )234

235 Test metrics generator 236 $(action-gendata)on(click function() 237 var td = 238 td[mnetprovider] = [hologramVodafoneTelekom][Mathfloor(Math

rarr˓random()3)]239 td[vethrottle] = Mathrandom() 100240 td[vb12vvoltageref] = 10 + Mathrandom() 4241 var m_vlt = [] m_min = []242 for (var i = 1 i lt= 16 i++) 243 m_vltpush(36 + Mathrandom() 05)244 m_minpush(34 + Mathrandom() 02)245 246 td[vbcvoltage] = m_vlt247 td[vbcvoltagemin] = m_min248 $(receiver)trigger(msgmetrics $extend(metrics td))249 )250

251 Display page source 252 $(action-showsrc)on(click function()

(continues on next page)

331 TLDR Examples 267

Open Vehicles

(continued from previous page)

253 $(ltdivgt)dialog(254 title Source Code255 body ltpre style=font-size85 heightcalc(100vh - 230px)gt256 + encode_html(pagesrc) + ltpregt257 size lg258 )259 )260

261 )()262 ltscriptgt

Vector Tables

Some metrics for example the battery cell voltages or the TPMS tyre health data may contain vectors of arbitrarysize Besides rendering into charts these can also be displayed by their textual values in form of a table

The following example shows a live view of the battery cell voltages along with their recorded minimum maximummaximum deviation and current warningalert state Alert states 0-2 are translated into icons

The metric table widget uses the DataTables library which is included in the web server The DataTables Javascriptlibrary offers a wide range of options to create tabular views into datasets

Install the example as a web page plugin

metrics-tablehtm (hint right click save as)

1 lt--2 Web UI page plugin DataTables metrics widget demonstration3 --gt4

5 ltstylegt6 td i

(continues on next page)

268 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

7 font-style normal8 font-size 1409 line-height 90

10 font-weight bold11 12 td iwarning color orange 13 td idanger color red 14 ltstylegt15

16

17 ltdiv class=panel panel-primary panel-single receiver id=my-receivergt18 ltdiv class=panel-headinggtMetrics Table Widget Exampleltdivgt19 ltdiv class=panel-bodygt20

21 ltpgtThe following table shows a live view of the battery cell voltages along withrarr˓their recorded

22 minimum maximum maximum deviation and current warningalert stateltpgt23 ltpgtTry resizing the window or using a mobile phone to see how the table adapts to

rarr˓the screen24 width The table will also keep the selected sorting over data updatesltpgt25 ltpgtHint if you dont have live battery cell data click the generator button to

rarr˓create26 some random values The random data is only generated in your browser not on

rarr˓the moduleltpgt27

28 ltdiv class=metric table29 data-metric=vbcvoltagevbcvoltageminvbcvoltagemaxvbcvoltage

rarr˓devmaxvbcvoltagealertgt30 lttable class=table table-striped table-bordered table-hover id=v-table gt31 ltdivgt32

33 ltpgtSee lta target=_blank href=httpsdatatablesnetmanualgtDataTables manualrarr˓ltagt for all

34 options and API methods availableltpgt35

36 ltdivgt37 ltdiv class=panel-footergt38 ltpgtltbutton type=button class=btn btn-default action-gendatagtGenerate random

rarr˓dataltbuttongtltpgt39 ltdivgt40 ltdivgt41

42

43 ltscriptgt44 (function()45

46 Utilities47 var alertMap = 48 0 49 1 lti class=warninggtltigt50 2 lti class=dangergtltigt51 52

53 function fmtCode(value map) 54 return (map[value] == undefined) map[value] null55 56 function fmtNumber(value prec)

(continues on next page)

331 TLDR Examples 269

Open Vehicles

(continued from previous page)

57 return (value == undefined) Number(value)toFixed(prec) null58 59

60 Init table61 $(v-table)table(62 responsive true63 paging true64 searching false65 info false66 autoWidth false67 columns [68 title className dt-body-center width 6

rarr˓responsivePriority 1 69 title Voltage className dt-body-right width 22

rarr˓responsivePriority 3 70 title Minimum className dt-body-right width 22

rarr˓responsivePriority 4 71 title Maximum className dt-body-right width 22

rarr˓responsivePriority 5 72 title MaxDev className dt-body-right width 22

rarr˓responsivePriority 2 73 title Alert className dt-body-center width 6

rarr˓responsivePriority 1 74 ]75 rowId 076 onUpdate function(update) 77 Get vector metrics to display78 var v = [79 metrics[vbcvoltage] || []80 metrics[vbcvoltagemin] || []81 metrics[vbcvoltagemax] || []82 metrics[vbcvoltagedevmax] || []83 metrics[vbcvoltagealert] || []84 ]85 var lcnt = 086 vmap(el =gt lcnt = Mathmax(lcnt ellength))87 Transpose vectors to columns88 var l d = []89 for (l = 0 l lt lcnt l++) 90 dpush([91 l+192 fmtNumber(v[0][l] 2)93 fmtNumber(v[1][l] 2)94 fmtNumber(v[2][l] 2)95 fmtNumber(v[3][l] 3)96 fmtCode(v[4][l] alertMap)97 ])98 99 Display new data

100 thisclear()rowsadd(d)draw()101 102 )103

104

105 Test data generator106 $(action-gendata)on(click function() 107 var td =

(continues on next page)

270 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

108 var m_vlt = [] m_min = [] m_max = [] m_devmax = [] m_alert = []109 for (var i = 1 i lt= 16 i++) 110 m_vltpush(36 + Mathrandom() 05)111 m_minpush(34 + Mathrandom() 02)112 m_maxpush(38 + Mathrandom() 02)113 m_devmaxpush(-02 + Mathrandom() 04)114 m_alertpush(Mathfloor(Mathrandom() 3))115 116 td[vbcvoltage] = m_vlt117 td[vbcvoltagemin] = m_min118 td[vbcvoltagemax] = m_max119 td[vbcvoltagedevmax] = m_devmax120 td[vbcvoltagealert] = m_alert121 $(receiver)trigger(msgmetrics $extend(metrics td))122 )123

124 )()125 ltscriptgt

3312 Command Buttons amp Monitors

commandshtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltstylegt6 h3 7 margin-top 40px8 margin-bottom 20px9

10 ltstylegt11

12 ltdiv class=panel panel-primarygt13 ltdiv class=panel-headinggtCommands ampamp Monitorsltdivgt14 ltdiv class=panel-bodygt15

16 ltpgtCommand execution is only allowed for an authorized session The command API will17 output Unauthorized and a Login button as necessary The login state is also18 available in the global variable ltcodegtloggedinltcodegt To send the user to the19 login page and return to the current page after login call ltcodegtlogin()ltcodegt

rarr˓ltpgt20

21 ltpgt22 ltbutton type=button class=btn btn-default action-login onclick=login()gtLogin

rarr˓ltbuttongt23 ltbutton type=button class=btn btn-default action-logout onclick=logout()gt

rarr˓Logoutltbuttongt24 ltpgt25

26 ltscriptgt27 $(action-login)prop(disabled loggedin)28 $(action-logout)prop(disabled loggedin)29 ltscriptgt

(continues on next page)

331 TLDR Examples 271

Open Vehicles

(continued from previous page)

30

31

32 lth3gtCommand Execution on Loadlth3gt33

34 ltpgtTo execute a command automatically on page load simply add the ltcodegtmonitorltrarr˓codegt class

35 to an output element set ltcodegtdata-updcmdltcodegt to the command to be executedrarr˓and

36 ltcodegtdata-updcntltcodegt to 1ltpgt37

38 ltpre class=monitor data-updcmd=boot status data-updcnt=1gtFetching bootrarr˓statusltpregt

39

40 ltpgtOutput elements typically are ltcodegtsampltcodegt or ltcodegtpreltcodegt as commands41 normally output formatted plain text but any element can be used ltcodegtsamplt

rarr˓codegt42 by default compresses white space and has no visible area while ltcodegtpreltcodegt43 is visible and preserves all spacingltpgt44

45 ltpgtltcodegtupdcntltcodegt will count down to zero and stop or run indefinitely ifrarr˓started

46 below zero The execution interval can be given in ltcodegtdata-updintltcodegt (inrarr˓seconds)

47 You can set the data attributes any time using jQuery all monitors are checkedrarr˓and

48 updated by the framework once per secondltpgt49

50

51 lth3gtCommand Execution on Eventslth3gt52

53 ltpgtTo automatically trigger a monitor update on OVMS events additionally set the54 ltcodegtdata-eventsltcodegt attribute to a regular expression matching the event(s)

rarr˓of55 interest This example monitor lists the active network channels and automatically56 updates on all server connection eventsltpgt57

58 ltpgtltpre class=monitor59 data-events=server(connect|open|close|stop)60 data-updcmd=network list61 data-updcnt=1gtltpregtltpgt62

63 ltpgt64 Try65 lta class=btn btn-default onclick=windowopen( _blank width=400

rarr˓height=500)gtOpen new windowltagt66 lta class=btn btn-default href= data-cmd=server v2 stopgtStop V2 serverltagt67 lta class=btn btn-default href= data-cmd=server v2 startgtStart V2 serverltagt68 lta class=btn btn-default href= data-cmd=event raise serverfakeopengtSend

rarr˓fake eventltagt69 ltpgt70

71

72 lth3gtCommand Buttonslth3gt73

74 ltpgtA bootstrap button has the base class ltcodegtbtnltcodegt Add the command torarr˓execute

75 as attribute ltcodegtdata-cmdltcodegt and optionally the output element as(continues on next page)

272 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

76 ltcodegtdata-targetltcodegt and youre doneltpgt77

78 ltdiv class=rowgt79

80 ltdiv class=col-sm-6gt81 ltbutton type=button class=btn btn-default data-target=out1 data-cmd=

rarr˓wifi statusgt82 Wifi Status rarr ltcodegtampltsampampgtltcodegt83 ltbuttongt84 ltsamp id=out1 gt85 ltdivgt86

87 ltdiv class=col-sm-6gt88 ltbutton type=button class=btn btn-default data-target=out2 data-cmd=

rarr˓wifi statusgt89 Wifi Status rarr ltcodegtampltpreampgtltcodegt90 ltbuttongt91 ltpre id=out2 gt92 ltdivgt93

94 ltdivgt95

96 ltpgtAdd class ltcodegtsamp-inlineltcodegt or wrap in a ltcodegtullist-inlineltcodegt torarr˓place

97 the output element on the same line with the button Prefix the target with a +rarr˓to

98 append to itltpgt99

100 ltpgt101 External 12V power102 ltbutton type=button class=btn btn-info data-target=+out3 data-cmd=power

rarr˓ext12v ongtonltbuttongt103 ltbutton type=button class=btn btn-info data-target=+out3 data-cmd=power

rarr˓ext12v offgtoffltbuttongt104 ltsamp class=samp-inline id=out3 gt105 ltpgt106

107

108 lth3gtCombining Buttons ampamp Monitorslth3gt109

110 ltpgtBy combination of a button and a monitor you can let the button start a repeated111 execution of a command set ltcodegtdata-watchcntltcodegt on the button to the

rarr˓number of112 repetitions (default 0) and ltcodegtdata-watchintltcodegt to the interval in seconds113 (default 2)ltpgt114

115 ltpgt116 ltbutton type=button class=btn btn-default data-target=out4117 data-cmd=power cellular on data-watchcnt=-1 data-watchint=3gt118 Power on cellular modem ampamp get status updates every 3 seconds119 ltbuttongt120 ltpre class=monitor id=out4 data-updcmd=cellular status gt121 ltpgt122

123 ltpgtNote to stop a monitor set ltcodegtdata-updcntltcodegt to 0124 ltbutton type=button class=btn btn-default onclick=$(out4)data(updcnt

rarr˓0)gt(continues on next page)

331 TLDR Examples 273

Open Vehicles

(continued from previous page)

125 Stop updates126 ltbuttongtltpgt127

128

129 lth3gtExecute Javascriptlth3gt130

131 ltpgtTo execute Javascript code directly (ie without calling ltcodegtscript evalltrarr˓codegt)

132 simply exchange the ltcodegtdata-cmd data-updcmdltcodegt attribute by133 ltcodegtdata-js data-updjsltcodegt Exampleltpgt134

135 ltpgt136 ltbutton type=button class=btn btn-default data-target=out5137 data-js=JSONprint(OvmsConfigGetValues(vehicle))gt138 Show vehicle config139 ltbuttongt140 ltpre id=out5 gt141 ltpgt142

143 ltdivgt144 ltdivgt145

146

147 ltscriptgt148 (function()149 Show page source 150 var pagesrc = $(main)html()151 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +152 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)153 $(action-showsrc)on(click function() 154 $(ltdivgt)dialog(155 title Source Code156 body ltpre style=font-size85 heightcalc(100vh - 230px)gt157 + encode_html(pagesrc) + ltpregt158 size lg159 )160 )161 )()162 ltscriptgt

3313 Notifications

notificationshtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web file path eg sddevnotificationshtm5 - open in framework by eg httptest1localdevnotificationshtm6 --gt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtNotification TestDemoltdivgt

10 ltdiv class=panel-bodygt

(continues on next page)

274 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

11 lth4gtReceiverlth4gt12 lt--13 You can use data-subscriptions to preconfigure subscriptions14 Note types info error and alert get sent to all receivers15 --gt16 ltpre id=log class=receiver data-subscriptions=notifystreammyappgtIm

rarr˓preconfigured to receive notifystreammyappltpregt17 ltdivgt18 ltdiv class=panel-footergt19 ltdivgt20 ltlabel for=topicsgtTest commandltlabelgt21 ltinput type=text class=form-control font-monospace id=cmd value=notify

rarr˓raise text stream myappinput my first streamgt22 ltpgtJSON example ltcode class=autoselectgtnotify raise text stream myappinput

rarr˓myJSON streampi3141fib[1235813]ltcodegtltpgt23 ltbutton type=button class=btn btn-default id=action-execgtExecuteltbuttongt24 ltsamp id=cmdres gt25 ltdivgt26 ltdivgt27 ltlabel for=topicsgtTopic subscription (separate topics by space)ltlabelgt28 ltinput type=text class=form-control font-monospace id=topics value=

rarr˓notifystreammyappgt29 ltbutton type=button class=btn btn-default id=action-subgtSubltbuttongt30 ltbutton type=button class=btn btn-default id=action-unsubgtUnsubltbuttongt31 ltbutton type=button class=btn btn-default id=action-unsuballgtUnsub alllt

rarr˓buttongt32 ltdivgt33 ltdivgt34 ltdivgt35

36 ltscriptgt37

38 Receiver event handling39 $(log)on(msgnotify function(ev msg) 40 You normally should filter by typesubtype here eg41 if (subtypestartsWith(myapp)) 42 msg has type subtype and value43 Dump the msg into the receiver to show the structure44 $(this)text(JSONstringify(msg null 2))45

46 A convenient way to transport complex data is JSON47 To decode a JSON string use JSONparse()48 Note JSONparse() needs strict JSON syntax ie quoted names49 var payload50 try 51 payload = JSONparse(msgvalue)52 if (payload) 53 $(this)append(ltdivgtFound JSON payloadltdivgt)54 append($(ltdiv gt)text(JSONstringify(payload null 2))html())55 consolelog(payload)56 57 catch(e) 58 no JSON59 consolelog(e)60 61 )62

(continues on next page)

331 TLDR Examples 275

Open Vehicles

(continued from previous page)

63 Topic subscription can be done on page load using the data-subscriptions attribute64 andor on demand using the subscribe amp unsubscribe calls65 $(action-sub)on(click function(ev) 66 var topics = $(topics)val()67 $(log)subscribe(topics)text(added + topics)68 )69 The receiver remembers the subscriptions and does an auto unsubscribe on unload70 You can also unsubscribe topics dynamically Your data producer can check for71 active subscriptions using the MyNotifyHasReader() method72 $(action-unsub)on(click function(ev) 73 var topics = $(topics)val()74 $(log)unsubscribe(topics)text(removed + topics)75 )76 $(action-unsuball)on(click function(ev) 77 $(log)unsubscribe()text(removed all subscriptions)78 )79

80 Command handler81 $(action-exec)on(click function(ev) 82 var cmd = $(cmd)val()83 if (cmd) loadcmd(cmd cmdres)84 )85 $(cmd)on(keydown function(ev) 86 if (evwhich == 13) $(action-exec)trigger(click)87 )88

89 ltscriptgt

3314 Hook Plugins

hookshtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 --gt4

5 ltdiv class=panel panel-primarygt6 ltdiv class=panel-headinggtPage Hook Pluginsltdivgt7 ltdiv class=panel-bodygt8

9 ltpgtPlugins can provide pages on their own or extend existing pages To extend anrarr˓existing

10 page the page needs to support this by offering hook pointsltpgt11

12 ltpgtYou are not limited to the hook points for page modifications To insert yourrarr˓extensions

13 at arbitrary placesltpgt14 ltulgt15 ltligtinsert your extensions dynamically or with ltcodegtdisplaynoneltcodegtltligt16 ltligtregister a onetime handler for the ltcodegtloadltcodegt event on ltcodegtmainlt

rarr˓codegtltligt17 ltligtmove your extensions into place and show them from the event handlerltligt18 ltulgt19

20 ltpgtand yes youre also not limited to adding stuffltpgt(continues on next page)

276 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

21

22 lth3gtExamplelth3gt23

24 ltpgtThe following hook plugin adds a custom menu and some color to ltcodegthomeltcodegtrarr˓ltpgt

25

26 ltpre id=plugindisplay style=font-size85gtltpregt27

28 lth3gtAvailable Hookslth3gt29

30 ltpgtas of January 2019 This is work in progress if you miss a hook somewhererarr˓contact usltpgt

31

32 lttable class=table table-condensed font-monospacegt33 lttrgtltth colspan=2gtFrameworkltthgtlttrgt34 lttrgtlttdgt lttdgtlttdgthtmlpre headpost bodypost

rarr˓ lttdgtlttrgt35 lttrgtlttdgthome lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt36 lttrgtlttdgtdashboard lttdgtlttdgtbodypre

rarr˓ lttdgtlttrgt37 lttrgtlttdgtstatus lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt38 lttrgtlttdgtshell lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt39 lttrgtltth colspan=2gtRenault Twizyltthgtlttrgt40 lttrgtlttdgtxrtdrivemode lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt41 lttrgtlttdgtxrtscmon lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt42 lttablegt43

44 ltdivgt45 ltdivgt46

47 ltscriptgt48 (function()49 var pluginsrc = $(pluginsrc)html()50 $(plugindisplay)html(encode_html(pluginsrcsubstr(1)))51 )()52 ltscriptgt53

54 ltdiv id=pluginsrc style=displaynonegt55 lt--56 Hook plugin for homebodypre57 - custom coloring of menu titles58 - add custom menu Test Demo after Main59 --gt60

61 ltstylegt62 menu legend 63 color brown64 65 ltstylegt66

67 ltfieldset class=menu id=fieldset-menu-demo1 style=displaynonegt68 ltlegendgtTest Demoltlegendgt

(continues on next page)

331 TLDR Examples 277

Open Vehicles

(continued from previous page)

69 ltul class=list-inlinegt70 ltligtlta class=btn btn-default href=usrdemometrics target=maingtMetrics lt

rarr˓agtltligt71 ltligtlta class=btn btn-info href=logslog target=_blankgtOpen Log File ltagtlt

rarr˓ligt72 ltulgt73 ltfieldsetgt74

75 ltscriptgt76 $(main)one(load function(ev) 77 $(fieldset-menu-demo1)insertAfter(fieldset-menu-main)show()78 )79 ltscriptgt80 ltdivgt

3315 Solid Gauges

solidgaugehtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltstylegt6 solidgauge highcharts-yaxis-grid highcharts-grid-line7 solidgauge highcharts-yaxis-grid highcharts-minor-grid-line 8 display none9

10 solidgauge highcharts-pane 11 fill eee12 fill-opacity 113 stroke aaa14 stroke-width 2px15 16 night solidgauge highcharts-pane 17 fill b1b1b118 stroke b1b1b119 20 solidgauge highcharts-point 21 transition fill 500ms stroke 500ms see stops styles note 22 23 throttle-gauge highcharts-color-0 24 fill eee initial colors = pane for smooth fade in 25 stroke aaa26 fill-opacity 0827 stroke-width 3px28 stroke-opacity 0529 30 rpm-gauge highcharts-color-0 31 fill 55e32 stroke none33 34 ltstylegt35

36 ltdiv class=panel panel-primarygt

(continues on next page)

278 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

37 ltdiv class=panel-headinggtSolid Gaugeltdivgt38 ltdiv class=panel-bodygt39

40 ltdiv class=receivergt41

42 ltdiv class=rowgt43 ltdiv class=col-sm-6gt44 ltdiv class=metric chart data-metric=vethrottle style=height220pxgt45 ltdiv class=chart-box solidgauge id=throttle-gaugegt46 ltdivgt47 ltpgt48 Note stops dont work by default in styled mode This example includes a

rarr˓simple redraw49 event callback that applies styles from the stops To get a smooth color

rarr˓transition50 the CSS transition time needs to be equal to the chart animation time51 ltpgt52 ltdivgt53 ltdiv class=col-sm-6gt54 ltdiv class=metric chart data-metric=vmrpm style=height220pxgt55 ltdiv class=chart-box solidgauge gaugechart id=rpm-gaugegt56 ltdivgt57 ltpgt58 Note the ltcodegtgaugechartltcodegt CSS class pulls in the default styling

rarr˓for the bands59 labels and ticks here You can also copy those CSS rules from ltcodegtovms

rarr˓cssltcodegt60 and do your own styling61 ltpgt62 ltdivgt63 ltdivgt64

65 ltpgtltbutton type=button class=btn btn-default action-gendatagtGenerate randomrarr˓dataltbuttongtltpgt

66

67 ltdivgt68

69 ltdivgt70 ltdivgt71

72 ltscriptgt73 (function()74

75 Show page source 76 var pagesrc = $(main)html()77 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +78 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)79 $(action-showsrc)on(click function() 80 $(ltdivgt)dialog(81 title Source Code82 body ltpre style=font-size85 heightcalc(100vh - 230px)gt83 + encode_html(pagesrc) + ltpregt84 size lg85 )86 )87

(continues on next page)

331 TLDR Examples 279

Open Vehicles

(continued from previous page)

88 Init throttle gauge 89 $(throttle-gauge)chart(90 chart 91 type solidgauge92 spacing [0 0 0 0]93 margin [0 0 0 0]94 animation duration 500 easing easeOutExpo 95 events 96 Apply stops styles on redraw97 redraw function(ev) 98 var y = thisseries[0]yData[0] $pt = $(thisrenderTo)find(highcharts-

rarr˓point)99 $map(thisyAxis[0]stops function(stop) if (y gt= stop[0]) $pt

rarr˓css(stop[1]) )100 101 102 103 title text Throttle verticalAlign middle y 75 104 credits enabled false 105 tooltip enabled false 106 plotOptions 107 solidgauge dataLabels enabled false overshoot 1 108 109 pane [110 startAngle -90 endAngle 90 size 140 center [50 85]111 background innerRadius 60 outerRadius 100 shape arc 112 ]113 yAxis [114 title text 115 className throttle116 reversed false117 min 0 max 100118 stops [119 [0 fill afa stroke 4f4 ]120 [50 fill ffa stroke ff4 ]121 [80 fill faa stroke f44 ]122 ]123 tickPixelInterval 40 tickPosition inside tickLength 13124 labels step 2 distance 10 x 0 y 0 zIndex 2 125 ]126 series [127 name Throttle data [40]128 className throttle129 animation duration 0 130 ]131 Update method 132 onUpdate function(update) 133 Create gauge data set from metric134 var data = [ metrics[vethrottle] ]135 Update chart136 thisseries[0]setData(data)137 138 )139

140 Init rpm gauge 141 $(rpm-gauge)chart(142 chart

(continues on next page)

280 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

143 type solidgauge144 spacing [0 0 0 0]145 margin [0 0 0 0]146 animation duration 500 easing easeOutExpo 147 148 title text RPM verticalAlign middle y 75 149 credits enabled false 150 tooltip enabled false 151 plotOptions 152 solidgauge dataLabels enabled false overshoot 1 153 154 pane [155 startAngle -90 endAngle 90 size 140 center [50 85]156 background innerRadius 70 outerRadius 100 shape arc 157 ]158 yAxis [159 title text rpm 160 className rpm161 reversed false162 min 0 max 11000163 plotBands [164 from 0 to 7000 className green-band 165 from 7000 to 9000 className yellow-band 166 from 9000 to 11000 className red-band 167 ]168 minorTickInterval auto minorTickLength 5 minorTickPosition inside169 tickPixelInterval 40 tickPosition inside tickLength 10170 labels step 2 distance 10 x 0 y 0 zIndex 2 171 ]172 series [173 name RPM data [4500]174 className rpm175 animation duration 0 176 innerRadius 72177 radius 92178 ]179 Update method 180 onUpdate function(update) 181 Create gauge data set from metric182 var data = [ metrics[vmrpm] ]183 Update chart184 thisseries[0]setData(data)185 186 )187

188 Test metrics generator 189 $(action-gendata)on(click function() 190 var td = 191 td[vethrottle] = Mathrandom() 100192 td[vmrpm] = Mathrandom() 11000193 $(receiver)trigger(msgmetrics $extend(metrics td))194 )195

196 )()197 ltscriptgt

331 TLDR Examples 281

Open Vehicles

3316 Command Streaming

loadcmdhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltdiv class=panel panel-primarygt6 ltdiv class=panel-headinggtAsynchronous Command Streamingltdivgt7 ltdiv class=panel-bodygt8

9 lth3gtSynopsislth3gt10

11 ltp class=leadgtltcodegt[jqxhr=] loadcmd(command [target] [filter] [timeout])ltrarr˓codegtltpgt

12

13 ltpgtThe ltcodegtloadcmd()ltcodegt function executes a shell command or evaluatesrarr˓javascript

14 code with asynchronous streaming of the output into a target element or onto ararr˓functionltpgt

15

16

17 lth3gtBasic Usagelth3gt18

19 ltpgtAs this is the underlying function for command buttons basic usage20 is very similar but fully scriptableltpgt21

22 ltpgt23 ltbutton type=button class=btn btn-default onclick=loadcmd(boot status

rarr˓out1)gt24 Show boot status25 ltbuttongt26 ltpgt27 ltpre id=out1 gt28

29 ltpgtAs with command buttons you can append the output by prefixing the target30 selector with + You can omit the output by passing null as the target If

rarr˓target31 is a DOM element loadcmd automatically sets the ltcodegtloadingltcodegt class on

rarr˓the32 target while the command is processedltpgt33

34 ltpgtThe target elements min-height is automatically fixed to the current height35 of the target before the output is set This avoids page layout jumps when36 reusing a target for commandsltpgt37

38 ltpgtIf the target is scrollable and the content exceeds the visible area the39 element is automatically scrolled to show the new content unless the user has40 done a manual scrolling on the elementltpgt41

42 ltpgtIf the command output stops for ltcodegttimeoutltcodegt seconds the request is43 aborted and a timeout error is shown Default timeout is 20 seconds for standard44 commands 300 seconds for known long running commandsltpgt45

46

47 lth3gtEvaluate Javascript Codelth3gt48

(continues on next page)

282 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

49 ltpgtTo execute Javascript either pass an object instead of the ltcodegtcommandltrarr˓codegt string

50 containing the command as property command and a second property type with51 value js or simply use the wrapper call ltcodegtloadjs()ltcodegt Exampleltpgt52

53 ltpgt54 ltbutton type=button class=btn btn-default55 onclick=loadjs(print(OvmsVehicleType()) out1js)gt56 Show vehicle type57 ltbuttongt58 ltpgt59 ltpre id=out1js gt60

61 ltpgtJavascript evaluation is not limited to a single command or line Hint torarr˓avoid

62 encoding complex JS code in the onclick attribute store the code in some hidden63 DOM element and read it via ltcodegt$()text()ltcodegtltpgt64

65

66 lth3gtOutput Encoding ampamp Binary Streamslth3gt67

68 ltpgtTo allow binary data to be sent by a command and to enable processing of the69 result by Javascript on the browser without character encoding issues the

rarr˓command70 API supports output binary modeltpgt71

72 ltpgtPrimary application for this is exchanging CBOR encoded objects between the73 module and the web frontend To fully support this the OVMS web frontent

rarr˓includes74 the CBOR library by Patrick Gansterer Example useltpgt75

76 ltpregt77 loadjs( command auxbatmondump(CBOR) output binary )done((data) =gt 78 history = CBORdecode(data)79 )80 ltpregt81

82 ltpgtSee the AuxBatMon and PwrMon OVMS plugins for full examplesltpgt83

84 ltpgtltcodegtoutputltcodegt modes supported by the command API areltpgt85

86 ltulgt87 ltligtltcodegttextltcodegt rarr Content-Type textplain charset=utf-8ltligt88 ltligtltcodegtjsonltcodegt rarr Content-Type applicationjson charset=utf-8ltligt89 ltligtltcodegtbinaryltcodegt rarr Content-Type applicationoctet-stream charset=x-

rarr˓user-definedltligt90 ltligtdefaultother rarr Content-Type applicationoctet-stream charset=utf-8ltligt91 ltulgt92

93

94 lth3gtjqXHR Objectlth3gt95

96 ltpgtltcodegtloadcmd()ltcodegt returns the jqXHR (XMLHttpRequest) object in charge for97 the asynchronous execution of the request This can be used to track the results98 of the execution check for errors or to abort the commandltpgt99

100 ltpgt(continues on next page)

331 TLDR Examples 283

Open Vehicles

(continued from previous page)

101 ltbutton type=button class=btn btn-default id=startcggtStart chargenltrarr˓buttongt

102 ltbutton type=button class=btn btn-default id=abortcg disabledgtAbortrarr˓chargenltbuttongt

103 ltpgt104 ltpre id=out2 style=max-height200px overflowauto gt105

106 ltpgtThe jQuery XHR object is also a thenable so actions to be performed after107 the command execution can simply be chained to the object Exampleltpgt108

109 ltpgtltbutton type=button class=btn btn-default id=showstatgtShow statltbuttongtrarr˓ltpgt

110

111 ltpgtSee lta target=_blank href=httpapijquerycomjQueryajaxjqXHRgtjQuery112 documentationltagt for full details and optionsltpgt113

114

115 lth3gtFilter Process Outputlth3gt116

117 ltpgtSupply a filter function to hook into the asynchronous output stream Userarr˓filters

118 to filter (ahem) preprocess reformat the command output scan the streamrarr˓for some

119 info youd like to know as soon as possible or completely take over the output120 processingltpgt121

122 ltpgtThe filter function is called when a new chunk of output has arrived or when123 a stream error has occurred The function gets a message object containing124 the ltcodegtrequestltcodegt object and either a ltcodegttextltcodegt for normal

rarr˓outputs125 or an ltcodegterrorltcodegt which is a preformatted error output you can use or126 ignoreltpgt127

128 ltpgtIf the filter function returns a string that will be added to the outputrarr˓target

129 If it returns ltcodegtnullltcodegt the target will remain untouchedltpgt130

131 ltpgtHint if you just want to scan the text for some info you can pass on therarr˓message

132 after your scan to the default ltcodegtstandardTextFilter()ltcodegtltpgt133

134 ltpgtExample lets reformat a ltcodegtcan statusltcodegt dump into a nice Bootstraprarr˓tableltpgt

135

136 ltpgtltbutton type=button class=btn btn-default id=canstatusgtCAN1 statusltrarr˓buttongtltpgt

137

138 lttable class=table table-condensed table-border table-striped table-hover id=rarr˓canoutgt

139 lttheadgt140 lttrgtltth class=col-xs-6gtKeyltthgtltth class=col-xs-6gtValueltthgtlttrgt141 lttheadgt142 lttbodygt143 lttablegt144

145 ltdivgt146 ltdivgt

(continues on next page)

284 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

147

148 ltscriptgt149 (function()150

151 Show page source 152 var pagesrc = $(main)html()153 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +154 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)155 $(action-showsrc)on(click function() 156 $(ltdivgt)dialog(157 title Source Code158 body ltpre style=font-size85 heightcalc(100vh - 230px)gt159 + encode_html(pagesrc) + ltpregt160 size lg161 )162 )163

164 Example jqXHRabort() 165 var xhr166 $(startcg)on(click function() 167 xhr = loadcmd(test chargen 20 600 out2)168 $(abortcg)prop(disabled false)169 )170 $(abortcg)on(click function() 171 xhrabort()172 )173

174 Example jqXHRthen() 175 $(showstat)on(click function() 176 loadcmd(stat)then(function(output) 177 confirmdialog(STAT result ltsampgt + output + ltsampgt [Close])178 )179 )180

181 Example filter output processor 182 $(canstatus)on(click function() 183 var $table = $(canout gt tbody)184 var buf = 185 $tableempty()186 loadcmd(can can1 status function(msg) 187 if (msgerror) 188 Render error into table row189 $(lttr class=dangergtlttd colspan=2gt + msgerror + lttdgtlttrgt)appendTo(

rarr˓$table)190 191 else if (msgtext) 192 As this is a stream the text chunks received need not be single or

rarr˓complete lines193 Were interested in lines here so we buffer the chunks and split the

rarr˓buffer at n194 buf += msgtext195 var lines = bufsplit(n)196 if (lineslength gt 1) 197 buf = lines[lineslength-1]198 for (var i = 0 i lt lineslength-1 i++) 199 Skip empty lines

(continues on next page)

331 TLDR Examples 285

Open Vehicles

(continued from previous page)

200 if (lines[i] == ) continue201 Split line into columns202 var col = lines[i]split( +)203 Create table row amp append to table add some color on error counters204 if (col[0]match([Ee]rr))205 $(lttr class=warninggtltthgt + col[0] + ltthgtlttdgt + col[1] + lttdgtlt

rarr˓trgt)appendTo($table)206 else207 $(lttrgtltthgt + col[0] + ltthgtlttdgt + col[1] + lttdgtlttrgt)appendTo(

rarr˓$table)208 209 210 211 Filter has handled everything212 return null213 )214 )215

216 )()217 ltscriptgt

3317 File API

The file API enables web clients to read and write files at arbitrary VFS locations

bull API URL apifile

bull Methods

ndash GET ndash read file

ndash POST ndash write file

bull Parameters

ndash path ndash the full path to the file

ndash content ndash the new file content on POST

bull Output

ndash HTTP status 200 (OK) or 400 (Error)

ndash HTTP body file content on GET or error message

On writing missing directories along the path will be created automatically

Usage Example

The API can be accessed easily in the web frontend with the jQuery AJAX methods

Write object JSON encoded into filevar json = JSONstringify(object)$post(apifile path sdmystorefile1 content json )

done(function() confirmdialog(Saved ltpgtFile has been savedltpgt [OK] 2)

)fail(function(jqXHR)

(continues on next page)

286 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

confirmdialog(Save failed jqXHRresponseText [OK]))

Read JSON encoded object from file$get(apifile path sdmystorefile1 )

done(function(responseText) var object = JSONparse(responseText) process object

)fail(function(jqXHR) confirmdialog(Load failed jqXHRresponseText [OK])

)

External Access

From external clients the API can be used by either registering a session cookie or by supplying the apikey param-eter (as explained in the general authorization overview)

Read example

curl http19216841apifileapikey=passwordamppath=sdmystorefile1

Write example

curl http19216841apifile -d apikey=password -d path=sdmystorefile1 --data-urlencode contentlocalfile

3318 Longtouch Buttons

btn-longtouchhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web dir eg scp testpagehtm test1localsddev5 - open in framework by eg httptest1localdevtestpagehtm6 --gt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtLongtouch Buttonsltdivgt

10 ltdiv class=panel-bodygt11

12 ltpgtNote open this test page with a mobile touch screen device or simulate13 a mobile device using the web debugger of your browserltpgt14

15 ltpgtThe buttons below should work normally on a non-touch deviceltpgt16

17 ltpgtOn a touch screen device touching the buttons starts a countdown18 of 15 seconds showing an overlay with a progress bar and giving vibration19 signals (on devices supporting this) The button action is triggered only20 after the countdown has finished while holding the touchltpgt21

22 ltpgtThis feature is meant to a) secure certain buttons against unintentionalrarr˓activation

(continues on next page)

331 TLDR Examples 287

Open Vehicles

(continued from previous page)

23 and to b) allow secure usage of these buttons while driving ie when the mobilerarr˓phone

24 tablet is mounted to a car holderltpgt25

26 ltpgtStandard candidates for this are buttons triggering deep modifications ie27 changing the car tuning or drive modeltpgt28

29 ltpgtTo activate the feature on a button simply add the class ltcodegtbtn-longtouchltrarr˓codegt to the button

30 To activate it on a group of buttons add the class to the container of therarr˓buttonsltpgt

31

32 ltpgtThe progress overlay shows the button title if set (HTML supported) else therarr˓button textltpgt

33

34 ltform action=gt35 ltdiv class=btn-group btn-group-justified btn-longtouchgt36 ltdiv class=btn-group btn-group-lggt37 ltbutton type=submit name=load value=0 id=prof-0 class=btn btn-

rarr˓defaultgtltstronggtSTDltstronggtltbuttongt38 ltdivgt39 ltdiv class=btn-group btn-group-lggt40 ltbutton type=submit name=load value=1 id=prof-1 class=btn btn-

rarr˓default title=Power ModegtltstronggtPWRltstronggtltbuttongt41 ltdivgt42 ltdiv class=btn-group btn-group-lggt43 ltbutton type=submit name=load value=2 id=prof-2 class=btn btn-

rarr˓successgtltstronggtECOltstronggtltbuttongt44 ltdivgt45 ltdiv class=btn-group btn-group-lggt46 ltbutton type=submit name=load value=3 id=prof-3 class=btn btn-

rarr˓default title=Winter ModegtltstronggtICEltstronggtltbuttongt47 ltdivgt48 ltdivgt49 ltformgt50

51 ltdivgt52 ltdivgt

3319 Basic Dialogs

dialogtesthtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web dir eg scp testpagehtm test1localsddev5 - open in framework by eg httptest1localdevtestpagehtm6 --gt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtDialog TestDemoltdivgt

10 ltdiv class=panel-bodygt11 lth4gtCore Widgetlth4gt12 ltbutton class=btn btn-default id=action-loadgtDialog 1ltbuttongt

(continues on next page)

288 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

13 ltbutton class=btn btn-default id=action-savegtDialog 2ltbuttongt14 ltbutton class=btn btn-default id=action-bothgtBoth togetherltbuttongt15 ltbutton class=btn btn-default id=action-dyngtDynamic customltbuttongt16 lthr gt17 lth4gtUtility Wrapperslth4gt18 ltbutton class=btn btn-default id=action-infogtAlertltbuttongt19 ltbutton class=btn btn-default id=action-confirmgtConfirmltbuttongt20 ltbutton class=btn btn-default id=action-choicegtChoiceltbuttongt21 ltbutton class=btn btn-default id=action-promptgtPromptltbuttongt22 ltbutton class=btn btn-default id=action-passwordgtPasswordltbuttongt23 lthr gt24 lth4gtLoglth4gt25 ltpre id=log gt26 ltdivgt27 ltdivgt28

29 ltdiv id=dialog1 gt30 ltdiv id=dialog2 gt31 ltdiv id=dialog3 gt32

33 ltscriptgt34

35 rarr˓=======================================================================================

36 Dialog core widget37 options 38 title 39 body 40 show false true = open directly on init41 remote false42 backdrop true background overlay43 keyboard true ESC = close44 transition fade 45 size sm lg46 contentClass added to modal-content47 onShown null function(input)48 onHidden null function(input)49 onShow null function(input)50 onHide null function(input)51 onUpdate null function(input)52 buttons [] see example53 timeout 0 in seconds54 input null predefinedshared input object to use55 56

57 Note use static dialogs (attached to the document) for speed and to store reusable58 input eg for a promptdialog59

60 The default dialog will contain just a Close button61 $(dialog1)dialog(62 title Please note63 body ltpgtThis is just a testltpgt64 )65 $(dialog2)dialog(66 title Alert67 body ltpgtDanger Will Robinson dangerltpgt68 contentClass alert-danger note looks strange just an example -- dont use

(continues on next page)

331 TLDR Examples 289

Open Vehicles

(continued from previous page)

69 )70

71 You can simply open preconfigured dialogs like this72 $(action-load)on(click function()73 $(dialog1)dialog(show)74 )75 $(action-save)on(click function()76 $(dialog2)dialog(show)77 )78

79 or you can reconfigure dialogs on the fly like this80 Note the new configuration is stored in the dialog81 $(action-both)on(click function()82 $(dialog1)dialog(show body ltpgtThis is now another testltpgt )83 This example also opens a second dialog on top of the first84 $(dialog2)dialog(show body ltpgtThis is a second layer dialogltpgt )85 )86

87 Use dynamic dialogs for single shot purposes88 $(action-dyn)on(click function()89 $(log)text()90 $(ltdiv gt)dialog(91 title Dynamic92 body ltpgtdialog with custom buttonsltpgt93 buttons [94 Buttons default to auto hiding the dialog95 label Nope 96 You can get the button clicked in the onHidden callback or you can97 add specific action callbacks to each button98 label Maybe btnClass warning autoHide false action

rarr˓function(input) 99 input is the data container of the widget with only predefined

100 member being button = the button clicked (or null)101 You can use this container for custom extensions102 inputclicked_maybe = true103 $(this)find(modal-body)append(ltpgtYoure now a maybe personltpgt)104 105 autoHide callbacks are called on the hidden event so a fade out106 is guaranteed to be finished in the callback107 label Done btnClass primary action function(input) 108 $(log)text(JSONstringify(input null 2))109 110 ]111 )112 )113

114

115 rarr˓=======================================================================================

116 Dialog utility wrappers117 confirmdialog(title body buttons [callback] timeout)118 promptdialog(type title body buttons callback)119 Both can be used plugin style or standalone for dynamic dialogs120

121 Dynamic alert() style dialog with 5 seconds timeout122 $(action-info)on(click function()123 confirmdialog(Sorry Im afraid I cant do that Dave [OK] 5)

(continues on next page)

290 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

124 Note you can also add a callback here to know when the dialog is dismissed125 )126

127 Dynamic confirm() style dialog128 $(action-confirm)on(click function()129 $(log)text()130 confirmdialog(Load file Discard unsaved changes [No Yes]

rarr˓function(confirmed)131 if (confirmed)132 $(log)text(Loading now)133 else134 $(log)text(Load aborted)135 )136 )137

138 The callback argument is the index of the button clicked (or null) so139 simple choice dialogs can be done like this140 $(action-choice)on(click function()141 $(log)text()142 confirmdialog(Select Please select the slot to use [1 2 3 4]

rarr˓function(button)143 if (button = null)144 $(log)text(Using slot + (button+1))145 else146 $(log)text(Abort)147 )148 )149

150 Static prompt() style text input dialog (with dialog3 keeping the dialog)151 $(action-prompt)on(click function()152 $(log)text()153 $(dialog3)promptdialog(text Save data Please enter file name [Cancel

rarr˓ Save] function(button input)154 if (button ampamp input)155 $(log)text(Saving to file + input)156 else157 $(log)text(Save aborted)158 )159 )160

161 All single field HTML5 input types can be used162 $(action-password)on(click function()163 $(log)text()164 promptdialog(password Authentication Please enter PIN [Cancel Continue

rarr˓] function(button input)165 if (button ampamp input)166 $(log)text(PIN entered + input)167 else168 $(log)text(Auth aborted)169 )170 )171

172 ltscriptgt

331 TLDR Examples 291

Open Vehicles

33110 File Dialogs

filedialoghtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web file path eg sddevfiledialoghtm5 - open in framework by eg httptest1localdevfiledialoghtm6 --gt7

8 ltdiv class=filedialog id=fileselectgt9

10 ltdiv class=panel panel-primarygt11 ltdiv class=panel-headinggtFileDialog Testltdivgt12 ltdiv class=panel-bodygt13

14 lth2gtDynamic APIlth2gt15

16 ltpgt17 ltbutton class=btn btn-default id=action-loadgtLoadltbuttongt18 ltbutton class=btn btn-default id=action-savegtSaveltbuttongt19 ltpgt20 ltpre id=loggt21

22 lth2gtData APIlth2gt23

24 ltdiv class=input-groupgt25 ltinput type=text class=form-control font-monospace placeholder=Enter file

rarr˓name26 name=filename id=input-filename value= autocapitalize=none

rarr˓autocorrect=off27 autocomplete=section-demo spellcheck=falsegt28 ltdiv class=input-group-btngt29 lt-- use data-toggle=filedialog data-target amp data-input on the button --gt30 ltbutton type=button class=btn btn-default data-toggle=filedialog data-

rarr˓target=fd-api data-input=input-filenamegtSelectltbuttongt31 ltdivgt32 ltdivgt33

34 lt-- This is the file dialog triggered by the button --gt35 ltdiv class=filedialog id=fd-api data-options=36 title This is a data API dialog37 path sdfoo38 quicknav [sd sdfoo sdbar]39 gt40 lt-- thats it no JS code necessary41 Note JSON syntax needs to be strict here see JS console for errors42 --gt43

44 ltdivgt45 ltdivgt46

47 ltscriptgt48

49 rarr˓=======================================================================================

50 FileDialog is a Dialog with an embedded FileBrowser

(continues on next page)

292 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

51 52 The input object combines the dialog button and the file browser data53 54 Options55 title Select file -- dialog title56 submit Select -- label of submit button57 select f -- f = only files selectable (default) d

rarr˓ = only directories58 onSubmit null -- callback function(input)59 onCancel null -- callback function(input)60 61 inherited from FileBrowser62 path 63 quicknav [sd store]64 filter null65 sortBy null66 sortDir 167 68 inherited from Dialog69 backdrop true70 keyboard true71 transition fade72 size lg73 onUpdate null74 75

76 Init dialog77 $(fileselect)filedialog(78 path storescripts79 quicknav [storescripts storeevents storeobd2ecu]80 )81

82 $(action-load)on(click function()83 $(log)empty()84 $(fileselect)filedialog(show 85 title Load Script86 submit Load87 onSubmit function(input) 88 This is called when the user doubleclicks an entry or presses Enter in a

rarr˓directory89 Note you need to check if inputfile is valid (empty = directory selected)90 if (inputfile)91 $(log)text(Loading + inputpath + n)92 else93 $(log)text(Directory selection + inputpath + n)94 95 onCancel function(input) 96 This is called when the user cancels or closes the dialog97 $(log)text(Load cancelledn)98 99 )

100 )101

102 $(action-save)on(click function()103 $(log)empty()104 $(fileselect)filedialog(show 105 title Save Script

(continues on next page)

331 TLDR Examples 293

Open Vehicles

(continued from previous page)

106 submit Save107 onSubmit function(input) 108 if (inputfile)109 $(log)text(Saving + inputpath + n)110 else111 $(log)text(Directory selection + inputpath + n)112 113 onCancel function(input) 114 $(log)text(Save cancelledn)115 116 )117 )118

119 ltscriptgt

33111 File Browser Widget

filebrowserhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web file path eg sddevfilebrowserhtm5 - open in framework by eg httptest1localdevfilebrowserhtm6 --gt7

8 ltstylegt9 Note set height or min-height on the filebrowser tbody

10 Default height by class filebrowser is 310px (each file row has a height of 31pxrarr˓with the default font size)

11 myfilebrowser tbody 12 height 35vh13 14 ltstylegt15

16 ltdiv class=panel panel-primarygt17 ltdiv class=panel-headinggtFileBrowser TestDemoltdivgt18 ltdiv class=panel-bodygt19

20 ltdiv class=filebrowser id=myfilebrowser gt21

22 lthrgt23 ltpre id=loggt24 ltbutton type=button class=btn btn-default id=action-setpathgtSet path to sd

rarr˓logslogltbuttongt25 ltbutton type=button class=btn btn-default id=action-stoploadgtStop loading

rarr˓dirltbuttongt26 ltbutton type=button class=btn btn-default id=action-filterongtFilter ziplt

rarr˓buttongt27 ltbutton type=button class=btn btn-default id=action-filteroffgtFilter offlt

rarr˓buttongt28 ltbutton type=button class=btn btn-default id=action-sortoffgtSort offlt

rarr˓buttongt29 ltpgtNote the test widget is configured to stopinhibit loading on selection of a

rarr˓txt file or a directory matching DCIMltpgt(continues on next page)

294 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

30 ltdivgt31 ltdivgt32

33 ltscriptgt34

35 rarr˓=======================================================================================

36 FileBrowser Widget37 38 Testdemo of init with all options39 Note you can init a filebrowser without any options40 Defaults are path amp quicknav as shown below no sorting no callbacks41 42 The input object passed to all callbacks contains these fields43 - path -- the full path (dir + + file)44 - file -- the file part of the currently selected path45 - dir -- the directory part of the currently selected path46 - noload -- set to true to inhibit directory loading (see onPathChange)47 48 Note path file amp dir are unvalidated user input49 50 Note on sorting disabling initial sorting improves user interaction while loading

rarr˓the51 directory ie to select filesdirs while the loader is running This may52 be an option especially for large directories The user can still sort manually53 54 Methods55 - getInput() -- retrieve input object56 - setPath(newpath reload) -- add trailing slash to enter dir wo file

rarr˓selection57 - sortList(by dir) -- sort file list58 - loadDir() -- trigger directory reload59 - stopLoad() -- abort directory loading60 - newDir() -- open create directory sub dialog61 62

63 $(myfilebrowser)filebrowser(64 path sd65 quicknav [sd store]66 filter null see Filter examples below67 sortBy name or size or date or null (disable)68 sortDir 1 or -1 for reverse69 onUpdate function(input) 70 This is called after any widget configuration update use for custom

rarr˓extensions71 $(log)append(onUpdate + JSONstringify(input) + n)72 73 onPathChange function(input) 74 Called whenever the path changes75 $(log)append(onPathChange + JSONstringify(input) + n)76 To inhibit loading the directory for the new path set inputnoload to true77 if (inputdirindexOf(DCIM) gt= 0 || inputfileindexOf(txt) gt= 0) 78 $(log)append(inhibiting directory loadingn)79 inputnoload = true80 81 82 onAction function(input)

(continues on next page)

331 TLDR Examples 295

Open Vehicles

(continued from previous page)

83 This is called when the user doubleclicks an entry or presses Enter in ararr˓directory

84 $(log)append(onAction + JSONstringify(input) + n)85 86 )87

88 $(action-setpath)on(click function(ev) 89 $(myfilebrowser)filebrowser(setPath sdlogslog true)90 )91 $(action-stopload)on(click function(ev) 92 $(myfilebrowser)filebrowser(stopLoad)93 )94 $(action-sortoff)on(click function(ev) 95 $(myfilebrowser)filebrowser(sortList )96 )97

98 Filter example99 $(action-filteron)on(click function(ev)

100 $(myfilebrowser)filebrowser(101 The list filter may be given as a string (regular expression applied to file

rarr˓name)102 filter zip$103 A string filter always lists directories104

105 For advanced usage you may alternatively specify a filter callback like this106 filter function(f) return fisdir || fnamematch(zip$) 107 The function is called per list entry object with108 - isdir true = is sub directory109 - name the name part (file or directory dir with trailing )110 - path the full path of this entry111 - size formatted size (68k)112 - date formatted date (23-Nov-2018 1742)113 - bytes size in bytes -1 for directories114 - isodate ISO style date YYYY-mm-dd HHMM115 - class can be used to add a custom row class116 Return true to allow the entry to be added to the list117

118 Note list filters do not restrict the allowed path input To do so119 register onPathChange or onAction and check the input in your callback120 See FileDialog widget select option handling for an example121 )122 )123 $(action-filteroff)on(click function(ev) 124 $(myfilebrowser)filebrowser(125 filter null126 )127 )128

129 ltscriptgt

33112 Slider Widget

input-sliderhtm (hint right click save as)

296 Chapter 33 Web Framework amp Plugins

Open Vehicles

1 ltstylegt2 Align multiple slider inputs by suitably fixing their value width 3 form-inline form-controlslider-value 4 width 80px5 6 ltstylegt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtSlider Widgetltdivgt

10 ltdiv class=panel-bodygt11

12 lth3gtStandard Numerical Inputslth3gt13

14 ltpgtThe number input is just the bootstrap defaultltpgt15

16 ltinput class=form-control type=number id=input-num1 name=num1 value=80rarr˓min=0 max=100 step=1gt

17 ltbrgt18

19 ltpgtThe range input has some styling optimization for touch devicesltpgt20

21 ltinput class=form-control type=range id=input-rng1 name=rng1 value=80rarr˓min=0 max=100 step=1gt

22 ltbrgt23

24 lth3gtSlider Widgetlth3gt25

26 ltpgt27 In many cases youd like to give especially the touchscreen user a combination

rarr˓of these input28 elements and as sliding may be too imprecise you also need large buttons for

rarr˓single step changes29 Thats what the slider widget does It also adds the option of a checkbox and a

rarr˓default value to30 reflect if the user control shall be applied31 ltpgt32

33 ltdiv class=rowgt34 ltdiv class=col-md-9gt35

36 ltpgtSliders can easily be created from minimal markup using the ltcodegtslider()rarr˓ltcodegt plugin

37 with configuration given by data attributes andor dynamic optionsltpgt38

39 ltdiv class=form-control slider id=sld1 data-min=-5 data-max=50 data-rarr˓step=05

40 data-default=40 data-unit= data-disabled=false data-checked=truerarr˓data-value=10 gt

41 ltbrgt42

43 ltdiv class=form-control slider id=sld2 gt44 ltbrgt45

46 ltpgtand slider state limits and value can be controlled using the samerarr˓methodltbrgt

47 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(rarr˓value42 )gt

(continues on next page)

331 TLDR Examples 297

Open Vehicles

(continued from previous page)

48 Set sld1 value to 4249 ltbuttongt50 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(

rarr˓checkedtrue )gt51 Check sld152 ltbuttongt53 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(

rarr˓disabledtrue )gt54 Disable sld155 ltbuttongt56 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(

rarr˓disabledfalse )gt57 Enable sld158 ltbuttongt59 ltpgt60 ltbrgt61

62 ltpgtIf you need even more control you can create the slider markup yourselfrarr˓as wellltpgt

63

64 ltdiv class=form-control slider id=sld3 data-default=50 data-reset=falserarr˓

65 data-value=80 data-min=-10 data-max=100 data-step=1gt66 ltdiv class=slider-control form-inlinegt67 ltinput class=slider-enable type=checkbox checkedgt68 ltinput class=form-control slider-value type=number id=input-sld3

rarr˓name=sld3gt69 ltspan class=slider-unitgtltspangt70 ltinput class=btn btn-default slider-down type=button value=gt71 ltinput class=btn btn-default slider-set type=button value=Lo data-

rarr˓set=25gt72 ltinput class=btn btn-default slider-set type=button value=Hi data-

rarr˓set=75gt73 ltinput class=btn btn-default slider-up type=button value=gt74 ltdivgt75 ltinput class=slider-input type=rangegt76 ltdivgt77 ltbrgt78

79 ltdivgt80 ltdiv class=col-md-3gt81

82 ltpgtltugtEvents ampamp valuesltugtltpgt83 ltpre id=show-sldevgtltpregt84

85 ltdivgt86 ltdivgt87

88 ltbrgt89

90 ltpgt91 Checkbox buttons and unit are optional You can reduce the widget to just a

rarr˓number or92 just a range input the input then needs to have the ltcodegtslider-inputltcodegt

rarr˓class93 ltpgt94

(continues on next page)

298 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

95 ltpgt96 The checkbox element defines the default value to be set on unchecking in97 ltcodegtdata-defaultltcodegt By default the checkbox will restore the previous

rarr˓user98 value when re-checked to disable this set ltcodegtdata-resetltcodegt to true99 To reset the value to the default from a script call the ltcodegtslider()ltcodegt

100 method with ltcodegtvalue nullltcodegt (this resets both the actual and the stored101 user value)102 ltpgt103

104 ltpgt105 Values and checkbox status need to be consistent on init or be set by your

rarr˓script106 To hook into value changes attach event handlers to events ltcodegtinputltcodegt107 andor ltcodegtchangeltcodegt as usual Read the ltcodegtcheckedltcodegt property to

rarr˓get the108 checkbox state109 ltpgt110

111 ltdivgt112 ltdivgt113

114 ltscriptgt115 (function()116

117 Show page source 118 var pagesrc = $(main)html()119 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +120 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)121 $(action-showsrc)on(click function() 122 $(ltdivgt)dialog(123 title Source Code124 body ltpre style=font-size85 heightcalc(100vh - 230px)gt125 + encode_html(pagesrc) + ltpregt126 size lg127 )128 )129

130 Init sliders 131 $(slider)slider()132 $(sld2)slider( min-10 max10 step01 default25 unitkW

rarr˓checkedfalse value-38 )133

134 Show slider events amp values 135 var sldev = 136 $(input-sld1 input-sld2 input-sld3)on(input change function(ev) 137 sldev[thisname] = $extend(sldev[thisname] checked thischecked )138 Note thisvalue is unvalidated here for a direct entry but the validation is

rarr˓simple139 sldev[thisname][evtype] = Mathmax(thismin Mathmin(thismax 1thisvalue))140 $(show-sldev)text(JSONstringify(sldev null 2))141 )142

143 )()144 ltscriptgt

331 TLDR Examples 299

Open Vehicles

33113 Regen Brake Monitor

This plugin defines a page including an acceleration level gauge chart number metrics for the acceleration speed andbattery power and two large indicators for the regen brake light and the brake pedal state

Itrsquos useful to fine tune the regen brake settings as you can monitor the actual deceleration levels while driving andcheck the smoothing level

Install add the source as a page plugin eg devregenmon

regenmonhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltstylegt6 indicator gt label 7 font-size 1508 line-height 2009 margin 10px

10 padding 10px11 display block12 border-radius 50px13 14 metricnumber label 15 min-width 8em16

(continues on next page)

300 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

17 metricnumber 18 display block19 float none20 text-align center21 22 ltstylegt23

24 ltdiv class=panel panel-primarygt25 ltdiv class=panel-headinggtRegen Brake Monitorltdivgt26 ltdiv class=panel-bodygt27

28 ltdiv class=receiver id=regenmon-receivergt29

30 ltdiv class=rowgt31 ltdiv class=col-sm-6gt32 ltdiv class=metric chart data-metric=vpacceleration style=height300px

rarr˓gt33 ltdiv class=chart-box gaugechart id=accel-gaugegt34 ltdivgt35 ltdiv class=metric number data-metric=vpacceleration data-prec=2gt36 ltspan class=labelgtAccelerationltspangt37 ltspan class=valuegtltspangt38 ltspan class=unitgtms2ltspangt39 ltdivgt40 ltdiv class=metric number data-metric=vpspeed data-prec=1gt41 ltspan class=labelgtSpeedltspangt42 ltspan class=valuegtltspangt43 ltspan class=unitgtkphltspangt44 ltdivgt45 ltdiv class=metric number data-metric=vbpower data-prec=1gt46 ltspan class=labelgtBattery powerltspangt47 ltspan class=valuegtltspangt48 ltspan class=unitgtkWltspangt49 ltdivgt50 ltbr class=clearfixgt51 ltdivgt52 ltdiv class=col-sm-6gt53 ltdiv class=indicator data-metric=veregenbrakegt54 ltspan class=label label-defaultgtREGENltspangt55 ltdivgt56 ltdiv class=indicator data-metric=vefootbrakegt57 ltspan class=label label-defaultgtFOOTltspangt58 ltdivgt59 ltdivgt60 ltdivgt61

62 ltdivgt63

64 ltdivgt65 ltdivgt66

67 ltscriptgt68 (function()69

70 Init acceleration gauge 71 $(accel-gauge)chart(72 chart

(continues on next page)

331 TLDR Examples 301

Open Vehicles

(continued from previous page)

73 type gauge74 spacing [0 0 0 0]75 margin [0 0 0 0]76 animation duration 250 easing easeOutExpo 77 78 title text Acceleration verticalAlign middle y 75 79 credits enabled false 80 tooltip enabled false 81 plotOptions 82 gauge dataLabels enabled false overshoot 5 83 84 pane [85 startAngle -120 endAngle 120 size 100 center [50 60]86 ]87 yAxis [88 title text ms2 89 className accel90 reversed false91 min -2 max 292 minorTickInterval 01 minorTickLength 5 minorTickPosition inside93 tickInterval 05 tickPosition inside tickLength 1394 labels step 1 distance -28 x 0 y 5 zIndex 2 95 ]96 series [97 name Acceleration data [0]98 className accel99 animation duration 0

100 pivot radius 10 101 dial radius 88 topWidth 1 baseLength 20 baseWidth 10

rarr˓rearLength 20 102 ]103 Update method 104 onUpdate function(update) 105 Create gauge data set from metric106 var data = [ metrics[vpacceleration] ]107 Update chart108 thisseries[0]setData(data)109 110 )111

112 Init indicators 113 $(regenmon-receiver)on(msgmetrics function(e update) 114 $(this)find(indicator)each(function() 115 var $el = $(this) metric = $eldata(metric) val = update[metric]116 if (val == null)117 return118 else if (val = 0)119 $elchildren()removeClass(label-default)addClass(label-danger)120 else if (val == 0)121 $elchildren()removeClass(label-danger)addClass(label-default)122 )123 )124

125 )()126 ltscriptgt

302 Chapter 33 Web Framework amp Plugins

Open Vehicles

33114 Dashboard

A refined and configurable version of this plugin has been added to the standard OVMS web UI and gets automaticallyconfigured by the vehicle modules with their respective vehicle parameters

Itrsquos a good example of the Highcharts gauge chart options and shows how to combine multiple gauge charts into asingle container (div gaugeset1) and how to style the charts using CSS

It also includes a simple test data generator so can be tested without actual vehicle data

To add a new vehicle parameter set for the standard dashboard simply override the GetDashboardConfig()method in your vehicle class Have a look at the existing overrides (for example Twizy Kia Soul Smart ED )

Install not necessary for the standard dashboard If yoursquore going to build your own dashboard from this install it asa page type plugin

dashboardhtm (hint right click save as)

1 lt-- Main --gt2

3 ltstylegt4 media (max-width 767px) 5 panel-single panel-body 6 padding 2px7 8 9 dashboard highcharts-data-label text

10 font-size 2em11 12 dashboard overlay 13 position absolute14 z-index 1015 top 6216 text-align center17 left 018 right 019 20 dashboard overlay value 21 color 04282b22 background 97b59723 padding 2px 5px

(continues on next page)

331 TLDR Examples 303

Open Vehicles

(continued from previous page)

24 margin-right 02em25 text-align center26 border 1px inset c3c3c38027 font-family Monaco Menlo Consolas QuickType Mono Lucida Console

rarr˓Roboto Mono Ubuntu Mono DejaVu Sans Mono Droid Sans Mono monospace28 display inline-block29 30 night dashboard overlay value 31 color fff32 background 25252533 34 dashboard overlay unit 35 color 66636 font-size 12px37 38 dashboard overlay range-value value 39 margin-left 10px40 width 100px41 42 dashboard overlay energy-value 43 margin-top 4px44 45 dashboard overlay energy-value value 46 margin-left 18px47 width 100px48 font-size 12px49 50 ltstylegt51

52 ltdiv class=panel panel-primary id=panel-dashboardgt53 ltdiv class=panel-headinggtDashboardltdivgt54 ltdiv class=panel-bodygt55

56 ltdiv class=receiver get-window-resize id=livestatusgt57 ltdiv class=dashboard style=position relative width 100 height 300px

rarr˓margin 0 autogt58 ltdiv class=overlaygt59 ltdiv class=range-valuegtltspan class=valuegt0 0ltspangtltspan class=unitgtkm

rarr˓ltspangtltdivgt60 ltdiv class=energy-valuegtltspan class=valuegt00 00ltspangtltspan class=

rarr˓unitgtkWhltspangtltdivgt61 ltdivgt62 ltdiv id=gaugeset1 style=width 100 height 100gtltdivgt63 ltdivgt64 ltdivgt65

66 ltdivgt67 ltdivgt68

69

70 lt-- Chart --gt71

72 ltstylegt73 highcharts-plot-band highcharts-pane 74 fill-opacity 075 76 highcharts-plot-bandborder

(continues on next page)

304 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

77 stroke 66666678 stroke-width 1px79 80

81 green-band 82 fill 55BF3B83 fill-opacity 0484 85 yellow-band 86 fill DDDF0D87 fill-opacity 0588 89 red-band 90 fill DF535391 fill-opacity 0692 93 violet-band 94 fill 9622ff95 fill-opacity 0696 97 night violet-band 98 fill 9622ff99 fill-opacity 08

100 101

102 highcharts-gauge-series highcharts-pivot 103 stroke-width 1px104 stroke 757575105 fill-opacity 1106 fill black107 108 highcharts-gauge-seriesauxgauge highcharts-pivot 109 fill-opacity 1110 fill fff111 stroke-width 0112 113 night highcharts-gauge-seriesauxgauge highcharts-pivot 114 fill 000115 116 highcharts-gauge-series highcharts-dial 117 fill d80000118 stroke 000119 stroke-width 05px120 121 highcharts-yaxis-grid highcharts-grid-line122 highcharts-yaxis-grid highcharts-minor-grid-line 123 display none124 125 highcharts-yaxis highcharts-tick 126 stroke-width 2px127 stroke 666666128 129 night highcharts-yaxis highcharts-tick 130 stroke e0e0e0131 132 highcharts-yaxis highcharts-minor-tick 133 stroke-width 18px

(continues on next page)

331 TLDR Examples 305

Open Vehicles

(continued from previous page)

134 stroke 00000085135 stroke-dasharray 6136 stroke-dashoffset -48137 stroke-linecap round138 139 night highcharts-yaxis highcharts-minor-tick 140 stroke ffffff85141 142 highcharts-axis-labels 143 fill 000144 font-weight bold145 font-size 09em146 147 night highcharts-axis-labels 148 fill ddd149 150 highcharts-data-label text 151 fill 333333152 153 night highcharts-data-label text 154 fill fff155 156

157 highcharts-axis-labelsspeed 158 font-size 12em159 160 ltstylegt161

162 ltscript type=textjavascriptgt163

164 Vehicle specific configuration165

166 var vehicle_config_twizy = 167 yAxis [168 Speed169 min 0 max 120170 plotBands [171 from 0 to 70 className green-band 172 from 70 to 100 className yellow-band 173 from 100 to 120 className red-band ]174 175 Voltage176 min 45 max 60177 plotBands [178 from 45 to 475 className red-band 179 from 475 to 50 className yellow-band 180 from 50 to 60 className green-band ]181 182 SOC183 min 0 max 100184 plotBands [185 from 0 to 125 className red-band 186 from 125 to 25 className yellow-band 187 from 25 to 100 className green-band ]188 189 Efficiency190 min 0 max 300

(continues on next page)

306 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

191 plotBands [192 from 0 to 150 className green-band 193 from 150 to 250 className yellow-band 194 from 250 to 300 className red-band ]195 196 Power197 min -10 max 30198 plotBands [199 from -10 to 0 className violet-band 200 from 0 to 15 className green-band 201 from 15 to 25 className yellow-band 202 from 25 to 30 className red-band ]203 204 Charger temperature205 min 20 max 80 tickInterval 20206 plotBands [207 from 20 to 65 className normal-band border 208 from 65 to 80 className red-band border ]209 210 Battery temperature211 min -15 max 65 tickInterval 25212 plotBands [213 from -15 to 0 className red-band border 214 from 0 to 50 className normal-band border 215 from 50 to 65 className red-band border ]216 217 Inverter temperature218 min 20 max 80 tickInterval 20219 plotBands [220 from 20 to 70 className normal-band border 221 from 70 to 80 className red-band border ]222 223 Motor temperature224 min 50 max 125 tickInterval 25225 plotBands [226 from 50 to 110 className normal-band border 227 from 110 to 125 className red-band border ]228 ]229 230

231 var vehicle_config_default = 232 yAxis [233 Speed234 min 0 max 120235 plotBands [236 from 0 to 70 className green-band 237 from 70 to 100 className yellow-band 238 from 100 to 120 className red-band ]239 240 Voltage241 min 310 max 410242 plotBands [243 from 310 to 325 className red-band 244 from 325 to 340 className yellow-band 245 from 340 to 410 className green-band ]246 247 SOC

(continues on next page)

331 TLDR Examples 307

Open Vehicles

(continued from previous page)

248 min 0 max 100249 plotBands [250 from 0 to 125 className red-band 251 from 125 to 25 className yellow-band 252 from 25 to 100 className green-band ]253 254 Efficiency255 min 0 max 400256 plotBands [257 from 0 to 200 className green-band 258 from 200 to 300 className yellow-band 259 from 300 to 400 className red-band ]260 261 Power262 min -50 max 200263 plotBands [264 from -50 to 0 className violet-band 265 from 0 to 100 className green-band 266 from 100 to 150 className yellow-band 267 from 150 to 200 className red-band ]268 269 Charger temperature270 min 20 max 80 tickInterval 20271 plotBands [272 from 20 to 65 className normal-band border 273 from 65 to 80 className red-band border ]274 275 Battery temperature276 min -15 max 65 tickInterval 25277 plotBands [278 from -15 to 0 className red-band border 279 from 0 to 50 className normal-band border 280 from 50 to 65 className red-band border ]281 282 Inverter temperature283 min 20 max 80 tickInterval 20284 plotBands [285 from 20 to 70 className normal-band border 286 from 70 to 80 className red-band border ]287 288 Motor temperature289 min 50 max 125 tickInterval 25290 plotBands [291 from 50 to 110 className normal-band border 292 from 110 to 125 className red-band border ]293 ]294 295

296 var vehicle_config = vehicle_config_twizy297

298 var gaugeset1299

300 function get_dashboard_data() 301 var rmin = metrics[vbrangeest]||0 rmax = metrics[vbrangeideal]||0302 var euse = metrics[vbenergyused]||0 erec = metrics[vbenergyrecd]||0303 if (rmin gt rmax) var x = rmin rmin = rmax rmax = x 304 var md =

(continues on next page)

308 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

305 range value + rmaxtoFixed(0) + + rmintoFixed(0) 306 energy value + eusetoFixed(1) + + erectoFixed(1) 307 series [308 data [metrics[vpspeed]] 309 data [metrics[vbvoltage]] 310 data [metrics[vbsoc]] 311 data [metrics[vbconsumption]] 312 data [metrics[vbpower]] 313 data [metrics[vctemp]] 314 data [metrics[vbtemp]] 315 data [metrics[vitemp]] 316 data [metrics[vmtemp]] ]317 318 return md319 320

321 function update_dashboard() 322 var md = get_dashboard_data()323 $(range-value value)text(mdrangevalue)324 $(energy-value value)text(mdenergyvalue)325 gaugeset1update( series mdseries )326 327

328 function init_gaugeset1() 329 var chart_config = 330 chart 331 type gauge332 spacing [0 0 0 0]333 margin [0 0 0 0]334 animation duration 0 easing swing 335 336 title text null 337 credits enabled false 338 tooltip enabled false 339

340 pane [341 startAngle -125 endAngle 125 center [50 45] size 80

rarr˓Speed342 startAngle 70 endAngle 110 center [-20 20] size 100

rarr˓Voltage343 startAngle 70 endAngle 110 center [-20 60] size 100 SOC344 startAngle -110 endAngle -70 center [120 20] size 100

rarr˓Efficiency345 startAngle -110 endAngle -70 center [120 60] size 100

rarr˓Power346 startAngle -45 endAngle 45 center [20 100] size 30

rarr˓Charger temperature347 startAngle -45 endAngle 45 center [40 100] size 30

rarr˓Battery temperature348 startAngle -45 endAngle 45 center [60 100] size 30

rarr˓Inverter temperature349 startAngle -45 endAngle 45 center [80 100] size 30 ]

rarr˓Motor temperature350

351 responsive 352 rules [353 condition minWidth 0 maxWidth 400

(continues on next page)

331 TLDR Examples 309

Open Vehicles

(continued from previous page)

354 chartOptions 355 pane [356 size 60 Speed357 center [-20 20] Voltage358 center [-20 60] SOC359 center [120 20] Efficiency360 center [120 60] Power361 center [15 100] size 25 Charger temperature362 center [3833 100] size 25 Battery temperature363 center [6166 100] size 25 Inverter temperature364 center [85 100] size 25 ] Motor temperature365 yAxis [ labels step 1 ] Speed366 367 368 condition minWidth 401 maxWidth 450 369 chartOptions 370 pane [371 size 70 Speed372 center [-15 20] Voltage373 center [-15 60] SOC374 center [115 20] Efficiency375 center [115 60] Power376 center [15 100] size 275 Charger temperature377 center [3833 100] size 275 Battery temperature378 center [6166 100] size 275 Inverter temperature379 center [85 100] size 275 ] Motor temperature380 381 382 condition minWidth 451 maxWidth 600 383 chartOptions 384 pane [385 size 80 Speed386 center [-10 20] Voltage387 center [-10 60] SOC388 center [110 20] Efficiency389 center [110 60] ] Power390 391 392 condition minWidth 601 393 chartOptions 394 pane [395 size 85 Speed396 center [0 20] Voltage397 center [0 60] SOC398 center [100 20] Efficiency399 center [100 60] ] Power400 401 ]402 403

404 yAxis [405 Speed axis406 pane 0 className speed title text kmh 407 reversed false408 minorTickInterval auto minorTickLength 5 minorTickPosition inside409 tickPixelInterval 30 tickPosition inside tickLength 13410 labels step 2 distance -28 x 0 y 5 zIndex 2

(continues on next page)

310 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

411 412 Voltage axis413 pane 1 className voltage title text Volt align low x 90 y

rarr˓35 414 reversed true415 minorTickInterval auto minorTickLength 5 minorTickPosition inside416 tickPixelInterval 30 tickPosition inside tickLength 13417 labels step 1 distance -25 x 0 y 5 zIndex 2 418 419 SOC axis420 pane 2 className soc title text SOC align low x 85 y 35 421 reversed true422 minorTickInterval auto minorTickLength 5 minorTickPosition inside423 tickPixelInterval 30 tickPosition inside tickLength 13424 labels step 1 distance -25 x 0 y 5 zIndex 2 425 426 Efficiency axis427 pane 3 className efficiency title text Whkm align low x -125

rarr˓ y 35 428 reversed false429 minorTickInterval auto minorTickLength 5 minorTickPosition inside430 tickPixelInterval 30 tickPosition inside tickLength 13431 labels step 1 distance -25 x 0 y 5 zIndex 2 432 433 Power axis434 pane 4 className power title text kW align low x -115 y 35

rarr˓435 reversed false436 minorTickInterval auto minorTickLength 5 minorTickPosition inside437 tickPixelInterval 30 tickPosition inside tickLength 13438 labels step 1 distance -25 x 0 y 5 zIndex 2 439 440 Charger temperature axis441 pane 5 className temp-charger title text CHG degC y 10 442 tickPosition inside tickLength 10 minorTickInterval null443 labels step 1 distance 3 x 0 y 0 zIndex 2 444 445 Battery temperature axis446 pane 6 className temp-battery title text BAT degC y 10 447 tickPosition inside tickLength 10 minorTickInterval null448 labels step 1 distance 3 x 0 y 0 zIndex 2 449 450 Inverter temperature axis451 pane 7 className temp-inverter title text PEM degC y 10 452 tickPosition inside tickLength 10 minorTickInterval null453 labels step 1 distance 3 x 0 y 0 zIndex 2 454 455 Motor temperature axis456 pane 8 className temp-motor title text MOT degC y 10 457 tickPosition inside tickLength 10 minorTickInterval null458 labels step 1 distance 3 x 0 y 0 zIndex 2 459 ]460

461 plotOptions 462 gauge 463 dataLabels enabled false 464 overshoot 1

(continues on next page)

331 TLDR Examples 311

Open Vehicles

(continued from previous page)

465 466 467 series [468 Speed value469 yAxis 0 name Speed className speed fullgauge data [0]470 pivot radius 10 471 dial radius 88 topWidth 1 baseLength 20 baseWidth 10

rarr˓rearLength 20 472 473 Voltage value474 yAxis 1 name Voltage className voltage auxgauge data [0]475 pivot radius 85 476 dial radius 95 baseWidth 5 baseLength 90 477 478 SOC value479 yAxis 2 name SOC className soc auxgauge data [0]480 pivot radius 85 481 dial radius 95 baseWidth 5 baseLength 90 482 483 Efficiency value484 yAxis 3 name Efficiency className efficiency auxgauge data [0]485 pivot radius 85 486 dial radius 95 baseWidth 5 baseLength 90 487 488 Power value489 yAxis 4 name Power className power auxgauge data [0]490 pivot radius 85 491 dial radius 95 baseWidth 5 baseLength 90 492 493 Charger temperature value494 yAxis 5 name Charger temperature className temp-charger tempgauge

rarr˓data [0]495 dial radius 90 baseWidth 3 baseLength 90 496 497 Battery temperature value498 yAxis 6 name Battery temperature className temp-battery tempgauge

rarr˓data [0]499 dial radius 90 baseWidth 3 baseLength 90 500 501 Inverter temperature value502 yAxis 7 name Inverter temperature className temp-inverter tempgauge

rarr˓data [0]503 dial radius 90 baseWidth 3 baseLength 90 504 505 Motor temperature value506 yAxis 8 name Motor temperature className temp-motor tempgauge data

rarr˓[0]507 dial radius 90 baseWidth 3 baseLength 90 508 ]509 510

511 Inject vehicle config512 for (var i = 0 i lt chart_configyAxislength i++) 513 $extend(chart_configyAxis[i] vehicle_configyAxis[i])514 515

516 gaugeset1 = Highchartschart(gaugeset1 chart_config(continues on next page)

312 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

517 function (chart) 518 chartupdate( chart animation duration 1000 easing swing )519 $(livestatus)on(msgmetrics function(e update)520 update_dashboard()521 )on(window-resize function(e)522 chartreflow()523 )524 525 )526 527

528 function init_charts() 529 init_gaugeset1()530 531

532 if (windowHighcharts) 533 init_charts()534 else 535 $ajax(536 url windowassetscharts_js537 dataType script538 cache true539 success function() init_charts() 540 )541 542

543 ltscriptgt544

545

546

547 lt-- TESTDATENGENERATOR --gt548 ltbr class=clearfixgt549 ltdiv id=viewportinfogtWxHltdivgt550 ltdiv id=debugfsgtltdivgt551 ltbutton class=btn btn-info id=mkmetricsgtMake test metricsltbuttongt552 ltbr class=clearfixgt553 ltscript type=textjavascriptgt554 $(mkmetrics)on(click function()555 var msg = 556 metrics 557 vbrangeest Mathrandom()80558 vbrangeideal Mathrandom()80559 vbenergyused Mathrandom()20560 vbenergyrecd Mathrandom()20561 vpspeed Mathrandom()120562 vbvoltage 45 + Mathrandom()15563 vbsoc Mathrandom()100564 vbconsumption Mathrandom()300565 vbpower Mathrandom()40 - 10566 vctemp Mathrandom()80567 vbtemp Mathrandom()80568 vitemp Mathrandom()80569 vmtemp Mathrandom()80570 571 572 $extend(metrics msgmetrics)573 $(receiver)trigger(msgmetrics msgmetrics)

(continues on next page)

331 TLDR Examples 313

Open Vehicles

(continued from previous page)

574 )575 $(window)on(resize function()576 $(viewportinfo)text($(window)width() + x + $(window)height())577 )trigger(resize)578 ltscriptgt

33115 Twizy Dashboard Tuning Plugin

This plugin adds two sliders to adjust neutral and braking recuperation levels to the dashboard

The sliders listen to driving profile changes and update accordingly

If not yet logged in the sliders are disabled

Install add the plugin as a hook type to page dashboard hook bodypre

dashboard-tunesliderhtm (hint right click save as)

1 lt--2 Hook plugin for dashboardbodypre or bodypost3 - add sliders to adjust recuperation power levels

(continues on next page)

314 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

4 --gt5

6 ltstylegt7 tuneslider 8 margin 10px 8px 09

10 form-inline form-controlslider-value 11 width 80px12 13 ltstylegt14

15 ltdiv class=receiver id=tuneslider style=displaynonegt16 ltdiv class=form-groupgt17 ltlabel class=control-label for=input-neutralgtNeutral recuperationltlabelgt18 ltdiv class=form-control slider id=neutral gt19 ltdivgt20 ltdiv class=form-groupgt21 ltlabel class=control-label for=input-brakegtBrake recuperationltlabelgt22 ltdiv class=form-control slider id=brake gt23 ltdivgt24 ltdivgt25

26 ltscriptgt27 (function()28

29 Init sliders30 $(neutral)slider( min0 max100 step1 unit default18 value18

rarr˓checkedfalse )31 $(brake)slider( min0 max100 step1 unit default18 value18

rarr˓checkedfalse )32

33 Update sliders on profile changes34 var profile35 $(tuneslider)on(msgmetrics function(ev update) 36 if (update[xrtcfgprofile] = null) 37 profile = update[xrtcfgprofile]38 var neutral = profile[7] brake = profile[8] see cfgconvc tagnames for

rarr˓profile structure39 $(neutral)slider( checked (neutral=-1) value (neutral=-1) neutral

rarr˓null )40 $(brake)slider( checked (brake=-1) value (brake=-1) brake null )41 42 )43

44 Update profile on slider changes45 $(tuneslider slider-value)on(change function(ev) 46 var neutral = $(input-neutral)prop(checked) $(input-neutral)val() -

rarr˓147 brake = $(input-brake)prop(checked) $(input-brake)val() -148 autorecup_minprc = profile[43] autorecup_ref = profile[44]49 var cmd = xrt cfg recup + neutral + + brake + + autorecup_ref + +

rarr˓autorecup_minprc50 loadcmd(cmd loadres)51 )52

53 Install into panel54 $(main)one(load function(ev)

(continues on next page)

331 TLDR Examples 315

Open Vehicles

(continued from previous page)

55 if (loggedin) 56 $(tuneslider slider)slider( disabled true )57 58 $(tuneslider)appendTo(panel-dashboard panel-body)show()59 )60

61 )()62 ltscriptgt

33116 Twizy Tuning Profile Editor

This plugin has been added to the Twizy code Itrsquos used here as a more complex example of what can be done byplugins

Itrsquos a full featured SEVCON tuning profile editor including dialogs to load amp save profiles from the OVMS configura-tion and to create amp read base64 profile codes

See Twizy documentation for details on tuning profiles and capabilities

Install not necessary if vehicle Twizy is configured (see ldquoTwizyrdquo menu) If yoursquod like to test this for another vehicleadd as a page plugin eg testprofed

profile-editorhtm (hint right click save as)

1 lt--2 Twizy page plugin Tuning Profile Editor3 Note included in firmware v32

(continues on next page)

316 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

4 --gt5

6 ltstylegt7 form-inline form-controlslider-value 8 width 70px9

10 radio-list 11 height 313px12 overflow-y auto13 overflow-x hidden14 padding-right 15px15 16 radio-list radio 17 overflow hidden18 19 radio-list key 20 min-width 20px21 display inline-block22 text-align center23 margin 0 10px24 25 radio-list kbd 26 min-width 60px27 display inline-block28 text-align center29 margin 0 20px 0 10px30 31 radio-list radio label 32 width 10033 text-align left34 padding 8px 30px35 36 radio-list radio labelactive 37 background-color 337ab738 color fff39 outline none40 41 radio-list radio labelactive input 42 outline none43 44 night radio-list radio labelhover 45 color fff46 47 ltstylegt48

49 ltdiv class=panel panel-primarygt50 ltdiv class=panel-headinggtTuning Profile ltspan id=headkeygtEditorltspangtltdivgt51 ltdiv class=panel-bodygt52 ltform action=gt53

54 ltdiv class=form-groupgt55 ltdiv class=flex-groupgt56 ltbutton type=button class=btn btn-default action-newgtNewltbuttongt57 ltbutton type=button class=btn btn-default action-loadgtLoadltbuttongt58 ltinput type=hidden id=input-key name=key value=gt59 ltinput type=hidden id=input-base64-reset name=base64-reset value=gt60 ltinput type=text class=form-control font-monospace placeholder=Base64

rarr˓profile code (continues on next page)

331 TLDR Examples 317

Open Vehicles

(continued from previous page)

61 name=base64 id=input-base64 value= autocapitalize=none autocorrect=rarr˓off

62 autocomplete=off spellcheck=falsegt63 ltdivgt64 ltdivgt65

66 ltul class=nav nav-tabsgt67 ltli class=activegtlta data-toggle=tab href=tab-drive aria-expanded=truegt

rarr˓Driveltagtltligt68 ltli class=gtlta data-toggle=tab href=tab-recup aria-expanded=falsegtRecup

rarr˓ltagtltligt69 ltli class=gtlta data-toggle=tab href=tab-ramps aria-expanded=falsegtRamps

rarr˓ltagtltligt70 ltulgt71 ltdiv class=tab-contentgt72

73 ltdiv id=tab-drive class=tab-pane section-drive active ingt74

75 ltfieldset id=part-speedgt76 ltlegendgtSpeedltlegendgt77 ltdiv class=form-horizontalgt78 ltdiv class=form-groupgt79 ltlabel class=control-label col-sm-2 for=input-speedgtMax speedlt

rarr˓labelgt80 ltdiv class=col-sm-10gtltdiv class=form-control slider id=speed gtlt

rarr˓divgt81 ltdivgt82 ltdiv class=form-groupgt83 ltlabel class=control-label col-sm-2 for=input-warngtWarn speedlt

rarr˓labelgt84 ltdiv class=col-sm-10gtltdiv class=form-control slider id=warn gtlt

rarr˓divgt85 ltdivgt86 ltdivgt87 ltfieldsetgt88

89 ltfieldset id=part-powergt90 ltlegendgtPowerltlegendgt91 ltdiv class=form-horizontalgt92 ltdiv class=form-groupgt93 ltlabel class=control-label col-sm-2 for=input-currentgtCurrentlt

rarr˓labelgt94 ltdiv class=col-sm-10gtltdiv class=form-control slider id=current gt

rarr˓ltdivgt95 ltdivgt96 ltdiv class=form-groupgt97 ltlabel class=control-label col-sm-2 for=input-torquegtTorqueltlabelgt98 ltdiv class=col-sm-10gtltdiv class=form-control slider id=torque gtlt

rarr˓divgt99 ltdivgt

100 ltdiv class=form-groupgt101 ltlabel class=control-label col-sm-2 for=input-power_lowgtPower lowlt

rarr˓labelgt102 ltdiv class=col-sm-10gtltdiv class=form-control slider id=power_low

rarr˓gtltdivgt103 ltdivgt104 ltdiv class=form-groupgt

(continues on next page)

318 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

105 ltlabel class=control-label col-sm-2 for=input-power_highgtPower highrarr˓ltlabelgt

106 ltdiv class=col-sm-10gtltdiv class=form-control slider id=power_highrarr˓gtltdivgt

107 ltdivgt108 ltdivgt109 ltfieldsetgt110

111 ltfieldset id=part-drivegt112 ltlegendgtDriveltlegendgt113 ltdiv class=form-horizontalgt114 ltdiv class=form-groupgt115 ltlabel class=control-label col-sm-2 for=input-drivegtDrive levellt

rarr˓labelgt116 ltdiv class=col-sm-10gtltdiv class=form-control slider id=drive gtlt

rarr˓divgt117 ltdivgt118 ltdiv class=form-groupgt119 ltlabel class=control-label col-sm-2 for=input-autodrive_refgtAuto 100

rarr˓ refltlabelgt120 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autodrive_

rarr˓ref gtltdivgt121 ltdivgt122 ltdiv class=form-groupgt123 ltlabel class=control-label col-sm-2 for=input-autodrive_minprcgtAuto

rarr˓min levelltlabelgt124 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autodrive_

rarr˓minprc gtltdivgt125 ltdivgt126 ltdivgt127 ltfieldsetgt128

129 ltfieldset id=part-tsmapdgt130 ltlegendgtTorqueSpeed-Map Driveltlegendgt131 ltdiv class=form-horizontalgt132 ltdiv class=form-groupgt133 ltlabel class=control-label col-sm-2 for=input-tsd_prc1gtTrq level 1

rarr˓ltlabelgt134 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc1 gt

rarr˓ltdivgt135 ltdivgt136 ltdiv class=form-groupgt137 ltlabel class=control-label col-sm-2 for=input-tsd_spd1gtat speed

rarr˓ltlabelgt138 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd1 gt

rarr˓ltdivgt139 ltdivgt140 ltdiv class=form-groupgt141 ltlabel class=control-label col-sm-2 for=input-tsd_prc2gtTrq level 2

rarr˓ltlabelgt142 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc2 gt

rarr˓ltdivgt143 ltdivgt144 ltdiv class=form-groupgt145 ltlabel class=control-label col-sm-2 for=input-tsd_spd2gtat speed

rarr˓ltlabelgt146 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd2 gt

rarr˓ltdivgt (continues on next page)

331 TLDR Examples 319

Open Vehicles

(continued from previous page)

147 ltdivgt148 ltdiv class=form-groupgt149 ltlabel class=control-label col-sm-2 for=input-tsd_prc3gtTrq level 3

rarr˓ltlabelgt150 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc3 gt

rarr˓ltdivgt151 ltdivgt152 ltdiv class=form-groupgt153 ltlabel class=control-label col-sm-2 for=input-tsd_spd3gtat speed

rarr˓ltlabelgt154 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd3 gt

rarr˓ltdivgt155 ltdivgt156 ltdiv class=form-groupgt157 ltlabel class=control-label col-sm-2 for=input-tsd_prc4gtTrq level 4

rarr˓ltlabelgt158 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc4 gt

rarr˓ltdivgt159 ltdivgt160 ltdiv class=form-groupgt161 ltlabel class=control-label col-sm-2 for=input-tsd_spd4gtat speed

rarr˓ltlabelgt162 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd4 gt

rarr˓ltdivgt163 ltdivgt164 ltdivgt165 ltfieldsetgt166

167 ltdivgt168

169 ltdiv id=tab-recup class=tab-pane section-recupgt170

171 ltfieldset id=part-recupgt172 ltlegendgtRecupltlegendgt173 ltdiv class=form-horizontalgt174 ltdiv class=form-groupgt175 ltlabel class=control-label col-sm-2 for=input-neutralgtNeutral level

rarr˓ltlabelgt176 ltdiv class=col-sm-10gtltdiv class=form-control slider id=neutral gt

rarr˓ltdivgt177 ltdivgt178 ltdiv class=form-groupgt179 ltlabel class=control-label col-sm-2 for=input-brakegtBrake levellt

rarr˓labelgt180 ltdiv class=col-sm-10gtltdiv class=form-control slider id=brake gtlt

rarr˓divgt181 ltdivgt182 ltdiv class=form-groupgt183 ltlabel class=control-label col-sm-2 for=input-autorecup_refgtAuto 100

rarr˓ refltlabelgt184 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autorecup_

rarr˓ref gtltdivgt185 ltdivgt186 ltdiv class=form-groupgt187 ltlabel class=control-label col-sm-2 for=input-autorecup_minprcgtAuto

rarr˓min levelltlabelgt188 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autorecup_

rarr˓minprc gtltdivgt (continues on next page)

320 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

189 ltdivgt190 ltdivgt191 ltfieldsetgt192

193 ltfieldset id=part-tsmapngt194 ltlegendgtTorqueSpeed-Map Neutralltlegendgt195 ltdiv class=form-horizontalgt196 ltdiv class=form-groupgt197 ltlabel class=control-label col-sm-2 for=input-tsn_prc1gtTrq level 1

rarr˓ltlabelgt198 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc1 gt

rarr˓ltdivgt199 ltdivgt200 ltdiv class=form-groupgt201 ltlabel class=control-label col-sm-2 for=input-tsn_spd1gtat speed

rarr˓ltlabelgt202 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd1 gt

rarr˓ltdivgt203 ltdivgt204 ltdiv class=form-groupgt205 ltlabel class=control-label col-sm-2 for=input-tsn_prc2gtTrq level 2

rarr˓ltlabelgt206 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc2 gt

rarr˓ltdivgt207 ltdivgt208 ltdiv class=form-groupgt209 ltlabel class=control-label col-sm-2 for=input-tsn_spd2gtat speed

rarr˓ltlabelgt210 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd2 gt

rarr˓ltdivgt211 ltdivgt212 ltdiv class=form-groupgt213 ltlabel class=control-label col-sm-2 for=input-tsn_prc3gtTrq level 3

rarr˓ltlabelgt214 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc3 gt

rarr˓ltdivgt215 ltdivgt216 ltdiv class=form-groupgt217 ltlabel class=control-label col-sm-2 for=input-tsn_spd3gtat speed

rarr˓ltlabelgt218 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd3 gt

rarr˓ltdivgt219 ltdivgt220 ltdiv class=form-groupgt221 ltlabel class=control-label col-sm-2 for=input-tsn_prc4gtTrq level 4

rarr˓ltlabelgt222 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc4 gt

rarr˓ltdivgt223 ltdivgt224 ltdiv class=form-groupgt225 ltlabel class=control-label col-sm-2 for=input-tsn_spd4gtat speed

rarr˓ltlabelgt226 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd4 gt

rarr˓ltdivgt227 ltdivgt228 ltdivgt229 ltfieldsetgt

(continues on next page)

331 TLDR Examples 321

Open Vehicles

(continued from previous page)

230

231 ltfieldset id=part-tsmapbgt232 ltlegendgtTorqueSpeed-Map Brakeltlegendgt233 ltdiv class=form-horizontalgt234 ltdiv class=form-groupgt235 ltlabel class=control-label col-sm-2 for=input-tsb_prc1gtTrq level 1

rarr˓ltlabelgt236 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc1 gt

rarr˓ltdivgt237 ltdivgt238 ltdiv class=form-groupgt239 ltlabel class=control-label col-sm-2 for=input-tsb_spd1gtat speed

rarr˓ltlabelgt240 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd1 gt

rarr˓ltdivgt241 ltdivgt242 ltdiv class=form-groupgt243 ltlabel class=control-label col-sm-2 for=input-tsb_prc2gtTrq level 2

rarr˓ltlabelgt244 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc2 gt

rarr˓ltdivgt245 ltdivgt246 ltdiv class=form-groupgt247 ltlabel class=control-label col-sm-2 for=input-tsb_spd2gtat speed

rarr˓ltlabelgt248 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd2 gt

rarr˓ltdivgt249 ltdivgt250 ltdiv class=form-groupgt251 ltlabel class=control-label col-sm-2 for=input-tsb_prc3gtTrq level 3

rarr˓ltlabelgt252 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc3 gt

rarr˓ltdivgt253 ltdivgt254 ltdiv class=form-groupgt255 ltlabel class=control-label col-sm-2 for=input-tsb_spd3gtat speed

rarr˓ltlabelgt256 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd3 gt

rarr˓ltdivgt257 ltdivgt258 ltdiv class=form-groupgt259 ltlabel class=control-label col-sm-2 for=input-tsb_prc4gtTrq level 4

rarr˓ltlabelgt260 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc4 gt

rarr˓ltdivgt261 ltdivgt262 ltdiv class=form-groupgt263 ltlabel class=control-label col-sm-2 for=input-tsb_spd4gtat speed

rarr˓ltlabelgt264 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd4 gt

rarr˓ltdivgt265 ltdivgt266 ltdivgt267 ltfieldsetgt268

269 ltdivgt270

(continues on next page)

322 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

271 ltdiv id=tab-ramps class=tab-pane section-rampsgt272

273 ltfieldset id=part-rampsglobalgt274 ltlegendgtGeneralltlegendgt275 ltdiv class=form-horizontalgt276 ltdiv class=form-groupgt277 ltlabel class=control-label col-sm-2 for=input-ramplimit_accelgtLimit

rarr˓upltlabelgt278 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramplimit_

rarr˓accel gtltdivgt279 ltdivgt280 ltdiv class=form-groupgt281 ltlabel class=control-label col-sm-2 for=input-ramplimit_decelgtLimit

rarr˓downltlabelgt282 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramplimit_

rarr˓decel gtltdivgt283 ltdivgt284 ltdiv class=form-groupgt285 ltlabel class=control-label col-sm-2 for=input-smoothgtSmoothinglt

rarr˓labelgt286 ltdiv class=col-sm-10gtltdiv class=form-control slider id=smooth gtlt

rarr˓divgt287 ltdivgt288 ltdivgt289 ltfieldsetgt290

291 ltfieldset id=part-rampsgt292 ltlegendgtRamp Speedsltlegendgt293 ltdiv class=form-horizontalgt294 ltdiv class=form-groupgt295 ltlabel class=control-label col-sm-2 for=input-ramp_startgtStart

rarr˓reverseltlabelgt296 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_start

rarr˓gtltdivgt297 ltdivgt298 ltdiv class=form-groupgt299 ltlabel class=control-label col-sm-2 for=input-ramp_accelgtAccelerate

rarr˓ltlabelgt300 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_accel

rarr˓gtltdivgt301 ltdivgt302 ltdiv class=form-groupgt303 ltlabel class=control-label col-sm-2 for=input-ramp_decelgtDecelerate

rarr˓ltlabelgt304 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_decel

rarr˓gtltdivgt305 ltdivgt306 ltdiv class=form-groupgt307 ltlabel class=control-label col-sm-2 for=input-ramp_neutralgtNeutral

rarr˓ltlabelgt308 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_neutral

rarr˓ gtltdivgt309 ltdivgt310 ltdiv class=form-groupgt311 ltlabel class=control-label col-sm-2 for=input-ramp_brakegtBrakelt

rarr˓labelgt312 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_brake

rarr˓gtltdivgt (continues on next page)

331 TLDR Examples 323

Open Vehicles

(continued from previous page)

313 ltdivgt314 ltdivgt315 ltfieldsetgt316

317 ltdivgt318

319 ltdivgt320

321 ltbrgt322 ltdiv class=form-horizontalgt323 ltdiv class=form-groupgt324 ltlabel class=control-label col-sm-2 for=input-labelgtLabelltlabelgt325 ltdiv class=col-sm-10gt326 ltinput type=text class=form-control placeholder=Short button label327 name=label id=input-label value= autocapitalize=none autocorrect=

rarr˓off328 autocomplete=off spellcheck=falsegt329 ltdivgt330 ltdivgt331 ltdiv class=form-groupgt332 ltlabel class=control-label col-sm-2 for=input-titlegtTitleltlabelgt333 ltdiv class=col-sm-10gt334 ltinput type=text class=form-control placeholder=optional titlename335 name=title id=input-title value= autocapitalize=none autocorrect=

rarr˓off336 autocomplete=off spellcheck=falsegt337 ltdivgt338 ltdivgt339 ltdivgt340

341 ltbrgt342 ltdiv class=text-centergt343 ltbutton type=button class=btn btn-default action-resetgtResetltbuttongt344 ltbutton type=button class=btn btn-default action-saveasgtSave asltbuttongt345 ltbutton type=button class=btn btn-primary action-savegtSaveltbuttongt346 ltdivgt347

348 ltformgt349 ltdivgt350 ltdivgt351

352 ltdiv id=key-dialog gt353

354 ltscriptgt355 (function()356

357 init sliders358

359 $(speed)slider( unitkph min6 max120 default80 value80rarr˓checkedfalse )

360 $(warn)slider( unitkph min6 max120 default89 value89 checkedfalserarr˓)

361

362 $(current)slider( unit min10 max123 default100 value100rarr˓checkedfalse )

363 $(torque)slider( unit min10 max130 default100 value100rarr˓checkedfalse )

(continues on next page)

324 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

364 $(power_low)slider( unit min10 max139 default100 value100rarr˓checkedfalse )

365 $(power_high)slider( unit min10 max130 default100 value100rarr˓checkedfalse )

366

367 $(drive)slider( unit min10 max100 default100 value100rarr˓checkedfalse )

368 $(autodrive_ref)slider( unitkW min0 max25 step01 default0 value0rarr˓ checkedfalse )

369 $(autodrive_minprc)slider( unit min0 max100 default0 value0rarr˓checkedfalse )

370

371 $(tsd_prc1)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

372 $(tsd_spd1)slider( unitkph min0 max120 default33 value33rarr˓checkedfalse )

373 $(tsd_prc2)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

374 $(tsd_spd2)slider( unitkph min0 max120 default39 value39rarr˓checkedfalse )

375 $(tsd_prc3)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

376 $(tsd_spd3)slider( unitkph min0 max120 default50 value50rarr˓checkedfalse )

377 $(tsd_prc4)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

378 $(tsd_spd4)slider( unitkph min0 max120 default66 value66rarr˓checkedfalse )

379

380 $(neutral)slider( unit min0 max100 default18 value18rarr˓checkedfalse )

381 $(brake)slider( unit min0 max100 default18 value18 checkedfalse rarr˓)

382 $(autorecup_ref)slider( unitkW min0 max25 step01 default0 value0rarr˓ checkedfalse )

383 $(autorecup_minprc)slider( unit min0 max100 default0 value0rarr˓checkedfalse )

384

385 $(tsn_prc1)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

386 $(tsn_spd1)slider( unitkph min0 max120 default33 value33rarr˓checkedfalse )

387 $(tsn_prc2)slider( unit min0 max100 default80 value80rarr˓checkedfalse )

388 $(tsn_spd2)slider( unitkph min0 max120 default39 value39rarr˓checkedfalse )

389 $(tsn_prc3)slider( unit min0 max100 default50 value50rarr˓checkedfalse )

390 $(tsn_spd3)slider( unitkph min0 max120 default50 value50rarr˓checkedfalse )

391 $(tsn_prc4)slider( unit min0 max100 default20 value20rarr˓checkedfalse )

392 $(tsn_spd4)slider( unitkph min0 max120 default66 value66rarr˓checkedfalse )

393

394 $(tsb_prc1)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

(continues on next page)

331 TLDR Examples 325

Open Vehicles

(continued from previous page)

395 $(tsb_spd1)slider( unitkph min0 max120 default33 value33rarr˓checkedfalse )

396 $(tsb_prc2)slider( unit min0 max100 default80 value80rarr˓checkedfalse )

397 $(tsb_spd2)slider( unitkph min0 max120 default39 value39rarr˓checkedfalse )

398 $(tsb_prc3)slider( unit min0 max100 default50 value50rarr˓checkedfalse )

399 $(tsb_spd3)slider( unitkph min0 max120 default50 value50rarr˓checkedfalse )

400 $(tsb_prc4)slider( unit min0 max100 default20 value20rarr˓checkedfalse )

401 $(tsb_spd4)slider( unitkph min0 max120 default66 value66rarr˓checkedfalse )

402

403

404 $(ramplimit_accel)slider( unit min1 max100 default30 value30rarr˓checkedfalse )

405 $(ramplimit_decel)slider( unit min0 max100 default30 value30rarr˓checkedfalse )

406 $(smooth)slider( unit min0 max100 default70 value70 checkedfalserarr˓)

407

408 $(ramp_start)slider( unitpermil min1 max250 default40 value40rarr˓checkedfalse )

409 $(ramp_accel)slider( unit min1 max100 default25 value25rarr˓checkedfalse )

410 $(ramp_decel)slider( unit min0 max100 default20 value20rarr˓checkedfalse )

411 $(ramp_neutral)slider( unit min0 max100 default40 value40rarr˓checkedfalse )

412 $(ramp_brake)slider( unit min0 max100 default40 value40rarr˓checkedfalse )

413

414 profile handling415

416 const keys = [417 checksum418 speed419 warn420 torque421 power_low422 power_high423 drive424 neutral425 brake426 tsd_spd1427 tsd_spd2428 tsd_spd3429 tsd_spd4430 tsd_prc1431 tsd_prc2432 tsd_prc3433 tsd_prc4434 tsn_spd1435 tsn_spd2436 tsn_spd3

(continues on next page)

326 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

437 tsn_spd4438 tsn_prc1439 tsn_prc2440 tsn_prc3441 tsn_prc4442 tsb_spd1443 tsb_spd2444 tsb_spd3445 tsb_spd4446 tsb_prc1447 tsb_prc2448 tsb_prc3449 tsb_prc4450 ramp_start451 ramp_accel452 ramp_decel453 ramp_neutral454 ramp_brake455 smooth456 brakelight_on457 brakelight_off458 ramplimit_accel459 ramplimit_decel460 autorecup_minprc461 autorecup_ref462 autodrive_minprc463 autodrive_ref464 current465 ]466

467 const scale = 468 autodrive_ref 01469 autorecup_ref 01470 471

472 var profile = 473

474 var plist = [475 label - title Working Set 476 label PWR title Power 477 label ECO title Economy 478 label ICE title Winter 479 ]480

481 load profile list482 var plistloader = loadcmd(config list xrt)then(function(data) 483 var lines = datasplit(n) line i key484 for (i = 0 i lt lineslength i++) 485 line = lines[i]match(profile([0-9]2)([^]) ())486 if (line ampamp linelength == 4) 487 key = Number(line[1])488 if (key lt 1 || key gt 99) continue489 if (plist[key]) plist[key] = 490 plist[key][line[2]||profile] = line[3]491 492 493 )

(continues on next page)

331 TLDR Examples 327

Open Vehicles

(continued from previous page)

494

495 current control rarr power ranges496 function currentControl(on trigger) 497 if (on) 498 $(input-torque input-power_low input-power_high)

rarr˓slider( max 254 )499 else 500 $(input-torque input-power_high)slider( max 130 )501 $(input-power_low)slider( max 139 )502 503 504 $(input-current)on(change function(ev) 505 currentControl(thischecked)506 $(input-torque input-power_low input-power_high)trigger(change)507 )508

509 load profile into sliders510 function loadProfile() 511 currentControl(profile[current] gt= 0)512 $map(profile function(val key) 513 $(input-+key)slider( value (val gt= 0) (val (scale[key]||1)) null

rarr˓checked (val gt= 0) )514 )515 516

517 calculate profile checksum518 function calcChecksum() 519 var checksum i520 checksum = 0x0101521 for (i=1 iltkeyslength i++)522 checksum += profile[keys[i]] + 1523 if ((checksum amp 0x0ff) == 0)524 checksum gtgt= 8525 return (checksum amp 0x0ff) - 1526 527

528 load a base64 string into profile529 function loadBase64(base64) 530 var bin = atob(base64)531 $map(keys function(key i) profile[key] = (bincharCodeAt(i)||0) - 1 )532 if (profile[checksum] == calcChecksum()) 533 loadProfile()534 return true535 else 536 confirmdialog(Profile Error Invalid base64 code (checksum mismatch) [

rarr˓Close])537 return false538 539 540

541 make a base64 string from profile542 function makeBase64() 543 profile[checksum] = calcChecksum()544 var u8 = new Uint8Array(keyslength)545 $map(keys function(key i) u8[i] = profile[key] + 1 )546 return btoa(StringfromCharCodeapply(null u8))547

(continues on next page)

328 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

548

549 load a profile550 function loadKey(key) 551 if (key lt 0 || key gt 99) return552 plistloaderthen(function() 553 $(input-label)val(plist[key] ampamp plist[key][label] || )554 $(input-title)val(plist[key] ampamp plist[key][title] || )555 loadcmd(xrt cfg get + key)fail(function(request textStatus errorThrown) 556 confirmdialog(Load Profile xhrErrorInfo(request textStatus errorThrown)

rarr˓[Close])557 )done(function(res) 558 var base64559 if (resmatch(errori))560 base64 = AQ561 else562 base64 = ressubstr(reslastIndexOf( )+1)563 if (loadBase64(base64)) 564 $(input-key)val(key)565 $(input-base64 input-base64-reset)val(base64)566 $(headkey)text( + key)567 568 )569 )570 571

572 save profile573 function saveKey(key) 574 if (key lt 0 || key gt 99) return575 var base64 = $(input-base64)val()576 label = $(input-label)val()replace(g )577 title = $(input-title)val()replace(g )578 ckey = profile + ((keylt10)0) + key579 var cmd = xrt cfg set + key + + base64 + + label + + title +

rarr˓580 loadcmd(cmd)fail(function(request textStatus errorThrown) 581 confirmdialog(Save Profile xhrErrorInfo(request textStatus errorThrown) [

rarr˓Close])582 )done(function(res) 583 confirmdialog(Save Profile res [Close])584 if (resmatch(errori)) 585 if (key gt 0) 586 if (plist[key]) plist[key] = 587 plist[key][label] = label588 plist[key][title] = title589 590 $(input-key)val(key)591 $(input-base64-reset)val(base64)592 $(headkey)text( + key)593 594 )595 596

597 base64 input598 $(input-base64)on(change function(ev) 599 var base64 = $(this)val() || AQ600 if (loadBase64(base64))601 $(input-base64-reset)val(base64)

(continues on next page)

331 TLDR Examples 329

Open Vehicles

(continued from previous page)

602 )603

604 update profile amp base64 on slider changes605 $(slider-value)on(change function(ev) 606 var key = thisname607 var val = Mathmax(thismin Mathmin(thismax 1thisvalue))608 profile[key] = thischecked (val (scale[key]||1)) -1609 var base64 = makeBase64()610 $(input-base64)val(base64)611 )612

613 prep key dialog614 $(key-dialog)dialog(615 show false616 onShow function(input) 617 var $this = $(this)618 $thisaddClass(loading)619 plistloaderthen(function(data) 620 var curkey = $(input-key)val() || 0 i label title621 $plist = $(ltdiv class=radio-list data-toggle=buttons gt)622 for (i = 0 i lt= Mathmin(99 plistlength + 2) i++) 623 if (plist[i] ampamp (i==0 || plist[i]profile)) 624 label = plist[i]label || -625 title = plist[i]title || (plist[i]profilesubstr(0 10) + )626 else 627 label = -628 title = -new-629 630 $plistappend(ltdiv class=radiogtltlabel class=btngt +631 ltinput type=radio name=key value= + i + gtltspan class=keygt +632 ((i==0) WS ( + ((ilt10)0) + i)) + ltspangt ltkbdgt +633 encode_html(label) + ltkbdgt + encode_html(title) + ltlabelgtltdivgt)634 635 $thisfind(modal-body)append($plist)find(input[value=+curkey+])636 prop(checked true)parent()addClass(active)637 $plist638 on(dblclick labelbtn function(ev) $thisdialog(triggerButton

rarr˓1) )639 on(keypress function(ev) if (evwhich==13) $thisdialog(triggerButton

rarr˓ 1) )640 $thisremoveClass(loading)641 )642 643 onShown function(input) 644 $(this)find(btnactive)focus()645 646 onHide function(input) 647 var $this = $(this) dlg = $thisdata(dialog)648 var key = $thisfind(input[name=key]checked)val()649 if (key == undefined ampamp inputbutton ampamp inputbuttonindex)650 dlgoptionsonActioncall(this key)651 652 )653

654 buttons655 $(action-new)on(click function(ev) 656 $(slider)slider( value null )

(continues on next page)

330 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

657 $(headkey)text(Editor)658 $(input-base64 input-label input-title)val()trigger(change)659 )660 $(action-reset)on(click function(ev) 661 $(input-base64)val($(input-base64-reset)val())trigger(change)662 )663 $(action-load)on(click function(ev) 664 $(key-dialog)dialog(665 show true title Load Profile body 666 buttons [ label Cancel btnClass default label Load btnClass

rarr˓primary ]667 onAction function(key) loadKey(key) 668 )669 )670 $(action-saveas)on(click function(ev) 671 $(key-dialog)dialog(672 show true title Save Profile body 673 buttons [ label Cancel btnClass default label Save btnClass

rarr˓primary ]674 onAction function(key) saveKey(key) 675 )676 )677 $(action-save)on(click function(ev) 678 var key = $(input-key)val()679 if (key === )680 $(action-saveas)trigger(click)681 else682 saveKey(key)683 )684

685 start load profile open load dialog686 if (pageparams[key] == undefined)687 loadKey(pageparams[key])688 else689 $(action-load)trigger(click)690

691 )()692 ltscriptgt

331 TLDR Examples 331

Open Vehicles

33117 Twizy Drivemode Button Editor

This plugin has been added to the Twizy code Itrsquos used here as a more complex example of what can be done byplugins

Itrsquos an editor for the drivemode buttons the Twizy adds to the dashboard for quick tuning profile changes The editorallows to change the layout (number and order of buttons) and the profiles to use

It includes a profile selector built with the dialog widget that retrieves the available profiles from the OVMS configstore

Install not necessary if vehicle Twizy is configured (see ldquoTwizyrdquo menu) If yoursquod like to test this for another vehicleadd as a page plugin eg testdmconfig

drivemode-confightm (hint right click save as)

1 lt--2 Twizy page plugin Drivemode Button Configuration3 Note included in firmware v324 --gt5

6 ltstylegt7 fullscreened panel-single panel-body 8 padding 10px9

10

11 btn-group-lggtbtn12 btn-lg 13 padding 10px 3px14 overflow hidden15 16 loadmenu btn 17 font-weight bold18 19 btn-groupbtn-group-lgexchange 20 width 221

(continues on next page)

332 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

22 editor btnhover 23 background-color e6e6e624 25 editor btn-group-lggtbtn26 editor btn-lg 27 padding 10px 0px28 font-size 15px29 30 editor exchange btn 31 font-weight bold32 33 night editor btn 34 color 00035 background 88836 37 night editor btnfocus38 night editor btnfocus39 night editor btnhover 40 background-color e0e0e041 42

43 radio-list 44 height 313px45 overflow-y auto46 overflow-x hidden47 padding-right 15px48 49 radio-list radio 50 overflow hidden51 52 radio-list key 53 min-width 20px54 display inline-block55 text-align center56 margin 0 10px57 58 radio-list kbd 59 min-width 60px60 display inline-block61 text-align center62 margin 0 20px 0 10px63 64 radio-list radio label 65 width 10066 text-align left67 padding 8px 30px68 69 radio-list radio labelactive 70 background-color 337ab771 color fff72 outline none73 74 radio-list radio labelactive input 75 outline none76 77 night radio-list radio labelhover 78 color fff

(continues on next page)

331 TLDR Examples 333

Open Vehicles

(continued from previous page)

79 80 ltstylegt81

82 ltdiv class=panel panel-primarygt83 ltdiv class=panel-headinggtDrivemode Button Configurationltdivgt84 ltdiv class=panel-bodygt85 ltform action=gt86

87 ltp id=infogtLoading button configurationltpgt88

89 ltdiv id=loadmenu class=btn-group btn-group-justifiedgtltdivgt90 ltdiv id=editor class=btn-group btn-group-justifiedgt91 ltdiv class=btn-group btn-group-lg add backgt92 ltbutton type=button class=btn title=Add buttongtltbuttongt93 ltdivgt94 ltdivgt95

96 ltbrgt97 ltbrgt98 ltdiv class=text-centergt99 ltbutton type=button class=btn btn-default onclick=reloadpage()gtResetlt

rarr˓buttongt100 ltbutton type=button class=btn btn-primary action-savegtSaveltbuttongt101 ltdivgt102

103 ltformgt104 ltdivgt105 ltdiv class=panel-footergt106 lta class=btn btn-sm btn-default target=main href=dashboardgtDashboardltagt107 lta class=btn btn-sm btn-default target=main href=xrtdrivemodegtDrivemodelt

rarr˓agt108 ltdivgt109 ltdivgt110

111 ltdiv id=key-dialog gt112

113 ltscriptgt114 (function()115

116 var $menu = $(loadmenu) $edit = $(editor) $back = $editfind(back)117

118 var pbuttons = [0123]119 var plist = [120 label STD title Standard 121 label PWR title Power 122 label ECO title Economy 123 label ICE title Winter 124 ]125

126 load profile list amp button config127 $(panel)addClass(loading)128 var plistloader = loadcmd(config list xrt)then(function(data) 129 var lines = datasplit(n) line i key130 for (i = 0 i lt lineslength i++) 131 line = lines[i]match(profile([0-9]2)([^]) ())132 if (line ampamp linelength == 4) 133 key = Number(line[1])

(continues on next page)

334 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

134 if (key lt 1 || key gt 99) continue135 if (plist[key]) plist[key] = 136 plist[key][line[2]||profile] = line[3]137 continue138 139 line = lines[i]match(profile_buttons ())140 if (line ampamp linelength == 2) 141 try 142 pbuttons = JSONparse([ + line[1] + ])143 catch (e) 144 consoleerror(e)145 146 147 148 )149

150 prep key dialog151 $(key-dialog)dialog(152 show false153 title Select Profile154 buttons [ label Cancel btnClass default label Select btnClass

rarr˓primary ]155 onShow function(input) 156 var $this = $(this) dlg = $thisdata(dialog)157 $thisaddClass(loading)158 plistloaderthen(function(data) 159 var curkey = dlgoptionskey || 0 i label title160 $plist = $(ltdiv class=radio-list data-toggle=buttons gt)161 for (i = 0 i lt= Mathmin(99 plistlength-1) i++) 162 if (plist[i] ampamp (i==0 || plist[i]profile)) 163 label = plist[i]label || -164 title = plist[i]title || (plist[i]profilesubstr(0 10) + )165 else 166 label = -167 title = -new-168 169 $plistappend(ltdiv class=radiogtltlabel class=btngt +170 ltinput type=radio name=key value= + i + gtltspan class=keygt +171 ((i==0) STD ( + ((ilt10)0) + i)) + ltspangt ltkbdgt +172 encode_html(label) + ltkbdgt + encode_html(title) + ltlabelgtltdivgt)173 174 $thisfind(modal-body)html($plist)find(input[value=+curkey+])175 prop(checked true)parent()addClass(active)176 $plist177 on(dblclick labelbtn function(ev) $thisdialog(triggerButton

rarr˓1) )178 on(keypress function(ev) if (evwhich==13) $thisdialog(triggerButton

rarr˓ 1) )179 $thisremoveClass(loading)180 )181 182 onShown function(input) 183 $(this)find(btnactive)focus()184 185 onHide function(input) 186 var $this = $(this) dlg = $thisdata(dialog)187 var key = $thisfind(input[name=key]checked)val()

(continues on next page)

331 TLDR Examples 335

Open Vehicles

(continued from previous page)

188 if (key == undefined ampamp inputbutton ampamp inputbuttonindex)189 dlgoptionsonActioncall(this key)190 191 )192

193 profile selection194 $(loadmenu)on(click button function(ev) 195 var $this = $(this)196 $(key-dialog)dialog(197 show true198 key $thisval()199 onAction function(key) 200 var prof = plist[key] || 201 $thisval(key)202 $thisattr(title proftitle || )203 $thistext(proflabel || (+((keylt10)0)+key))204 205 )206 )207

208 create buttons209

210 function addButton(key front) 211 var prof = plist[key] || 212 if ($menu[0]childElementCount == 0) 213 $backbefore(214 ltdiv class=btn-group btn-group-lg add frontgt215 ltbutton type=button class=btn title=Add buttongtltbuttongt216 ltdivgt217 ltdiv class=btn-group btn-group-lg removegt218 ltbutton type=button class=btn title=Remove buttongtltbuttongt219 ltdivgt)220 else 221 $backbefore(222 ltdiv class=btn-group btn-group-lg exchangegt223 ltbutton type=button class=btn title=Exchange buttonsgtltbuttongt224 ltdivgt225 ltdiv class=btn-group btn-group-lg removegt226 ltbutton type=button class=btn title=Remove buttongtltbuttongt227 ltdivgt)228 229 var $btn = $(230 ltdiv class=btn-group btn-group-lggt231 ltbutton type=button value=key class=btn btn-default title=titlegt

rarr˓labelltbuttongt232 ltdivgt233 replace(key key)234 replace(title encode_html(proftitle || ))235 replace(label encode_html(proflabel || +((keylt10)0)+key)))236 if (front)237 $menuprepend($btn)238 else239 $menuappend($btn)240 241

242 plistloaderthen(function() 243 var key prof

(continues on next page)

336 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

244 for (var i = 0 i lt pbuttonslength i++) 245 addButton(pbuttons[i])246 247 $(panel)removeClass(loading)248 $(info)text(Click button to select profile)249 )250

251 editor buttons252 $(editor)on(click add btn function(ev) 253 addButton(0 $(this)parent()hasClass(front))254 )on(click remove btn function(ev) 255 var $this = $(this) pos = $editfind(btn)index(this) gtgt 1256 $($menuchildren()get(pos))detach()257 if (pos gt 0 || $menu[0]childElementCount == 0)258 $thisparent()prev()detach()259 else if ($menu[0]childElementCount = 0)260 $thisparent()next()detach()261 $thisparent()detach()262 )on(click exchange btn function(ev) 263 var pos = $editfind(btn)index(this) gtgt 1264 if (pos gt 0) $($menuchildren()get(pos))insertBefore($($menuchildren()get(pos-

rarr˓1)))265 )266

267 save268 $(action-save)on(click function(ev) 269 pbuttons = []270 $menufind(btn)each(function() pbuttonspush(thisvalue) )271 loadcmd(config set xrt profile_buttons + pbuttonstoString())272 fail(function(request textStatus errorThrown) 273 confirmdialog(Save Configuration xhrErrorInfo(request textStatus

rarr˓errorThrown) [Close])274 )275 done(function(res) 276 confirmdialog(Save Configuration res [Close])277 )278 )279

280 )()281 ltscriptgt

332 Installing Plugins

The framework supports installing user content as pages or extensions to pages To install an example

1 Menu Config rarr Web Plugins

2 Add plugin type ldquoPagerdquo name eg ldquodevmetricsrdquo (used as the file name in storeplugin)

3 Save rarr Edit

4 Set page to eg ldquousrdevmetricsrdquo label to eg ldquoDev Metricsrdquo

5 Set the menu to eg ldquoToolsrdquo and auth to eg ldquoNonerdquo

6 Paste the page source into the content area

332 Installing Plugins 337

Open Vehicles

7 Save rarr the page is now accessible in the ldquoToolsrdquo menu

Hint use the standard editor (tools menu) in a second session to edit a plugin repeatedly during test development

333 Basics

The OVMS web framework is based on HTML 5 Bootstrap 3 and jQuery 3 Plenty documentation and guides onthese basic web technologies is available on the web a very good resource is w3schoolscom

For charts the framework includes Highcharts 6 Info and documentation on this is available on Highchartscom

The framework is ldquoAJAXrdquo based The index page loads the framework assets and defines a default container structureincluding a menu and a main container Content pages are loaded into the main container The window URLincludes the page URL after the hash mark

bull httpovmslocalstatus ndash this loads page status into main

bull httpovmslocaldashboardnm=1 ndash this loads the dashboard and activates night mode

Links and forms having id targets are automatically converted to AJAX by the framework

bull lta href=editpath=sdindextxt target=maingtEdit indextxtltagt ndash loadthe editor

Pages can be loaded outside the framework as well (eg httpovmslocalstatus) See index source onframework scripts and styles to include if yoursquod like to design standalone pages using the framework methods

If file system access is enabled all URLs not handled by the system or a user plugin (see below) are mapped onto thefile system under the configured web root Of course files can be loaded into the framework as well For example ifthe web root is sd (default)

bull httpovmslocalmypagehtm ndash load file sdmypagehtm into main

bull httptest1locallogs ndash load directory listing sdlogs into main

Important Note the framework has a global shared context (ie the window object) To avoid polluting the globalcontext with local variables good practice is to wrap your local scripts into closures Pattern

ltscriptgt(function()

insert your code here )()ltscriptgt

334 Authorization

Page access can be restricted to authorized users either session based or per access File access can be restricted usingdigest authentication

The module password is used for all authorizations A user account or API key administration is not yet included themain username is admin

To create a session call the login page and store the resulting cookie

1 curl -c auth -b auth http19216841login -d username=admin -dpassword=

2 curl -c auth -b auth http19216841apiexecutecommand=xrt+cfg+info

338 Chapter 33 Web Framework amp Plugins

Open Vehicles

To issue a single call eg to execute a command from a Wifi button supply the password as apikey

bull curl http19216841apiexecuteapikey=passwordampcommand=xrt+cfg+info

bull curl http19216841apiexecuteapikey=passwordamptype=jsampcommand=print(Duktapeversion)

335 Web UI Development Framework

To simplify and speed up UI and plugin development you can simply run a local web server from the dev directoryof the ovms_webserver component source

Preparation create your local git clone if you donrsquot have one already

gt cd ~gt git clone httpsgithubcomopenvehiclesOpen-Vehicle-Monitoring-System-3git

Local web server options List of static web servers

Example

gt cd ~Open-Vehicle-Monitoring-System-3vehicleOVMSV3componentsovms_webserverdevgt python3 -m httpserver 8000Serving HTTP on 0000 port 8000 (http00008000)

Now open the development framework in your browser at URI httplocalhost8000 If that doesnrsquot workcheck your firewall settings for port 8000 on localhost

You should see the examples home Edit indexhtm to add custom menus edit homehtm to add custom homebuttons

Hint to test your plugin for mobile devices use the mobile emulation mode of your browserrsquos development toolkitMobile mode allows to test small screen resolutions rotation and touch events

A static local HTTP server allows to use all frontend features but cannot emulate the backend API (commandscriptexecution) If using a CGI capable HTTP server you can also add a proxy handler for apiexecute that forwardsthe requests to your module by HTTP or SSH

If you want to add your results to a C++ module use the tools mksrc and mksrcf to convert your HTML files intoC++ compatible strings mksrc is meant for static strings mksrcf for strings with printf style placeholders

335 Web UI Development Framework 339

Open Vehicles

340 Chapter 33 Web Framework amp Plugins

CHAPTER 34

Scripting

341 Example Foglight

This is an example for combining a script module implementing some functional extension with a web plugin toprovide a user interface

The plugin realizes a fog light with automatic speed adaption ie the light will be turned off above a configurablespeed and on again when the vehicle slows down again It also switches off automatically when the vehicle is parked

The plugin shows how to

bull read custom config variables

bull use module state variables

341

Open Vehicles

bull react to events

bull send custom events

bull read metrics

bull execute system commands

bull provide new commands

bull provide a web UI

3411 Installation

bull Save foglightjs as storescriptslibfoglightjs (add the lib directory as necessary)

bull Add foglighthtm as a web hook type plugin at page dashboard hook bodypre

bull Execute script eval foglight = require(libfoglight)

Optionally

bull To test the module execute script eval foglightinfo() ndash it should print config and state

bull To automatically load the module on boot add the line foglight = require(libfoglight) tostorescriptsovmsmainjs

3412 Commands Functions

The module provides two public API functions

Function Descriptionfoglightset(onoff) switch fog light on (1) off (0)foglightinfo() output config amp state in JSON format

To call these from a shell use script eval Example

bull script eval foglightset(1)

3413 Configuration

Wersquoll add the configuration for this to the vehicle section

Config Default Descriptionfoglightport 1 EGPIO output port numberfoglightauto no yes = speed automationfoglightspeedon 45 auto turn on below this speedfoglightspeedoff 55 auto turn off above this speed

Note You can add arbitrary config instances to defined sections simply by setting them config set vehiclefoglightauto yes

342 Chapter 34 Scripting

Open Vehicles

Update Beginning with firmware release 32009 a general configuration section usr is provided for plugins Werecommend using this for all custom parameters now Keep in mind to prefix all instances introduced by the pluginname so your plugin can nicely coexist with others

To store the config for simple amp quick script access and implement the defaults we introduce an internal modulemember object cfg

Listing 1 Module Plugin

28 var cfg = 29 foglightport 130 foglightauto no31 foglightspeedon 4532 foglightspeedoff 5533

By foglight = require() the module is added to the global name space as a javascript object This objectcan contain any internal standard javascript variables and functions Internal members are hidden by default if youwould like to expose the cfg object you would simply add a reference to it to the exports object as is done belowfor the API methods

Reading OVMS config variables from a script currently needs to be done by executing config list and parsingthe output This is done by the readconfig() function

42 function readconfig() 43 var cmdres lines cols i44 cmdres = OvmsCommandExec(config list vehicle)45 lines = cmdressplit(n)46 for (i=0 iltlineslength i++) 47 if (lines[i]indexOf(foglight) gt= 0) 48 cols = lines[i]substr(2)split( )49 cfg[cols[0]] = cols[1]50 51

Update OVMS release 32009 adds the OvmsConfigGetValues() API To use this we would now omit theldquofoglightrdquo prefix from our cfg properties Reading the foglight configuration can then be reduced to a single line

Objectassign(cfg OvmsConfigGetValues(vehicle foglight))

3414 Listen to Events

The module needs to listen to three events

bull configchanged triggers reloading the configuration

bull ticker1 is used to check the speed once per second

bull vehicleoff automatically also turns off the fog light

The per second ticker is only necessary when the speed adaption is enabled so we can use this to show how todynamically add and remove event handlers through the PubSub API

341 Example Foglight 343

Open Vehicles

Listing 2 Module Plugin

52 update ticker subscription53 if (cfg[foglightauto] == yes ampamp stateticker) 54 stateticker = PubSubsubscribe(ticker1 checkspeed)55 else if (cfg[foglightauto] = yes ampamp stateticker) 56 PubSubunsubscribe(stateticker)57 stateticker = false58

state is another internal object for our state variables

3415 Send Events

Sending custom events is a lightweight method to inform the web UI (or other plugins) about simple state changes Inthis case wersquod like to inform listeners when the fog light actually physically is switched on or off so the web UI cangive visual feedback to the driver on this

Beginning with firmware release 32006 there is a native API OvmsEventsRaise() available to send events

Before 32006 we simply use the standard command event raise

Listing 3 Module Plugin

61 EGPIO port control62 function toggle(onoff) 63 if (stateport = onoff) 64 OvmsCommandExec(egpio output + cfg[foglightport] + + onoff)65 stateport = onoff66 OvmsCommandExec(event raise usrfoglight + (onoff on off))67 68

The web plugin subscribes to the foglight events just as to any system event

Listing 4 Web Plugin

64 Listen to foglight events65 $(foglight)on(msgevent function(e event) 66 if (event == usrfoglighton)67 update( state port 1 )68 else if (event == usrfoglightoff)69 update( state port 0 )70 else if (event == vehicleoff) 71 update( state on 0 )72 $(action-foglight-output)empty()73 74 )

Note You can raise any event you like but you shouldnrsquot raise system events without good knowledge of theireffects Event codes are simply strings so yoursquore free to extend them Use the prefix usr for custom events to avoidpotential conflicts with future system event additions

344 Chapter 34 Scripting

Open Vehicles

3416 Read Metrics

Reading metrics is straight forward through the OvmsMetrics API

Listing 5 Module Plugin

74 var speed = OvmsMetricsAsFloat(vpspeed)

Use Value() instead of AsFloat() for non-numerical metrics

Note You cannot subscribe to metrics changes directly (yet) Metrics can change thousands of times per secondwhich would overload the scripting capabilities To periodically check a metric register for a ticker event (as shownhere)

3417 Provide Commands

To add commands simply expose their handler functions through the exports object By this users will be able tocall these functions using the script eval command from any shell or from any script by referencing them viathe global module variable foglight in our case

Listing 6 Module Plugin

99 API method foglightinfo()100 exportsinfo = function() 101 JSONprint( cfg cfg state state )102

JSONprint() is a convenient way to communicate with a web plugin as that wonrsquot need to parse some potentiallyambigous textual output but can simply use JSONparse() to read it into a variable

Listing 7 Web Plugin

82 Init amp install83 $(main)one(load function(ev) 84 loadcmd(script eval foglightinfo())then(function(output) 85 update(JSONparse(output))

Note Keep in mind commands should always output some textual response indicating their action and result If acommand does nothing it should tell the user so If a command is not intended for shell use it should still providesome clue about this when called from the shell

3418 Module Plugin

foglightjs (hint right click save as)

1 2 storescriptslibfoglightjs3 4 Module plugin5 Foglight control with speed adaption and auto off on vehicle off

(continues on next page)

341 Example Foglight 345

Open Vehicles

(continued from previous page)

6 7 Version 10 Michael Balzer ltdexterdexters-webdegt8 9 Enable

10 - install at above path11 - add to storescriptsovmsmainjs12 foglight = require(libfoglight)13 - script reload14 15 Config16 - vehicle foglightport EGPIO output port number17 - vehicle foglightauto yes = speed automation18 - vehicle foglightspeedon auto turn on below this speed19 - vehicle foglightspeedoff auto turn off above this speed20 21 Usage22 - script eval foglightset(1) toggle foglight on23 - script eval foglightset(0) toggle foglight off24 - script eval foglightinfo() show config amp state (JSON)25 26 27

28 var cfg = 29 foglightport 130 foglightauto no31 foglightspeedon 4532 foglightspeedoff 5533 34

35 var state = 36 on 0 foglight onoff37 port 0 current port output state38 ticker false ticker subscription39 40

41 Read config42 function readconfig() 43 var cmdres lines cols i44 cmdres = OvmsCommandExec(config list vehicle)45 lines = cmdressplit(n)46 for (i=0 iltlineslength i++) 47 if (lines[i]indexOf(foglight) gt= 0) 48 cols = lines[i]substr(2)split( )49 cfg[cols[0]] = cols[1]50 51 52 update ticker subscription53 if (cfg[foglightauto] == yes ampamp stateticker) 54 stateticker = PubSubsubscribe(ticker1 checkspeed)55 else if (cfg[foglightauto] = yes ampamp stateticker) 56 PubSubunsubscribe(stateticker)57 stateticker = false58 59 60

61 EGPIO port control62 function toggle(onoff)

(continues on next page)

346 Chapter 34 Scripting

Open Vehicles

(continued from previous page)

63 if (stateport = onoff) 64 OvmsCommandExec(egpio output + cfg[foglightport] + + onoff)65 stateport = onoff66 OvmsCommandExec(event raise usrfoglight + (onoff on off))67 68 69

70 Check speed71 function checkspeed() 72 if (stateon)73 return74 var speed = OvmsMetricsAsFloat(vpspeed)75 if (speed lt= cfg[foglightspeedon])76 toggle(1)77 else if (speed gt= cfg[foglightspeedoff])78 toggle(0)79 80

81 API method foglightset(onoff)82 exportsset = function(onoff) 83 if (onoff) 84 stateon = 185 if (cfg[foglightauto] == yes) 86 checkspeed()87 print(Foglight AUTO moden)88 else 89 toggle(1)90 print(Foglight ONn)91 92 else 93 stateon = 094 toggle(0)95 print(Foglight OFFn)96 97 98

99 API method foglightinfo()100 exportsinfo = function() 101 JSONprint( cfg cfg state state )102 103

104 Init105 readconfig()106 PubSubsubscribe(configchanged readconfig)107 PubSubsubscribe(vehicleoff function() exportsset(0) )

3419 Web Plugin

foglighthtm (hint right click save as)

1 lt--2 foglighthtm Web plugin for hook dashboardbodypre3 - add button to activatedeactivate foglight4 - add indicator to show current foglight state5

(continues on next page)

341 Example Foglight 347

Open Vehicles

(continued from previous page)

6 Requires module plugin foglightjs7

8 Version 10 Michael Balzer ltdexterdexters-webdegt9 --gt

10

11 ltstylegt12 foglight 13 margin 10px 8px 014 15 foglight indicator gt label 16 font-size 13017 line-height 16018 margin 0px19 padding 10px20 display block21 border-radius 50px22 23 ltstylegt24

25 ltdiv class=receiver id=foglight style=displaynonegt26 ltformgt27 ltdiv class=form-groupgt28 ltdiv class=col-xs-6gt29 ltdiv class=indicator indicator-foglightgt30 ltspan class=label label-defaultgtFOGLIGHTltspangt31 ltdivgt32 ltdivgt33 ltdiv class=col-xs-6gt34 ltdiv class=btn-group btn-group-justified action-foglight-set data-toggle=

rarr˓buttonsgt35 ltlabel class=btn btn-default action-foglight-0gtltinput type=radio name=

rarr˓foglight value=0gtOFFltlabelgt36 ltlabel class=btn btn-default action-foglight-1gtltinput type=radio name=

rarr˓foglight value=1gtONAUTOltlabelgt37 ltdivgt38 ltsamp id=action-foglight-output class=text-centergtltsampgt39 ltdivgt40 ltdivgt41 ltformgt42 ltdivgt43

44 ltscriptgt45 (function()46

47 var foglight = cfg state on 0 port 0 48 var $indicator = $(foglight indicator-foglight gt label)49 var $actionset = $(foglight action-foglight-set gt label)50

51 State amp UI update52 function update(data) 53 $extend(true foglight data)54 update indicator55 if (foglightstateport)56 $indicatorremoveClass(label-default)addClass(label-danger)57 else58 $indicatorremoveClass(label-danger)addClass(label-default)59 update buttons

(continues on next page)

348 Chapter 34 Scripting

Open Vehicles

(continued from previous page)

60 $actionsetremoveClass(active)61 $actionsetfind(input[value=+foglightstateon+])prop(checked true)

rarr˓parent()addClass(active)62 63

64 Listen to foglight events65 $(foglight)on(msgevent function(e event) 66 if (event == usrfoglighton)67 update( state port 1 )68 else if (event == usrfoglightoff)69 update( state port 0 )70 else if (event == vehicleoff) 71 update( state on 0 )72 $(action-foglight-output)empty()73 74 )75

76 Button action77 $(foglight action-foglight-set input)on(change function(e) 78 foglightstateon = $(this)val()79 loadcmd(script eval foglightset(+foglightstateon+) action-foglight-

rarr˓output)80 )81

82 Init amp install83 $(main)one(load function(ev) 84 loadcmd(script eval foglightinfo())then(function(output) 85 update(JSONparse(output))86 $(foglight)appendTo(panel-dashboard panel-body)show()87 )88 )89

90 )()91 ltscriptgt

341 Example Foglight 349

Open Vehicles

350 Chapter 34 Scripting

CHAPTER 35

CANopen

351 CANopen Basics

3511 Communication Objects

A CANopen network consists of ldquomastersrdquo and ldquoslavesrdquo masters are clients slaves are servers At most one mastermay be active at a time

CANopen supports addressing of up to 127 slaves on a bus using node IDs 1-127 Node address 0 is used for broadcaststo all nodes Node addressing is simply mapped onto CAN IDs by adding the node id to a base ID

The CANopen protocol mainly consists of

bull PDO (process data objects)

bull SDO (service data objects)

bull NMT (network management)

bull SYNC (synchronisation)

bull EMCY (emergency events)

PDO are regular normally periodical status update frames for example sensor data You can log them using theCAN monitor (can log start monitor ) PDOs can be sent at any CAN ID except those reserved forother CANopen services

SDO are memory registers of nodes that can be read and written by masters on request SDO requests are normally sentat ID 0x600 + nodeid responses at ID 0x580 + nodeid SDOs are addressed by a 16 bit index + 8 bit subindex Reg-isters and data types for a given device are documented by the device specific object dictionary normally representedas an EDS (electronic data sheet) file

NMT are short datagrams to control node startup shutdown Therersquos a special node state ldquopre-operationalrdquo allowingaccess to all operation and communication parameters of a node in a standardized way NMT requests are sent at ID0x000 responses and unsolicited updates (aka heartbeats) are sent at ID 0x700 + nodeid with length 1

SYNC messages are datagrams of length 0 normally sent at ID 0x080

351

Open Vehicles

EMCY messages are sent if a node encounters some kind of alert or warning condition they are normally sent at ID0x080 + nodeid with a length of 8 bytes

CAN IDs Communication objects0x000 NMT requests0x080 SYNC0x081 - 0x0FF EMCY0x581 - 0x5FF SDO responses0x601 - 0x67F SDO requests0x701 - 0x77F NMT responses heartbeats

So if any of these IDs look familiar to you chances are yoursquove got a CANopen network

Note CANopen coexists nicely with OBD-II and often does in a vehicle (ie Renault Twizy) OBD-II devicesnormally are addressed at IDs gt 0x780 so are outside the CANopen ID range Even if they use non-standard IDs thedevices normally will detect and ignore frames not matching their protocol

3512 SDO Addresses

The SDO address space layout is standardized

Index (hex) Object0000 not used0001-001F Static Data Types0020-003F Complex Data Types0040-005F Manufacturer Specific Complex Data Types0060-007F Device Profile Specific Static Data Types0080-009F Device Profile Specific Complex Data Types00A0-0FFF Reserved for further use1000-1FFF Communication Profile Area2000-5FFF Manufacturer Specific Profile Area6000-9FFF Standardised Device Profile AreaA000-BFFF Standardised Interface Profile AreaC000-FFFF Reserved for further use

See CiA DS301 for details on standard SDOs

For example a device shall tell about the PDOs it transmits or listens to their IDs update frequency and contentstructure at SDO registers 1400-1BFF This is mandatory in theory but real devices may not fully comply to that rule

CANopen compliant standard device types like motor controllers need to implement some standard profile registersSee CiA DS401 for the generic IO device class definition and CiA DS402 for motor controllers

Most devices will require some kind of login before allowing you to change operational parameters This is also doneusing SDO writes but there is no standard for this so yoursquoll need to dig into the device documentation

Of course therersquos a lot more on CANopen but this should get you going

3513 CAN in Automation

More info on the standard and specific device profiles can be found on the CiA website

352 Chapter 35 CANopen

Open Vehicles

httpswwwcan-ciaorg

CAN in Automation (CiA) is the international usersrsquo and manufacturersrsquo group for the CAN network (Controller AreaNetwork) internationally standardized in the ISO 11898 series The nonprofit association was established in 1992The aim is to provide an unbiased platform for future developments of the CAN protocol and to promote the image ofthe CAN technology

352 How to detect and identify CANopen nodes

So yoursquove got a CAN bus with some devices but you donrsquot know which of them speaks ldquoCANopenrdquo if any TheOVMS v3 will help you to detect them and open their CANs )

3521 Before you begin

you need to activate the CAN bus(es) yoursquore going to use As a CANopen master needs to write to the networkyou need to start the interfaces in active mode ie

OVMS can can1 start active 500000OVMS can can2 start active 125000

and then start the CANopen master for the bus(es) ie

OVMS copen can1 startOVMS copen can2 start

3522 Detecting CANopen nodes

The ldquoopenrdquo in ldquoCANopenrdquo means any implementation can decide how much of the standard it implements There aresome few mandatory features though a CANopen slave has to implement if it wants to comply with the standard

The mandatory features helping to detect and identify CANopen nodes on a CAN bus are

bull NMT (network management) especially RESET and PREOP

bull NMT bootup event messages

bull Standard SDO access in pre-operational mode

If yoursquove got CANopen nodes on a bus even silent ones issuing copen nmt reset will tell all of them toreboot and as bootup messages are mandatory you will see them in the OVMS log output like this

I (162904) canopen can1 node 1 new state Booting

The OVMS CANopen master continously monitors the network for NMT and EMCY messages After bootup of allnodes you can get a list of all nodes that have been detected by issuing metrics list co

OVMS metrics list cococan1nd1emcycodecocan1nd1emcytypecocan1nd1state Operational

Note if you request a reset nodes may decide to boot into pre-operational state That may produce some errormessages Donrsquot worry you can resolve this anytime by issuing copen nmt start

352 How to detect and identify CANopen nodes 353

Open Vehicles

3523 Identifying CANopen nodes

In pre-operational state a CANopen node must be accessible at the CANopen default IDs That means if the nodesupports SDO access we can query some standard attributes from it

Thatrsquos what copen info and copen scan do

bull copen info queries the standard device attributes from a specific node

bull copen scan queries all 127 node IDs

Caution There may be non-CANopen devices on the bus producing regular data frames at CANopen responseIDs andor reading and possibly misinterpreting CANopen requests sent to node IDs not planned by the manufac-turer Chances are low this triggers problems but you should be ready to switch off the vehicle when doing a scanndash just in case

A complete scan takes about 20 seconds A typical scan could look like this

OVMS level debug canopenOVMS copen can1 scanScan 1-127Node 1

Device type 0x00000000Error state 0x00Vendor ID 0x0000001eProduct 0x0712302dRevision 0x00010019SN 0x47c5Device name Gen4 (Renault Twizy)11 November 2011 12HW version 0x00000003SW version 07120001

Node 23 SDO access failedNode 25 SDO access failedNode 27 SDO access failedNode 30 SDO access failedNode 87 SDO access failedDoneD (227994) canopen ReadSDO 23 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (228194) canopen ReadSDO 25 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (228444) canopen ReadSDO 27 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (228844) canopen ReadSDO 30 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (238384) canopen ReadSDO 87 0x100000 InitUpload failed CANopen error coderarr˓0xffffffff

This means one CANopen node was found and some non-CANopen frames were received on IDs 0x580 +23 +25+27 +30 and +87

3524 Great What now

As you now know therersquos a CANopen node you can look for documentation on it You can also try to access moredefault SDOs to see if you can control and configure the node

354 Chapter 35 CANopen

Open Vehicles

bull If yoursquore lucky the device will provide its own EDS file at SDO 102100 You can check that by issuing

OVMS copen ltbusgt readsdo ltnodeidgt 1021 0

bull Check out the CiA specifications for CANopen standards for example

ndash DS301 for details on general standard SDOs

ndash DS401 for the generic IO device class definition

ndash DS402 for motor controller SDOs

bull Look up the manufacturer of your device by itrsquos vendor ID

httpswwwcan-ciaorgservicescanopen-vendor-id

bull Contact the manufacturer of your device for specific documentation and EDS files

353 CANopen Shell Commands

Show status report

copen status

Start stop workers

copen ltbusgt startcopen ltbusgt stop

bull stop will fail if clients are still running

Send NMT commands

copen ltbusgt nmt ltstart|stop|preop|reset|commresetgt [id=0] [timeout_ms=0]

bull id 0 = broadcast

bull timeout gt 0 wait for state change (heartbeat) 3 tries Note state change response is not a mandatoryCANopen feature

Read SDO

copen ltbusgt readsdo ltidgt ltindex_hexgt ltsubindex_hexgt [timeout_ms=50]

bull index amp subindex hexadecimal without ldquo0xrdquo or ldquohrdquo

bull defaults to 3 tries on timeout

Write SDO

copen ltbusgt writesdo ltidgt ltindex_hexgt ltsubindex_hexgt ltvaluegt [timeout_ms=50]

bull index amp subindex hexadecimal without ldquo0xrdquo or ldquohrdquo

bull value prefix ldquo0xrdquo = hex else decimal string if no decimal

bull defaults to 3 tries on timeout

Show node core attributes

353 CANopen Shell Commands 355

Open Vehicles

copen ltbusgt info ltidgt [timeout_ms=50]

bull prints device type error register device name etc

bull Note some attributes read are optional and may be emptyzero

Scan bus for nodes

copen ltbusgt scan [[startid=1][-][endid=127]] [timeout_ms=50]

bull loops ldquoinfordquo over multiple node ids (default all)

bull Note a full scan with default timeout takes ~20 seconds

354 CANopen API Usage

3541 Synchronous API

The synchronous use is very simple all you need is a CANopenClient instance

On creation the client automatically connects to the active CANopen worker or starts a new worker instance if neces-sary

The CANopenClient methods will block until the job is done (or has failed) Job results andor error details arereturned in the caller provided job

Caution Do not make synchronous calls from code that may run in a restricted context eg within a metricupdate handler Avoid using synchronous calls from time critical code eg a CAN or event handler

Example

include canopenh

find CAN interfacecanbus bus = (canbus) MyPcpAppFindDeviceByName(can1) or simply use m_can1 if youre a vehicle subclass

create CANopen clientCANopenClient client(bus)

a CANopen job holds request and response dataCANopenJob job

read value from node 1 SDO 0x100800uint32_t valueif (clientReadSDO(ampjob 1 0x1008 0x00 (uint8_t)ampvalue sizeof(value)) == COR_OK) read result is now in value

start node 2 wait for presenceif (clientSendNMT(ampjob 2 CONC_Start true) == COR_OK)

node 2 is now started

(continues on next page)

356 Chapter 35 CANopen

Open Vehicles

(continued from previous page)

write value into node 3 SDO 0x234518if (clientWriteSDO(ampjob 3 0x2345 0x18 (uint8_t)ampvalue 0) == COR_OK)

value has now been written into register 0x234518

Main API methods

SendNMT send NMT request and optionally wait for NMT state change

aka heartbeat message

Note NMT responses are not a part of the CANopen NMT protocol and

sending heartbeat NMT state updates is optional for CANopen nodes

If the node sends no state info waiting for it will result in timeout

even though the state has in fact changed -- theres no way to know

if the node doesnt tell

CANopenResult_t SendNMT(CANopenJobamp job

uint8_t nodeid CANopenNMTCommand_t commandbool wait_for_state=false int resp_timeout_ms=1000 int max_tries=3)

ReceiveHB wait for next heartbeat message of a node

return state received

Use this to read the current state or synchronize to the heartbeat

Note heartbeats are optional in CANopen

CANopenResult_t ReceiveHB(CANopenJobamp job

uint8_t nodeid CANopenNMTState_t statebuf=NULLint recv_timeout_ms=1000 int max_tries=1)

ReadSDO read bytes from SDO server into buffer

- reads data into buf (up to bufsize bytes)

- returns data length read in jobsdoxfersize

- and data length available in jobsdocontsize (if known)

- remaining buffer space will be zeroed

- on result COR_ERR_BufferTooSmall the buffer has been filled up to bufsize

- on abort the CANopen error code can be retrieved from jobsdoerror

Note result interpretation is up to caller (check device object dictionary

for data types amp sizes) As CANopen is little endian as ESP32 we dont

need to check lengths on numerical results ie anything from int8_t to

uint32_t can simply be read into a uint32_t buffer

CANopenResult_t ReadSDO(CANopenJobamp job

uint8_t nodeid uint16_t index uint8_t subindex uint8_t buf size_t bufsizeint resp_timeout_ms=50 int max_tries=3)

WriteSDO write bytes from buffer into SDO server

- sends bufsize bytes from buf

- or 4 bytes from buf if bufsize is 0 (use for integer SDOs of unknown type)(continues on next page)

354 CANopen API Usage 357

Open Vehicles

(continued from previous page)

- returns data length sent in jobsdoxfersize

- on abort the CANopen error code can be retrieved from jobsdoerror

Note the caller needs to know data type amp size of the SDO register (check

device object dictionary) As CANopen servers normally are intelligent

anything from int8_t to uint32_t can simply be sent as a uint32_t with

bufsize=0 the server will know how to convert it

CANopenResult_t WriteSDO(CANopenJobamp job

uint8_t nodeid uint16_t index uint8_t subindex uint8_t buf size_t bufsizeint resp_timeout_ms=50 int max_tries=3)

If you want to create custom jobs use the low level method ExecuteJob() to execute them

3542 Asynchronous API

The CANopenAsyncClient class provides the asynchronous interface and the response queue

To use the asynchronous API you need to handle asynchronous responses which normally means adding a dedicatedtask for this A minimal handling would be to simply discard the responses (just empty the queue) if you donrsquot needto care about the results

Example

Instantiate the async client for a CAN bus and a queue size like this

CANopenAsyncClient m_async(m_can1 50)

Example response handler task

void MyAsyncTask()

CANopenJob jobwhile (true) if (m_asyncReceiveDone(job portMAX_DELAY) = COR_ERR_QueueEmpty)

process job results

Sending requests is following the same scheme as with the synchronous API Standard result code is COR_WAIT anerror may occur if the queue is full

if (m_asyncWriteSDO(m_nodeid index subindex (uint8_t)value 0) = COR_WAIT) handle error

Main API methods

The API methods are similar to the synchronous methods (see above)

358 Chapter 35 CANopen

Open Vehicles

CANopenResult_t SendNMT(uint8_t nodeid CANopenNMTCommand_t commandbool wait_for_state=false int resp_timeout_ms=1000 int max_tries=3)

CANopenResult_t ReceiveHB(uint8_t nodeid CANopenNMTState_t statebuf=NULLint recv_timeout_ms=1000 int max_tries=1)

CANopenResult_t ReadSDO(uint8_t nodeid uint16_t index uint8_t subindexuint8_t buf size_t bufsizeint resp_timeout_ms=100 int max_tries=3)

CANopenResult_t WriteSDO(uint8_t nodeid uint16_t index uint8_t subindexuint8_t buf size_t bufsizeint resp_timeout_ms=100 int max_tries=3)

CANopenJob objects are created automatically by these methods Jobs done need to be fetched by loopingReceiveDone() until it returns COR_ERR_QueueEmpty

If you want to create custom jobs use the low level method SubmitJob() to add them to the worker queue

3543 Error Handling

If an error occurs it will be given as a CANopenResult_t other than COR_OK or COR_WAIT either by a methodresult or by the CANopenJobresult field

Result codes are

COR_OK = 0

API levelCOR_WAIT job waiting to be processedCOR_ERR_UnknownJobTypeCOR_ERR_QueueFullCOR_ERR_QueueEmptyCOR_ERR_NoCANWriteCOR_ERR_ParamRangeCOR_ERR_BufferTooSmall

Protocol levelCOR_ERR_TimeoutCOR_ERR_SDO_AccessCOR_ERR_SDO_SegMismatch

General purpose application levelCOR_ERR_DeviceOffline = 0x80COR_ERR_UnknownDeviceCOR_ERR_LoginFailedCOR_ERR_StateChangeFailed

Additionally if an SDO readwrite error occurs an abortion error code may be given by the slave These codes followthe CANopen standard and may be extended by device specific codes

To translate a CANopenResult_t andor a known SDO abort code into a string use the CANopen class utilitymethods

stdstring GetAbortCodeName(const uint32_t abortcode)stdstring GetResultString(const CANopenResult_t result)

(continues on next page)

354 CANopen API Usage 359

Open Vehicles

(continued from previous page)

stdstring GetResultString(const CANopenResult_t result const uint32_t abortcode)stdstring GetResultString(const CANopenJobamp job)

Example

if (jobresult = COR_OK) ESP_LOGE(TAG Result for s sCANopenGetJobName(job)c_str()CANopenGetResultString(job)c_str())

3544 Custom Address Schemes

The standard clients use the CiA DS301 default IDs for node addressing ie

NMT request rarr 0x000NMT response rarr 0x700 + nodeidSDO request rarr 0x600 + nodeidSDO response rarr 0x580 + nodeid

If you need another address scheme create a sub class of CANopenAsyncClient or CANopenClient and over-ride the Init() methods as necessary

3545 More Code Examples

bull See shell commands in canopen_shellcpp

bull See classes SevconClient and SevconJob in the Twizy SEVCON module

360 Chapter 35 CANopen

CHAPTER 36

OVMS Server

361 Welcome

The OVMS (Open Vehicle Monitoring System) team is a group of enthusiasts who are developing a means to remotelycommunicate with our cars and are having fun while doing it

The OVMS module is a low-cost hardware device that you install in your car simply by installing a SIM card con-necting the module to your carrsquos Diagnostic port connector and positioning a cellular antenna Once connected theOVMS module enables remote control and monitoring of your car

This guide documents the installation and operation of an OVMS server

You should however start by asking yourself the question lsquodo I need thisrsquo You donrsquot need to run your own OVMSserver as you can just use one of the public Open Vehicles OVMS servers The choice is yours

362 Installation

3621 Prerequisites

Yoursquoll need a Linux OSX BSD or other flavour of Unix server with a public IP address and a shell account able tosetup a daemon listening on a port Yoursquoll need a modern version of perl running on that server and a bunch of perlmodules (from cpan)

Yoursquoll need a MYSQL server running on the same machine or another machine and credentials to be able to create adatabase and accounts

This could possibly run on a windows server but you are on your own -) [ let us know instructions if you manage toget it running ]

3622 Clone from GitHub

Start the installation with a clone from GitHub

361

Open Vehicles

git clone httpsgithubcomopenvehiclesOpen-Vehicle-Servergit

You can then change into the v3server directory and start the installation process

3623 Perl Module Installation

You will need at a minimum the following modules from CPAN (or from your distributionrsquos package manager)

bull ConfigIniFiles

bull DigestMD5

bull DigestHMAC

bull CryptRC4XS

bull MIMEBase64

bull DBI

bull DBDmysql

bull EV

bull AnyEvent

bull AnyEventHTTP

bull AnyEventHTTPD

bull HTTPParserXS

bull DataUUID

bull EmailMIME

bull EmailSenderSimple

bull NetSSLeay

bull JSONXS

bull ProtocolWebSocket

bull TimePiece

3624 MySQL Setup

Create a mysql database ldquoopenvehiclesrdquo and use the ovms_serversql script to create the necessary ovms_ tablesCreate a mysql username and password with access to the database

Insert a record into the ovms_cars table to give you access to your own car

vehicleid DEMOowner 1carpass DEMOuserpass DEMOcryptscheme 0v_ptokenv_lastupdate 0000-00-00 000000

362 Chapter 36 OVMS Server

Open Vehicles

Obviously change the vehicleid carpass and userpass as necessary The only required fields are vehicleid and carpass

If you are upgrading from server v2 to v3 you can instead source the ovms_server_v2_to_v3sql code to migrate yourdatabase schema

3625 OVMS Server Configuration

Copy confovms_serverconfdefault to confovms_serverconf to provide a template for your configuration Thenmodify the configuration as appropriate

3626 OVMS Server Access to MySQL

In the configovms_serverconf file define the access to the mysql database

[db]path=DBImysqldatabase=openvehicleshost=127001user=ltmysqlusernamegtpass=ltmysqlpasswordgt

If the host is remote change the host= parameter to be the remote IP address Use 127001 for local

Test the connection with

$ mysql -h 127001 -u ltmysqlusernamegt -pEnter password ltmysqlpasswordgtWelcome to the MySQL monitor Commands end with or g

If you get ldquoERROR 1044 (42000) Access deniedrdquo fix it before proceeding The most likely cause is a mistake inyour mysql user grant rights

3627 Enable SSL (optional)

If you want to support SSL connections to your server (port 6869 for the REST API port 6870 for OVMS MP) youneed to supply a certificate You can create a self-signed certificate or get a certificate signed by some root CA foryour server

In both cases you need to merge the private key PEM and the chain PEM into the file ldquoovms_serverpemrdquo located inthe same directory as the ldquoovms_serverplrdquo Also take care to secure the file as it now contains your private key

To create a self-signed certificate do

$ openssl req -sha256 -newkey rsa4096 -nodes -keyout privkeypem -x509 -days 365 -rarr˓out fullchainpem$ cat privkeypem fullchainpem gtconfovms_serverpem$ chmod 0600 confovms_serverpem

Or if you want to reuse eg your Letrsquos Encrypt server certificate do this as root

cat etcletsencryptliveyourhostprivkeypem etcletsencryptliveyourhostrarr˓fullchainpem gtconfovms_serverpem chmod 0600 confvms_serverpem chown youruid confovms_serverpem

and add a cron job or certbot hook to check for renewals and redo these steps as necessary

362 Installation 363

Open Vehicles

3628 Configure the Plugins

The OVMS Server v3 is based on a pluggable architecture The plugins themselves are stored in pluginssystem andpluginslocal directories You must configure (in confovms_serverconf) the plugins that you require

We recommend the following

[plugins]load=ltltEOTVECEDbDBIAuthDrupalApiV2PushPushAPNSPushGCMPushMAILApiHttpApiHttpCoreApiHttpMqapiEOT

3629 Run The Server

You can run the server manually with

$ ovms_serverpl

If your linux host is running systemd you can also look at supportovms_serverservice and supportovmslogrotate asexamples for how you can run this as a background daemon

7 ENJOY

Any questionscomments please let us know

Mark Webb-Johnson March 2020

363 Plugins

3631 ApiHttp

This plugin provides an HTTP (and optional HTTPS) server and is used by subsequent API plugins to provide HTTPservices The HTTP server is on port tcp6868 If you provide a confovms_serverpem file it will also use that tolaunch a HTTPS server on port tcp6869

3632 ApiHttpCore

This plugin provides support for the HTTP API in OVMS Server v3 It supports the api HTTP endpoint

If you want to use this plugin you need to also include lsquoApiHttprsquo before loading this

364 Chapter 36 OVMS Server

Open Vehicles

3633 ApiHttpFile

This plugin provides support serving static files from the httpfiles directory It supports the file HTTP endpoint

If you want to use this plugin you need to also include lsquoApiHttprsquo before loading this

3634 ApiHttpMqapi

This plugin provides support for Mosquitto API functions for authentication and ACL access control It supports themqapi HTTP endpoint

If you want to use this plugin you need to also include lsquoApiHttprsquo before loading this

You will also need to configure your mosquittoconf to include

auth_opt_superusers ltyour-superuser-usernamegtauth_opt_acl_cacheseconds 300auth_opt_auth_cacheseconds 300auth_opt_backends httpauth_opt_http_ip 127001auth_opt_http_port 6868auth_opt_http_getuser_uri mqapiauthauth_opt_http_superuser_uri mqapisuperuserauth_opt_http_aclcheck_uri mqapiacl

3635 ApiV2

This plugin provides support for the v2 OVMS protocol including crypto protocols 0x30 and 0x31 It provides a rawv2 protocol server on tcp6867 If you provide a confovms_serverpem file it will also launch an SSL enabled v2protocol server on tcp6870

3636 AuthDrupal

This plugin provides support for authentication via the Drupal database It also provides a facility to periodicallysynchronise drupal users to OVMS owner table records

Note that only one Auth plugin should be enabled

3637 AuthNone

This is a stub authentication plugin It will always fail authentication and is only provided as an example (or for usein systems where user authentication is not required)

Note that only one Auth plugin should be enabled

3638 DbDBI

This is the core database plugin for perl DBI style SQL databases It is used for example to provide access to MySQLdatabases

363 Plugins 365

Open Vehicles

3639 Push

This provides the core support for Push Notifications The actual notifications themselves are issued by sub-pluginswhich register with this

36310 PushAPNS

This plugin supports the lsquoapnsrsquo notification type for push notifications to Apple devices (iPhones iPadsetc) It requires apple certificates in PEM format to be placed in confovms_apns_sandboxpem andconfovms_apns_productionpem

36311 PushGCM

This plugin supports the lsquogcmrsquo notification type for push notifications to Android devices It requires a google APIkey to be placed in the confovms_serverconf file under [gcm] section parameter lsquoapikeyrsquo You can obtain that keyby

Log in to your Google account Open httpsdevelopersgooglecommobileadd Select platform ldquoAndroidrdquo Enter an arbitrary project name eg ldquoMyOvmsServerrdquo Package name should be ldquocomopenvehiclesOVMSrdquo Activate ldquoCloud Messagingrdquo and generate the key Note the API key and project number (= GCM sender ID)

36312 PushMAIL

This plugin supports the lsquomailrsquo notification type for push notifications by eMail It simply requires a sendmail stylemailer installed on the server

You can configure confovms_serverconf [mail] section parameter lsquosenderrsquo as the sender address to be used (otherwisedefaulting to lsquonotificationsopenvehiclescomrsquo

36313 VECE

This plugin extends the notification system to translate error codes into textual error messgaes It uses files in the vecedirectory named ltvehicletypegtvece (for example trvece vavece etc)

The vece files themselves are ini style files

366 Chapter 36 OVMS Server

CHAPTER 37

OVMS Protocol v2

371 Welcome

The OVMS (Open Vehicle Monitoring System) team is a group of enthusiasts who are developing a means to remotelycommunicate with our cars and are having fun while doing it

The OVMS module is a low-cost hardware device that you install in your car simply by installing a SIM card con-necting the module to your carrsquos Diagnostic port connector and positioning a cellular antenna Once connected theOVMS module enables remote control and monitoring of your car

This developerrsquos guide documents version 2 of the OVMS protocol

372 Terms

Server The OVMS server

Car The OVMS car module

App An OVMS client application one of

bull Active client interactive user applications ie mobile App (Note the car module will raise the updatefrequency when active clients are connected)

bull Batch client a non-interactive application ie shell script

373 Startup

On startup there is no bannerwelcome message from the server The caller initiates the protocol by sending a welcomemessage to the server

1 For cars

MP-C ltprotection schemegt lttokengt ltdigestgt ltcar idgt

367

Open Vehicles

2 For interactive user apps

MP-A ltprotection schemegt lttokengt ltdigestgt ltcar idgt

3 For noninteractive batch apps

MP-B ltprotection schemegt lttokengt ltdigestgt ltcar idgt

4 For servers

MP-S ltprotection schemegt lttokengt ltdigestgt ltcar idgt

The server responds with a welcome message to the caller

MP-S ltprotection schemegt lttokengt ltdigestgt

374 Encryption Scheme 0x30

This scheme is based on using shared secrets hmac digest for authentication and encryption key negotiation withRC4 stream cipher and base64 encoding

Upon startup both the server and callers generate random tokens (encoded as textual characters) Each party thenhmac-md5s the token with the shared secret to create a digest base64 encoded

Note that the server will only issue itrsquos welcome message after receiving and validating the callerrsquos welcome message

Validation of the welcome message is performed by

1 Checking the received token to ensure that it is different from its own token and aborting the connection if thesame

2 Hmac-md5s the received token with the shared secret and comparing the result to the received digest

3 If the digest match then the partner had authenticated itself (proven it knows the shared secret or has listenedto a previous conversation)

4 If the digests donrsquot match then abort the connection as the partner doesnrsquot agree with the shared secret

Once the partner has been authenticated

1 Create a new hmac-md5 based on the client and server tokens concatenated with the shared secret

2 Use the new hmac digest as the key for symmetric rc4 encryption

3 Generate and discard 1024 bytes of cipher text

From this point on messages are rc4 encrypted and base64 encoded before transmission Lines are terminated withCR+LF

375 Encryption Scheme 0x31

This scheme is based on server authentication and is supported in OVMS server v3 and later Typically serversprovide two methods of authentication

bull Username + Password The usual username and associated password as used when registering on the server

bull Username + ApiToken An API token based authentication scheme where each user may maintain one or moreaccess tokens (which can be created or revoked at will)

The arguments to the MP- startup command are

bull ltprotection schemegt Must be set to lsquo1rsquo (0x31)

368 Chapter 37 OVMS Protocol v2

Open Vehicles

bull lttokengt Must be the username pre-registered with the server

bull ltdigestgt Must be the password or api token for that user

bull ltcar idgt Must be the vehicle ID to connect to or the special value lsquorsquo to request connection to the first vehicleon that userrsquos account

Once the partner has been authenticated a response lsquoMP-S 1 ltusergt ltvehicleidgt ltlist-of-all-other-vehiclesgtrsquo will besent from the server to indicate a successful authentication

From then onwards the messages are in plaintext with no further encryption or encoding Lines are terminated withCR+LF

Note that this scheme is intended to be used with external encryption schemes such as SSLTLS

376 Auto Provisioning

A caller can perform auto-provisioning at any time (authenticated or not) However only one auto-provision can beperformed for each connection

Auto-Provisioning relies on two secrets known both to the server and client The first is usually the VIN of the vehicleand the second is usually the ICCID of the SIM card in the vehicle module The reason these two are chosen is thatthey can be auto-determined by the vehicle module but also clearly seen by the user (for entry into the server)

The mechanism works by the client module first determining its VIN and ICCID secrets then connecting to the serverand sending a AP-C message to the server proving its VIN The server will then lookup the auto-provisioning recordand reply with that to the client (via a AP-S or AP-X message)

The auto-provisioning record itself is platform dependent but will typically be an ordered space separated list ofparameter values For OVMS hardware and OVMSX PIC firmware these are merely parameters 0 1 2 etc tobe stored in the car module

3761 Auto Provisioning Protection Scheme 0x30

1 For cars

AP-C ltprotection schemegt ltapkeygt

2 For servers

AP-S ltprotection schemegt ltserver tokengt ltserver digestgt ltprovisioninggt

AP-X

When the provisioning record is created at the server a random token is generated (encoded as textual characters) Theserver then hmac-md5s this token with the shared secret (usually the ICCID known by the server) to create a digestbase64 encoded Using this hmac digest the server generates and discards 1024 bytes of cipher text The serverthen rc4 encrypts and base64 encodes the provisioning information and stores its token digest and encoded provisionrecord ready for the client to request

The car knows its VIN and ICCID With this information it makes a connection to the OVMS service on the serverand provides the VIN as the ltapkeygt in a AP-C message to the server

The server will ensure that it only responds to one AP-C message for any one connection Once responded allsubsequent AP-C requests will always be replied with a AP-X message

Upon receiving the AP-C message the server looks up any provisioning records it has for the given ltapkeygt If it hasnone it replies with an AP-X message

376 Auto Provisioning 369

Open Vehicles

If the server does find a matching provisioning record it replies with an AP-S message sending the previously savedserver token digest and encoded provisioning record to the car

If the car receives an AP-X message it knows that auto-provisioning was not successful

If the car receives an AP-S message it can first validate the server authenticity By producing its own hmac-md5 ofthe server token and secret ICCID the car can validate the server-provided digest is as expected If this validation stepdoes not succeed the car should abort the auto-provisioning

If acceptable the car can decrypt the provisioning record by first generating and discarding 1024 bytes of cipher textthen decoding the provisioning record provided by the server

377 Backwards Compatibility

Typically comma-separated lists are used to transmit parameters Applications Servers and the Car firmware shouldin general ignore extra parameters not expected In this way the protocol messages can be extended by adding extraparameters without breaking old AppsCars that donrsquot expect the new parameters

Similarly unrecognized messages should due ignored Unrecognised commands in the ldquoCrdquo (command) messageshould be responded to with a generic ldquounrecognizedrdquo response (in the ldquocrdquo (command response) messages)

378 Messages

3781 Car lt-gt Server lt-gt App

After discarding CR+LF line termination and base64 decoding the following protocol messages are defined

ltmessagegt = ltmagicgt ltversiongt ltspacegt ltprotmsggt

ltmagicgt = MP-

ltversiongt = 1 byte version number - this protocol is 0x30

ltspacegt = lsquo lsquo (ascii 0x20)

ltprotmsggt = ltservertocargt | ltcartoservergt | ltservertoappgt | ltapptoservergt

ltservertocargt - ldquoSrdquo ltpayloadgt

ltcartoservergt = ldquoCrdquo ltpayloadgt

ltservertoappgt = ldquosrdquo ltpayloadgt

ltapptoservergt = ldquocrdquo ltpayloadgt

ltpayloadgt = ltcodegt ltdatagt

ltcodegt = 1 byte instruction code

ltdatagt = N bytes data (dependent on instruction code)

3782 Ping message 0x41 ldquoArdquo

This message may be sent by any party to test the link The expected response is a 0x61 ping acknowledgementThere is no expected payload to this message an any given can be discarded

370 Chapter 37 OVMS Protocol v2

Open Vehicles

3783 Ping Acknowledgement message 0x61 ldquoardquo

This message is sent in response to a 0x41 ping message There is no expected payload to this message an any givencan be discarded

3784 Command message 0x43 ldquoCrdquo

This message is sent ltapptoservergt then ltservertocargt and carries a command to be executed on the car The messagewould normally be paranoid-encrypted

ltdatagt is a comma-separated list of

bull command (a command code 065535)

bull parameters (dependent on the command code)

For further information on command codes and parameters see the command section below

3785 Command response 0x63 ldquocrdquo

This message is sent ltcartoservergt then ltservertoappgt and carries the response to a command executed on the carThe message would normally be paranoid-encrypted

ltdatagt is a comma-separated list of

bull command (a command code 065535)

bull result (0=ok 1=failed 2=unsupported 3=unimplemented)

bull parameters (dependent on the command code and result)

For result=0 the parameters depend on the command being responded to (see the command section below for furtherinformation)

For result=1 the parameter is a textual string describing the fault

For result=2 or 3 the parameter is not used

3786 Car Environment message 0x44 ldquoDrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the environment settings of the vehicle

ltdatagt is comma-separated list of

Door state 1

bull bit0 = Left Door (open=1closed=0)

bull bit1 = Right Door (open=1closed=0)

bull bit2 = Charge port (open=1closed=0)

bull bit3 = Pilot present (true=1false=0) (always 1 on my 25)

bull bit4 = Charging (true=1false=0)

bull bit5 = always 1

bull bit6 = Hand brake applied (true=1false=0)

bull bit7 = Car ON (ldquoignitionrdquo) (true=1false=0)

378 Messages 371

Open Vehicles

Door state 2

bull bit3 = Car Locked (locked=1unlocked=0)

bull bit4 = Valet Mode (active=1inactive=0)

bull bit6 = Bonnet (open=1closed=0)

bull bit7 = Trunk (open=1closed=0)

LockUnlock state

bull 4 = car is locked

bull 5 = car is unlocked

Temperature of the PEM (celcius)

Temperature of the Motor (celcius)

Temperature of the Battery (celcius)

Car trip meter (in 110th of a distance unit)

Car odometer (in 110th of a distance unit)

Car speed (in distance units per hour)

Car parking timer (0 for not parked or number of seconds car parked for)

Ambient Temperature (in Celcius)

Door state 3

bull bit0 = Car awake (turned on=1 off=0)

bull bit1 = Cooling pump (on=1off=0)

bull bit6 = 1=Logged into motor controller

bull bit7 = 1=Motor controller in configuration mode

Stale PEMMotorBattery temps indicator (-1=none 0=stale gt0 ok)

Stale ambient temp indicator (-1=none 0=stale gt0 ok)

Vehicle 12V line voltage

Door State 4

bull bit2 = alarm sounds (on=1off=0)

Reference voltage for 12v power

Door State 5

bull bit0 = Rear left door (open=1closed=0)

bull bit1 = Rear right door (open=1closed=0)

bull bit2 = Frunk (open=1closed=0)

bull bit4 = 12V battery charging

bull bit5 = Auxiliary 12V systems online

bull bit7 = HVAC running

372 Chapter 37 OVMS Protocol v2

Open Vehicles

Temperature of the Charger (celsius)

Vehicle 12V current (ie DC converter output)

Cabin temperature (celsius)

3787 Paranoid-mode encrypted message 0x45 ldquoErdquo

This message is sent for any of the four message ltprotmsggt types and represents an encrypted transmission that theserver should just relay (or is relaying) without being able to interpret it The encryption is based on a shared secretbetween the car and the apps to which the server is not privy

ltdatagt is

bull ltparanoidtokengt | ltparanoidcodegt

bull ltparanoidtokengt = ldquoTrdquo ltptokengt

bull ltparanoidcodegt = ldquoMrdquo ltcodegt ltdatagt

In the case of ltparanoidtokengt the ltptokengt is a random token that represent the encryption key It can only besent ltcartoservergt or ltservertoappgt Upon receiving this token the server discards all previously stored paranoidmessages sends it on to all connected apps and then stores the token Every time an app connects the server alsosends this token to the app

In the case of ltparanoidcodegt the ltcodegt is a sub-message code and can be any of the codes listed in this document(except for ldquoArdquo ldquoardquo and ldquoErdquo) The ltdatagt is the corresponding encrypted payload message The encryption isperformed on the ltdatagt by

bull Create a new hmac-md5 based on the ltptokengt with the shared secret

bull Use the new hmac digest as the key for symmetric rc4 encryption

bull Generate and discard 1024 bytes of cipher text

and the data is base64 encoded Upon receiving a paranoid message from the car the server forwards it on the allconnected apps and then stores the message Every time an app connects the server sends all such stored messagesUpon receiving a paranoid message from an app if the car is connected the server merely forwards it on to the carotherwise discarding it

3788 Car firmware message 0x46 ldquoFrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the firmware versions of the vehicle

ltdatagt is comma-separated list of

bull OVMS firmware version

bull VIN (vehicle identification number)

bull Current network signal quality (Wifi GSM in SQ units)

bull Write-enabled firmware (0=read-only 1=write-enabled)

bull Vehicle type code (eg TR = Tesla Roadster see command output vehicle list)

bull Current network name (Wifi SSID GSM provider)

bull Distance to next scheduled maintenanceservice [km]

bull Time to next scheduled maintenanceservice [seconds]

bull OVMS hardware version

378 Messages 373

Open Vehicles

3789 Server firmware message 0x66 ldquofrdquo

This message is sent ltservertocargt ldquoSrdquo or ltservertoappgt ldquosrdquo and transmits the firmware versions of the server

ltdatagt is comma-separated list of

bull Server firmware version

37810 Car group subscription message 0x47 ldquoGrdquo

This message is sent ltapptoservergt ldquoArdquo and requests subscription to the specified group

ltdatagt is comma-separated list of

bull Group name

37811 Car group update message 0x67 ldquogrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits a group location message for the vehicle

ltdatagt is comma-separated list of

bull Vehicle ID (only ltservertoappgt not sent ltcartoservergt)

bull Group name

bull Car SOC

bull Car Speed

bull Car direction

bull Car altitude

bull Car GPS lock (0=nogps 1=goodgps)

bull Stale GPS indicator (-1=none 0=stale gt0 ok)

bull Car latitude

bull Car longitude

37812 Historical Data update message 0x48 ldquoHrdquo

This message is sent ltcartoservergt ldquoC and transmits a historical data message for storage on the server

ltdatagt is comma-separated list of

bull type (unique storage class identification type)

bull recordnumber (integer record number)

bull lifetime (in seconds)

bull data (a blob of data to be dealt with as the application requires)

The lifetime is specified in seconds and indicates to the server the minimum time the vehicle expects the server toretain the historical data for Consideration should be made as to server storage and bandwidth requirements

The type is composed of ltvehicletypegt - ltclassgt - ltpropertygt

ltVehicletypegt is the usual vehicle type or lsquorsquo to indicate generic storage suitable for all vehicles

374 Chapter 37 OVMS Protocol v2

Open Vehicles

ltClassgt is one of

bull PWR (power)

bull ENG (engine)

bull TRX (transmission)

bull CHS (chassis)

bull BDY (body)

bull ELC (electrics)

bull SAF (safety)

bull SEC (security)

bull CMF (comfort)

bull ENT (entertainment)

bull COM (communications)

bull X (unclassified and experimental with replaced with 2 digits code)

ltPropertygt is a property code which the vehicle decides

The server will timestamp the incoming historical records and will set an expiry date of timestamp + ltlifetimegtseconds The server will endeavor to retain the records for that time period but may expend data earlier if necessary

37813 Historical Data update+ack message 0x68 ldquohrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltsevertocargt ldquocrdquo and transmitsacknowledges historical data message forstorage on the server

For ltcartoservergt the ltdatagt is comma-separated list of

bull ackcode (an acknowledgement code)

bull timediff (in seconds)

bull type (unique storage class identification type)

bull recordnumber (integer record number)

bull lifetime (in seconds)

bull data (a blob of data to be dealt with as the application requires)

The ackcode is a numeric acknowledgement code - if the server successfully receives the message it will reply withldquohrdquo and this ackcode to acknowledge reception

The timediff is the time difference in seconds to use when storing the record (eg -3600 would indicate the recorddata is from one hour ago)

The lifetime is specified in seconds and indicates to the server the minimum time the vehicle expects the server toretain the historical data for Consideration should be made as to server storage and bandwidth requirements

For ltservertocargt the ltdatagt is

bull ackcode (an acknowledgement code)

The ltcartoservergt message sends the data to the server The ltservertocargt message acknowledges the data

378 Messages 375

Open Vehicles

37814 Push notification message 0x50 ldquoPrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo When used by the car it requests the server to send atextual push notification alert message to all apps registered for this car The ltdatagt is 1 byte alert type followed by Nbytes of textual message The server will use this message to send the notification to any connected apps and can alsosend via external mobile frameworks for unconnected apps

37815 Push notification subscription 0x70 ldquoprdquo

This message is sent ltapptoservergt Ardquo It is used by app to register for push notifications and is normally at the startof a connection The ltdatagt is made up of

ltappidgtltpushtypegtltpushkeytypegtltvehicleidgtltnetpassgtltpushkeyvaluegt

The server will verify the credentials for each vehicle and store the required notification information

Note As of June 2020 only one vehicleid can be subscribed at a time If multiple vehicles are required then theyshould each be subscribed in individual messages

37816 Server -gt Server Record message 0x52 ldquoRrdquo

This message is sent ltservertoservergt ldquoSrdquo and transmits an update to synchronized database table records

Sub-type RV (Vehicle record) ltdatagt is comma-separated list of

bull Vehicleid

bull Owner

bull Carpass

bull v_server

bull deleted

bull changed

Sub-type RO (Owner record) ltdatagt is comma-separated list of

bull Ownerid

bull OwnerName

bull OwnerMail

bull PasswordHash

bull OwnerStatus

bull deleted

bull changed

37817 Server -gt Server Message Replication message 0x72 ldquorrdquo

This message is sent ltservertoservergt ldquoSrdquo and replicates a message for a particular car

ltdatagt is comma-separated list of

bull vehicleid

bull message code

376 Chapter 37 OVMS Protocol v2

Open Vehicles

bull message data

37818 Car state message 0x53 ldquoSrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the last known status of the vehicle

ltdatagt is comma-separated list of

bull SOC

bull Units (ldquoMrdquo for miles ldquoKrdquo for kilometers)

bull Line voltage

bull Charge current (amps)

bull Charge state (charging topoff done prepare heating stopped)

bull Charge mode (standard storage range performance)

bull Ideal range

bull Estimated range

bull Charge limit (amps)

bull Charge duration (minutes)

bull Charger B4 byte (tba)

bull Charge energy consumed (110 kWh)

bull Charge sub-state

bull Charge state (as a number)

bull Charge mode (as a number)

bull Charge Timer mode (0=onplugin 1=timer)

bull Charge Timer start time

bull Charge timer stale (-1=none 0=stale gt0 ok)

bull Vehicle CAC100 value (calculated amp hour capacity in Ah)

bull ACC Mins remaining until car will be full

bull ACC Mins remaining until car reaches charge limit

bull ACC Configured range limit

bull ACC Configured SOC limit

bull Cooldown Car is cooling down (0=no 1=yes)

bull Cooldown Lower limit for battery temperature

bull Cooldown Time limit (minutes) for cooldown

bull ACC charge time estimation for current charger capabilities (min)

bull Charge ETR for range limit (min)

bull Charge ETR for SOC limit (min)

bull Max ideal range

378 Messages 377

Open Vehicles

bull Chargeplug type ID according to OpenChargeMapsorg connectiontypes (see httpapiopenchargemapiov2referencedata)

bull Charge power output (kW)

bull Battery voltage (V)

bull Battery SOH (state of health) ()

bull Charge power input (kW)

bull Charger efficiency ()

bull Battery current (A)

bull Battery ideal range gainloss speed (mphkph gain=positive)

37819 Car update time message 0x53 ldquoTrdquo

This message is sent ltservertoappgt ldquosrdquo and transmits the last known update time of the vehicle

ltdatagt is the number of seconds since the car last sent an update message

37820 Car location message 0x4C ldquoLrdquo

This message is sent ltcartoservergt ldquoCrdquo and transmits the last known location of the vehicle

ltdatagt is comma-separated list of

bull Latitude

bull Longitude

bull Car direction

bull Car altitude

bull Car GPS lock (0=nogps 1=goodgps)

bull Stale GPS indicator (-1=none 0=stale gt0 ok)

bull Car speed (in distance units per hour)

bull Car trip meter (in 110th of a distance unit)

bull Drive mode (car specific encoding of current drive mode)

bull Battery power level (in kW negative = charging)

bull Energy used (in Wh)

bull Energy recovered (in Wh)

bull Inverter motor power (kW) (positive = output)

bull Inverter efficiency ()

bull GPS mode indicator (see below)

bull GPS satellite count

bull GPS HDOP (see below)

bull GPS speed (in distance units per hour)

378 Chapter 37 OVMS Protocol v2

Open Vehicles

GPS mode indicator this shows the NMEA receiver mode If using the SIM5360 modem for GPS this is a twocharacter string The first character represents the GPS receiver mode the second the GLONASS receiver mode Eachmode character may be one of

bull N = No fix Satellite system not used in position fix or fix not valid

bull A = Autonomous Satellite system used in non-differential mode in position fix

bull D = Differential (including all OmniSTAR services) Satellite system used in differential mode in position fix

bull P = Precise Satellite system used in precision mode Precision mode is defined as no deliberate degradation(such as Selective Availability) and higher resolution code (P-code) is used to compute position fix

bull R = Real Time Kinematic Satellite system used in RTK mode with fixed integers

bull F = Float RTK Satellite system used in real time kinematic mode with floating integers

bull E = Estimated (dead reckoning) Mode

bull M = Manual Input Mode

bull S = Simulator Mode

GPS HDOP HDOP = horizontal dilution of precision This is a measure for the currently achievable precision ofthe horizontal coordinates (latitude amp longitude) which depends on the momentary relative satellite positions andvisibility to the device

The lower the value the higher the precision Values up to 2 mean high precision up to 5 is good If the value ishigher than 20 coordinates may be off by 300 meters from the actual position

See httpsenwikipediaorgwikiDilution_of_precision_(navigation) for further details

37821 Car Capabilities message 0x56 ldquoVrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the vehicle capabilities It was introducedwith v2 of the protocol

ltdata is comma-separated list of vehicle capabilities of the form

bull Cltcmdgt indicates vehicle support command ltcmdgt

bull CltcmdLgt-ltcmdHgt indicates vehicle will support all commands in the specified range

37822 Car TPMS message 0x57 ldquoWrdquo (oldobsolete)

Note Message ldquoWrdquo has been replaced by ldquoYrdquo (see below) for OVMS V3 The V3 module will still send ldquoWrdquomessages along with ldquoYrdquo for old clients for some time Clients shall adapt to using ldquoYrdquo if available ASAP ldquoWrdquomessages will be removed from V3 in the near future

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the last known TPMS values of thevehicle

ltdatagt is comma-separated list of

bull front-right wheel pressure (psi)

bull front-right wheel temperature (celcius)

bull rear-right wheel pressure (psi)

bull rear-right wheel temperature (celcius)

378 Messages 379

Open Vehicles

bull front-left wheel pressure (psi)

bull front-left wheel temperature (celcius)

bull rear-left wheel pressure (psi)

bull rear-left wheel temperature (celcius)

bull Stale TPMS indicator (-1=none 0=stale gt0 ok)

37823 Car TPMS message 0x59 ldquoYrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the last known TPMS values of thevehicle

ltdatagt is comma-separated list of

bull number of defined wheel names

bull list of defined wheel names

bull number of defined pressures

bull list of defined pressures (kPa)

bull pressures validity indicator (-1=undefined 0=stale 1=valid)

bull number of defined temperatures

bull list of defined temperatures (Celcius)

bull temperatures validity indicator (-1=undefined 0=stale 1=valid)

bull number of defined health states

bull list of defined health states (Percent)

bull health states validity indicator (-1=undefined 0=stale 1=valid)

bull number of defined alert levels

bull list of defined alert levels (0=none 1=warning 2=alert)

bull alert levels validity indicator (-1=undefined 0=stale 1=valid)

Note Pressures are transported in kPa now instead of the former PSI To convert to PSI multiply by014503773773020923

37824 Peer connection message 0x5A ldquoZrdquo

This message is sent ltservertocargt or ltservertoappgt to indicate the connection status of the peer (car for ltserver-toappgt interactive apps for ltservertocargt) It indicates how many peers are currently connected

It is suggested that the car should use this to immediately report on and to increase the report frequency of status - inthe case that one or more interactive Apps are connected and watching the car

Batch client connections do not trigger any peer count change for the car but they still receive the car peer status fromthe server

ltdatagt is

bull Number of peers connected expressed as a decimal string

380 Chapter 37 OVMS Protocol v2

Open Vehicles

37825 Car export power message 0x47 ldquoGrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits ldquovgrdquo metrics from the vehicle

ltdatagt is comma-separated list of

bull vggenerating (1 = currently delivering power)

bull vgpilot (1 = pilot present)

bull vgvoltage (in V)

bull vgcurrent (in A)

bull vgpower (in kW)

bull vgefficiency (in )

bull vgtype (eg ldquochademordquo)

bull vgstate (eg ldquoexportingrdquo)

bull vgsubstate (eg ldquoonrequestrdquo)

bull vgmode (eg ldquostandardrdquo)

bull vgclimit (in A)

bull vglimitrange (in km)

bull vglimitsoc (in )

bull vgkwh (in kWh)

bull vgkwhgrid (in kWh)

bull vgkwhgridtotal (in kWh)

bull vgtime (in s)

bull vgtimermode (1 = generator timer enabled)

bull vgtimerstart

bull vgdurationempty (in min)

bull vgdurationrange (in min)

bull vgdurationsoc (in min)

bull vgtemp (in deg C)

Refer httpsdocsopenvehiclescomenlatestuserguidemetricshtml

379 Commands

3791 Commands and Expected Responses

For message types ldquoCrdquo and ldquocrdquo the following commands and responses are expected to be supported

379 Commands 381

Open Vehicles

3792 1 - Request feature list

Command parameters are unused and ignored by the car

Response is a sequence of individual messages with each message containing the following parameters

bull feature number

bull maximum number of features

bull feature value

Registered features are

bull 0 Digital SPEEDO (experimental)

bull 8 Location STREAM mode (consumes more bandwidth)

bull 9 Minimum SOC

bull 15 CAN bus can write-enabled

Note that features 0 through 7 are lsquovolatilersquo and will be lost (reset to zero value) if the power is lost to the car moduleor module is reprogrammed These features are considered extremely experimental and potentially dangerous

Features 8 through 15 are lsquopermanentrsquo and will be stored as parameters 23 through 31 These features are consideredmore stable but optional

3793 2 - Set feature

Command parameters are

bull feature number to set

bull value to set

Response parameters are unused and will merely indicate the success or not of the result

3794 3 - Request parameter list

Command parameters are unused and ignored by the car

Response is a sequence of individual messages with each message containing the following parameters

bull parameter number

bull maximum number of parameters

bull parameter value

Registered parameters are

bull 0 Registered telephone number

bull 1 Registration Password

bull 2 Miles Kilometer flag

bull 3 Notification method list

bull 4 Server IP

bull 5 GPRS APN

bull 6 GPRS User

382 Chapter 37 OVMS Protocol v2

Open Vehicles

bull 7 GPRS Password

bull 8 Vehicle ID

bull 9 Network Password

bull 10 Paranoid Password

Note that some parameters (24 through 31) are tied directly to the features system (for permanent features) and arethus not directly maintained by the parameter system or shown by this command

3795 4 - Set parameter

Command parameters are

bull parameter number to set

bull value to set

Response parameters are unused and will merely indicate the success or not of the result

3796 5 - Reboot

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result Shortly after sending theresponse the module will reboot

3797 6 - Charge Alert

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result Shortly after sending theresponse the module will issue a charge alert

3798 7 - Execute SMS command

Command parameter is

bull SMS command with parameters

Response is the output of the SMS command that would otherwise have been sent as the reply SMS with LF charactersconverted to CR

The caller id is set to the registered phone number Return code 1 is used for all errors ie authorization failurecommand failure and unknownunhandled commands

Note SMS commands with multiple replies are not yet supported only the last reply will be returned

3799 10 - Set Charge Mode

Command parameters are

bull mode (0=standard 1=storage3=range4=performance)

Response parameters are unused and will merely indicate the success or not of the result

379 Commands 383

Open Vehicles

37910 11 - Start Charge

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

37911 12 - Stop Charge

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

37912 15 - Set Charge Current

Command parameters are

bull current (specified in Amps)

Response parameters are unused and will merely indicate the success or not of the result

37913 16 - Set Charge Mode and Current

Command parameters are

bull mode (0=standard 1=storage3=range4=performance)

bull current (specified in Amps)

Response parameters are unused and will merely indicate the success or not of the result

37914 17 - Set Charge Timer Mode and Start Time

Command parameters are

bull timermode (0=plugin 1=timer)

bull start time (0x059F for midnight GMT 0x003B for 1am GMT etc)

Response parameters are unused and will merely indicate the success or not of the result

37915 18 - Wakeup car

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

37916 19 - Wakeup temperature subsystem

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

384 Chapter 37 OVMS Protocol v2

Open Vehicles

37917 20 - Lock Car

Command parameters are

bull pin (the car pin to use for locking)

Response parameters are unused and will merely indicate the success or not of the result

NB unlocklock may not affect the immobilizer+alarm (when fitted)

37918 21 - Activate Valet Mode

Command parameters are

bull pin (the car pin to activate valet mode)

Response parameters are unused and will merely indicate the success or not of the result

37919 22 - Unlock Car

Command parameters are

bull pin (the car pin to use for unlocking)

Response parameters are unused and will merely indicate the success or not of the result

NB unlocklock does not affect the immobilizer+alarm (when fitted)

37920 23 - Deactivate Value Mode

Command parameters are

bull pin (the car pin to use for deactivating value mode)

Response parameters are unused and will merely indicate the success or not of the result

37921 24 - Home Link

Command parameters are

bull button (home link button 0 1 or 2)

Response parameters are unused and will merely indicate the success or not of the result

37922 25 - Cooldown

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

379 Commands 385

Open Vehicles

37923 30 - Request GPRS utilization data

Command parameters are unused and ignored by the car

Response is a sequence of individual messages with each message containing the following parameters

bull record number

bull maximum number of records

bull date

bull car received bytes

bull car transmitted bytes

bull apps received bytes

bull apps transmitted bytes

Note that this request is handled by the server not the car so must not be sent in paranoid mode The response (fromthe server) will also not be sent in paranoid mode

NB Dates (and GPRS utilization data) are in UTC

37924 31 - Request historical data summary

Command parameters are

bull since (optional timestamp condition)

Response is a sequence of individual messages with each message containing the following parameters

bull type number

bull maximum number of types

bull type value

bull number of unique records (per type)

bull total number of records (per type)

bull storage usage (in bytes per type)

bull oldest data timestamp (per type)

bull newest data timestamp (per type)

NB Timestamps are in UTC

37925 32 - Request historical data records

Command parameters are

bull type (the record type to retrieve)

bull since (optional timestamp condition)

Response is a sequence of individual messages with each message containing the following parameters

bull response record number

bull maximum number of response records

bull data record type

386 Chapter 37 OVMS Protocol v2

Open Vehicles

bull data record timestamp

bull data record number

bull data record value

37926 40 - Send SMS

Command parameters are

bull number (telephone number to send sms to)

bull message (sms message to be sent)

Response parameters are unused and will merely indicate the success or not of the submission (not delivery) of theSMS

37927 41 - Send MMIUSSD Codes

Command parameters are

bull USSD_CODE (the ussd code to send)

Response parameters are unused and will merely indicate the success or not of the submission (not delivery) of therequest

37928 49 - Send raw AT Command

Command parameters are

bull at (the AT command to send - including the AT prefix)

Response parameters are unused and will merely indicate the success or not of the submission (not delivery) of therequest

379 Commands 387

Open Vehicles

388 Chapter 37 OVMS Protocol v2

CHAPTER 38

OVMS HTTP API

381 Welcome

For some time now Irsquove wanted to offer an HTTP API for OVMS The existing carlt-gtserver and serverlt-gtapp protocolis cool but requires going through some hoops (perl whatever) to handle the encryption and protocol level stuff AnHTTP API would make this much easier to externally script and would be great for pulling down logs and other suchthings

This document describes this HTTP API

Mark February 2013

382 Format

The API is a RESTfull service running at

bull httpapiopenvehiclescom6868api

bull httpsapiopenvehiclescom6869api

Other OVMS servers should provide this API on the same ports but for the rest of this manual we will simply refer toapiopenvehiclescom as the server being used

The return data is a json formatted array of hashes Each record is one for one vehicle and shows you the vehicle idas well as counts for the number of apps currently connected to that vehicle and whether the vehicle is connected tothe net (server) or not

From the server point of view we can treat an api session just like an app session From the vehicle point of view therewill be no difference - once an API connects to a vehicle the server will send a ldquoZ 1rdquo message to tell the module it hasa connection If the session times out or is logged out the server will inform the modules in the vehicles

389

Open Vehicles

3821 Example

For example once authenticated you can request a list of vehicles on your account

$ curl -v -X GET -b cookiejar httpapiopenvehiclescom6868apivehicles

About to connect() to apiopenvehiclescom port 6868 (0)

Trying apiopenvehiclescom

connected

Connected to tmcopenvehiclescom (641117040) port 6868 (0)gt GET apivehicles HTTP11User-Agent curl7240 (x86_64-apple-darwin120) libcurl7240OpenSSL098r zlib125Host apiopenvehiclescom6868Accept Cookie ovmsapisession=9ed66d0e-5768-414e-b06d-476f13be40ff

HTTP 10 assume close after bodylt HTTP10 200 Logout oklt Connection closelt Content-Length 280lt Cache-Control max-age=0lt Content-Type applicationjsonlt Date Fri 22 Feb 2013 124441 GMTlt Expires Fri 22 Feb 2013 124441 GMTlt[

idDEMOv_apps_connected0v_net_connected1idMARKSCARv_apps_connected1v_net_connected1idQCCARv_apps_connected0v_net_connected0idRALLYCARv_apps_connected0v_net_connected0idTESTCARv_apps_connected0v_net_connected0

]

(note that the above is re-formatted slightly to make it clearer to read)

383 Authentication

3831 Alternatives

Each API call must be authenticated and there are currently three options for this

Username+Passsword authentication Specify parameters lsquousernamersquo and lsquopasswordrsquo in the URL and they will bevalidated against registered users on the server Username+ApiToken authentication Specify parameter lsquousernamersquoas the registered user and lsquopasswordrsquo as a registered API token in the URL and they will be validated againstregistered API tokens for that user on the server Cookie authentication A cookie may be obtained (by either of theabove two authentication methods) and then used for subsequent API calls

3832 Cookie Based Authentication

Cookie based authentication avoids the requirement to authenticate each time It is also a requirement for sessionbased API calls This is done with a http ldquoGET apicookierdquo passing parameters lsquousernamersquo and lsquopasswordrsquo as yourwwwopenvehiclescom username and password (or API token) respectively

390 Chapter 38 OVMS HTTP API

Open Vehicles

$ curl -v -X GET -c cookiejarhttpapiopenvehiclescom6868apicookieusername=USERNAMEamppassword=PASSWORD

About to connect() to tmcopenvehiclescom port 6868 (0)

Trying 641117040

connected

Connected to tmcopenvehiclescom (641117040) port 6868 (0)GET apicookieusername=USERNAMEamppassword=PASSWORD HTTP11User-Agent curl7240 (x86_64-apple-darwin120) libcurl7240OpenSSL098r zlib125Host tmcopenvehiclescom6868Accept

HTTP 10 assume close after bodylt HTTP10 200 Authentication oklt Connection closelt Content-Length 9lt Cache-Control max-age=0lt Content-Type textplain

Added cookie ovmsapisession=9ed66d0e-5768-414e-b06d-476f13be40ff for domain tmcrarr˓openvehiclescom path api expire 0lt Set-Cookie ovmsapisession=9ed66d0e-5768-414e-b06d-476f13be40fflt Date Fri 22 Feb 2013 124356 GMTlt Expires Fri 22 Feb 2013 124356 GMTltLogin ok

Once logged in all subsequent requests should pass the cookie (ovmsapisession) The session will expire after 3minutes of no use or you can specifically terminate logout the session by calling ldquoDELETE apicookierdquo

The cookie can be destroyed (and session logged out) using the DELETE method (passing the original cookie)

$ curl -v -X DELETE -b cookiejarhttpapiopenvehiclescom6868apicookie

3833 API Token Maintenance

An API token can be created with a POST to the apitoken API endpoint

$ curl -v -X POST -F application=ltappgt -F purpose=ltpurposegt -F permit=ltpermitgthttpapiopenvehiclescom6868apitoken

Note that the lsquopurposersquo and lsquoapplicationrsquo fields are comments attached to the token and are intended to identify theapplication that createduses the token and the purpose that token is used for

The lsquopermitrsquo field defines the list of rights granted to the user of this token

Any of the three authentication mechanisms can be used for this so long as the permissions include either lsquoto-kenadminrsquo or lsquoadminrsquo rights

An API token can be deleted with a DELETE to the apitokenltTOKENgt API endpoint

$ curl -v -X DELETE httpapiopenvehiclescom6868apitokenltTOKENgt

383 Authentication 391

Open Vehicles

384 Requests

3841 GET apicookie

Login and return a session cookie

3842 DELETE apicookie

Delete the session cookie and logout

All vehicles still connected (via apivehicle) will be disconnected automatically

3843 GET apitoken

Return a list of registered API tokens

3844 POST apitoken

Create an API token

3845 DELETE apitokenltTOKENgt

Delete the specified API token

3846 GET apivehicles

Return a list of registered vehicles

bull id Vehicle ID

bull v_net_connected Number of vehicles currently connected

bull v_apps_connected Number of apps currently connected

bull v_btcs_connected Number of batch clients currently connected

3847 GET apivehicleltVEHICLEIDgt

Connect to the vehicle and return vehicle information

bull m_msgage_s age (seconds) of last status (S) message received if available

bull m_msgtime_s time stamp (UTC) of last status (S) message received if available

bull v_apps_connected number of apps currently connected (including the API connection)

bull v_btcs_connected number of batch clients currently connected

bull v_first_peer 01 1 = the API connection is the first peer connecting to the car

bull v_net_connected 01 1 = the car is currently connected to the server

392 Chapter 38 OVMS HTTP API

Open Vehicles

While no application is connected to the vehicle the module will send status updates using the configured ldquoidlerdquointerval to reduce data volume and energy consumption

Connecting to the car tells the module (if connected) to send status updates in the normally shorter ldquoconnectedrdquointervals (as configured) If yoursquore the first peer and the car is online the module will send a full status update withinthe next second after receiving the new peer count Depending on the connection speed you should give the car modulesome seconds to transmit the first update before proceeding to other status queries

You can also check m_msgage_s and m_msgtime_s to see if the status record is up to date (yet) These fields arealso included in the other status responses eg apichargeltVEHICLEIDgt

3848 DELETE apivehicleltVEHICLEIDgt

Disconnect from the vehicle

This is optional on session logout or expiry all vehicles will be disconnected automatically

3849 GET apiprotocolltVEHICLEIDgt

Return raw protocol records (no vehicle connection)

bull m_msgtime Datetime message received

bull m_paranoid Paranoid mode flag

bull m_ptoken Paranoid mode token

bull m_code Message code

bull m_msg Message body

38410 GET apistatusltVEHICLEIDgt

Return vehicle status

bull soc

bull units

bull idealrange

bull idealrange_max

bull estimatedrange

bull mode

bull chargestate

bull cac100

bull soh

bull cooldown_active

bull fl_dooropen

bull fr_dooropen

bull cp_dooropen

bull pilotpresent

384 Requests 393

Open Vehicles

bull charging

bull caron

bull carlocked

bull valetmode

bull bt_open

bull tr_open

bull temperature_pem

bull temperature_motor

bull temperature_battery

bull temperature_charger

bull temperature_cabin

bull tripmeter

bull odometer

bull speed

bull parkingtimer

bull temperature_ambient

bull carawake

bull staletemps

bull staleambient

bull charging_12v

bull vehicle12v

bull vehicle12v_ref

bull vehicle12v_current

bull alarmsounding

bull m_msgage_s age (seconds) of last status (S) message received if available

bull m_msgtime_s time stamp (UTC) of last status (S) message received if available

bull m_msgage_d age (seconds) of last doorsenv (D) message received if available

bull m_msgtime_d time stamp (UTC) of last doorsenv (D) message received if available

38411 GET apitpmsltVEHICLEIDgt

Return tpms status

bull fr_pressure

bull fr_temperature

bull rr_pressure

bull rr_temperature

bull fl_pressure

394 Chapter 38 OVMS HTTP API

Open Vehicles

bull fl_temperature

bull rl_pressure

bull rl_temperature

bull staletpms

bull m_msgage_w age (seconds) of last TPMS (W) message received if available

bull m_msgtime_w time stamp (UTC) of last TPMS (W) message received if available

38412 GET apilocationltVEHICLEIDgt

Return vehicle location

bull latitude

bull longitude

bull direction

bull altitude

bull gpslock

bull stalegps

bull speed

bull tripmeter

bull drivemode

bull power

bull energyused

bull energyrecd

bull m_msgage_l age (seconds) of last location (L) message received if available

bull m_msgtime_l time stamp (UTC) of last location (L) message received if available

38413 GET apichargeltVEHICLEIDgt

Return vehicle charge status

bull linevoltage

bull battvoltage

bull chargecurrent

bull chargepower

bull chargetype

bull chargestate

bull soc

bull units

bull idealrange

bull estimatedrange

384 Requests 395

Open Vehicles

bull mode

bull chargelimit

bull chargeduration

bull chargeb4

bull chargekwh

bull chargesubstate

bull chargetimermode

bull chargestarttime

bull chargetimerstale

bull cac100

bull soh

bull charge_etr_full

bull charge_etr_limit

bull charge_limit_range

bull charge_limit_soc

bull cooldown_active

bull cooldown_tbattery

bull cooldown_timelimit

bull charge_estimate

bull charge_etr_range

bull charge_etr_soc

bull idealrange_max

bull cp_dooropen

bull pilotpresent

bull charging

bull caron

bull temperature_pem

bull temperature_motor

bull temperature_battery

bull temperature_charger

bull temperature_ambient

bull temperature_cabin

bull carawake

bull staletemps

bull staleambient

bull charging_12v

396 Chapter 38 OVMS HTTP API

Open Vehicles

bull vehicle12v

bull vehicle12v_ref

bull vehicle12v_current

bull m_msgage_s age (seconds) of last status (S) message received if available

bull m_msgtime_s time stamp (UTC) of last status (S) message received if available

bull m_msgage_d age (seconds) of last doorsenv (D) message received if available

bull m_msgtime_d time stamp (UTC) of last doorsenv (D) message received if available

38414 GET apihistoricalltVEHICLEIDgt

Request historical data summary (as array of)

bull h_recordtype

bull distinctrecs

bull totalrecs

bull totalsize

bull first

bull last

38415 GET apihistoricalltVEHICLEIDgtltDATATYPEgt

Request historical data records

bull h_timestamp

bull h_recordnumber

bull h_data

38416 Not Yet Implemented

bull PUT apichargeltVEHICLEIDgt Set vehicle charge status

bull DELETE apichargeltVEHICLEIDgt Abort a vehicle charge

bull GET apilockltVEHICLEIDgt Return vehicle lock status

bull PUT apilockltVEHICLEIDgt Lock a vehicle

bull DELETE apilockltVEHICLEIDgt Unlock a vehicle

bull GET apivaletltVEHICLEIDgt Return valet status

bull PUT apivaletltVEHICLEIDgt Enable valet mode

bull DELETE apivaletltVEHICLEIDgt Disable valet mode

bull GET apifeaturesltVEHICLEIDgt Return vehicle features

bull PUT apifeatureltVEHICLEIDgt Set a vehicle feature

bull GET apiparametersltVEHICLEIDgt Return vehicle parameters

384 Requests 397

Open Vehicles

bull PUT apiparameterltVEHICLEIDgt Set a vehicle parameter

bull PUT apiresetltVEHICLEIDgt Reset the module in a particular vehicle

bull PUT apihomelinkltVEHICLEIDgt Activate home link

398 Chapter 38 OVMS HTTP API

Index

AApp 367

CCar 367

SServer 367

399

  • Open-Vehicle-Monitoring-System-3 (OVMS3)
  • User Guide
  • Plugins
  • BMW i3 i3s
  • DBC Based Vehicles
  • DEMO Vehicle
  • Fiat 500e
  • Hyundai Ioniq vFL
  • Jaguar IPace
  • Kia e-Niro
  • Kia Soul EV
  • Maxus eDeliver3
  • Mercedes-Benz B250E W242
  • MG EV
  • Mitsubishi Trio
  • Nissan Leafe-NV200
  • OBDII Vehicles
  • Renault Twizy
  • Renault Zoe
  • Smart ED Gen3
  • Smart EDEQ Gen4 (453)
  • Tesla Model 3
  • Tesla Model S
  • Tesla Roadster
  • Toyota RAV4 EV
  • Tracking Vehicles
  • VW e-Up
  • VW e-Up via OBD2
  • VW e-Up via Comfort CAN (T26A)
  • Command Line Interpreter
  • CAN Bus Data Logging
  • CRTD CAN Log Format
  • Web Framework amp Plugins
  • Scripting
  • CANopen
  • OVMS Server
  • OVMS Protocol v2
  • OVMS HTTP API
  • Index
Page 4: Open Vehicles - Home | Read the Docs

Open Vehicles

Note This online manual includes documentation for the stable release of the OVMS firmware (available as OTAversion tag ldquomainrdquo) and the latest nightly firmware build (available as OTA version ldquoedgerdquo) Select the manual versionmatching your setup using the menu on the bottom left

User Guides 1

Open Vehicles

2 User Guides

CHAPTER 1

Open-Vehicle-Monitoring-System-3 (OVMS3)

11 Introduction

The OVMS is an all open source vehicle remote monitoring diagnosis and control system

3

Open Vehicles

The system provides live monitoring of vehicle metrics like state of charge temperatures tyre pressures and diag-nostic fault conditions It will alert you about critical conditions and events like a charge abort battery cell failureor potential theft Depending on the vehicle integration it allows you to take control over the charge process cli-mate control tuning parameters of the engine and more OVMS developers are enthusiasts trying hard to provide asdetailed information about the internals of a vehicle as possible

While most new vehicles now include some kind of remote control system very few allow deep insight some willnot work in all regions and none will give you control over your personal data The OVMS fills that gap and alsoenables you to add all these features to existing vehicles of any kind

The OVMS can also be used for fleet monitoring It allows a fleet manager to not only track the vehicle locations butalso to monitor the vehiclersquos vitals remotely check for fault conditions offer services like automatic preheating forusers and take active control in case of abusive use As the system is open source and fully scriptable it can easilyintegrate custom access and control systems

For developers and technicians the OVMS includes a range of CAN tools including multiple logging formats aconfigurable OBD2 translator a DBC decoder a reverse engineering toolkit and a CANopen client The moduleprovides SSH access and WebSocket streaming and can stream and inject CAN frames via TCP Both the module andthe web frontend can be customized by plugins The module has three builtin CAN buses and can be extended by afourth one

The OVMS base component is a small and inexpensive hardware module that connects to the vehicle OBD2 port Thestandard kit includes a 3G modem to provide GSM connectivity and GPS and comes with a ready-to-use HologramioSIM card The US kit has been FCC certified the EU kit CE certified

The module provides a built-in Web App user interface and remote control via native cellphone Apps available forAndroid and iOS It integrates into homeprocess automation systems via MQTT and provides data logging to SDcard and to a server

12 Vehicle Support

bull Native Integration

ndash Chevrolet Volt Opel Ampera

ndash Chevrolet Bolt EV Opel Ampera-e

ndash BMW i3 i3s

ndash Fiat 500e

ndash Hyundai Ioniq vFL

ndash Jaguar Ipace

ndash Kia e-Niro Hyundai Kona

ndash Kia Soul EV

ndash Maxus eDeliver 3

ndash Mercedes-Benz B250E

ndash MG ZS EV

ndash Mitsubishi Trio (i-MiEV et al)

ndash Nissan Leaf e-NV200

ndash Renault Twizy

ndash Renault Zoe Kangoo

4 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

Open Vehicles

ndash Smart ED Gen3

ndash Smart EDEQ Gen4 (453)

ndash Tesla Model S

ndash Tesla Roadster

ndash Think City

ndash Toyota RAV4 EV

ndash VW e-Up

bull General Support

ndash DBC File Based

ndash GPS Tracking

ndash OBD-II Standard

ndash Zeva BMS

13 Links

bull User Resources

ndash User and Developer Guides (hint version selection in left menu at the bottom)

Stable release (OTA version ldquomainrdquo)

Latest nightly build (OTA version ldquoedgerdquo)

ndash User Support Forum

ndash Android App

ndash iOS App

bull Distributors

ndash FastTech (global)

ndash Medlock amp Sons (North America)

ndash OpenEnergyMonitor (UKEurope)

bull Servers

ndash Asia-Pacific

ndash GermanyEurope

bull Developers

ndash Developer Guide

ndash Developer Mailing List amp Archive

ndash Server Source

ndash Android App Source

ndash iOS App Source

13 Links 5

Open Vehicles

14 Hardware

bull Module Schematics and PCB Layouts

bull Base Module (v30-33)

ndash Black injection-moulded plastic enclosure approximately 99x73x29 mm excl plugs

ndash ESP32 WROVER processor (16MB flash 4MB SPI RAM 520KB SRAM dual core 160240MHz XtensaLX6 processor)

ndash WIFI 80211 bgn

ndash Bluetooth v42 BREDR and BLE

ndash 3x CAN buses

ndash 1x Micro USB connector (for flash download and serial console)

ndash 1x Micro SD card slot

ndash 1x Internal expansion slot

ndash 8x EGPIO 2x GPIO

ndash 1x GSM antenna connector

ndash 1x GPS antenna connector

ndash 1x DB9 vehicle connector

ndash 1x DB26 expansion connector

bull Modem Module v30-32

ndash US edition is SIM5360A (Dual-Band UMTSHSPA+ 8501900MHz Quad-Band GSMGPRSEDGE85090018001900MHz)

ndash EU edition is SIM5360J(E) (Dual-Band UMTSHSPA+ 9002100MHz Quad-Band GSMGPRSEDGE85090018001900MHz)

ndash 3G (EV-DOHSPA+) dual band modem

ndash Includes 2G (GSMGPRS) and 25G (EDGE) quad band

ndash GPSGNSS

6 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

Open Vehicles

ndash Nano (4FF) SIM slot

ndash HOLOGRAMIO nano sim included (can be exchanged if necessary)

bull Modem Module v33

ndash World edition SIM7600G (Multi-Band LTE-FDDLTE-TDDHSPA+ and GSMGPRSEDGE)

ndash 4G (LTE-FDDLTE-TDD) multi band modem

ndash Includes 3G (EV-DOHSPA+) 2G (GSMGPRS) and 25G (EDGE) quad band

ndash GPSGNSS

ndash Nano (4FF) SIM slot

ndash HOLOGRAMIO nano sim included (can be exchanged if necessary)

141 Extensions

The external DB26 DIAG connector provides access to the three CAN buses and offers some free extension ports Theinternal PCB expansion connector allows stacked additions of further modules and serves for routing GPIO ports tothe external DIAG connector See schematics for details

A very nice first extension module has been developed by Marko Juhanne OVMS-SWCAN

If you plan on developing a hardware extension or just want to do some custom adaptations have a look at ourprototyping PCB kit Itrsquos available in packs of 3 PCBs and includes headers and mounting material

If the kit isnrsquot available at the distributors please contact Mark Webb-Johnson markwebb-johnsonnet

14 Hardware 7

Open Vehicles

15 Development and Contributions

New developers are very welcome on any part of the system and we will gladly provide any help needed to getstarted

The purpose of this project is to get the community of vehicle hackers and enthusiasts to be able to expand the projectWe canrsquot do it all and there is so much to do What we are doing is providing an affordable and flexible base that thecommunity can work on and extend

Everything is open and APIs are public Other car modules can talk to the server and other Apps can show the statusand control the car This is a foundation that others hopefully will interface to and and build upon

If yoursquod like to contribute please accept our code of conduct

bull Introduce yourself on the developer mailing list

bull Be kind amp polite

bull Understand the framework concepts

bull Ask if you need help

bull Present your plans if in doubt

bull Write decent code

bull If you extend modules stick to their code style

bull Write brief but descriptive commit comments

bull Add user level descriptions to the change history

bull Provide documentation in the user guide

bull Use pull requests to submit your code for inclusion

A note on pull requests

Pull requests shall focus on one specific issue feature vehicle at a time and shall only mix vehicle specific changeswith framework changes if they depend on each other If changes are not or only loosely related split them intomultiple PRs (just as you would do with commits)

Usage hint create a branch for each pull request include only those commits in that branch (by cherry-picking ifnecessary) that shall be included in the pull request That way you can push further commits to that branch Githubwill automatically add them to an open pull request

16 Donations

The OVMS is a non-profit community project Hardware production and service can normally be financed by salesbut some things (eg prototype development and certifications) need extra money To help the project you can makea donation on the OVMS website httpswwwopenvehiclescomforum

Please also consider supporting the vehicle developers directly Check out their web sites and support addresses fortheir respective donation channels

Thank you

8 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

Open Vehicles

17 License

The project includes some third party libraries and components to which their respective licenses apply see componentsources for details

The project itself is published under the MIT license

Copyright (c) 2011-2020 Open Vehicles

Permission is hereby granted free of charge to any person obtaining a copy of this software and associated documen-tation files (the ldquoSoftwarerdquo) to deal in the Software without restriction including without limitation the rights to usecopy modify merge publish distribute sublicense andor sell copies of the Software and to permit persons to whomthe Software is furnished to do so subject to the following conditions

The above copyright notice and this permission notice shall be included in all copies or substantial portions of theSoftware

THE SOFTWARE IS PROVIDED ldquoAS ISrdquo WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIEDINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PAR-TICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTIONOF CONTRACT TORT OR OTHERWISE ARISING FROM OUT OF OR IN CONNECTION WITH THE SOFT-WARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

Software which uses other licenses will be annotated appropriately

17 License 9

Open Vehicles

10 Chapter 1 Open-Vehicle-Monitoring-System-3 (OVMS3)

CHAPTER 2

User Guide

21 Warnings and Notices

211 OVMS-33-7600G FCC Statement

This equipment has been tested and found to comply with the limits for a Class B digital device pursuant to part15 of the FCC Rules These limits are designed to provide reasonable protection against harmful interference in aresidential installation This equipment generates uses and can radiate radio frequency energy and if not installedand used in accordance with the instructions may cause harmful interference to radio communications Howeverthere is no guarantee that interference will not occur in a particular installation If this equipment does cause harmfulinterference to radio or television reception which can be determined by turning the equipment off and on the user isencouraged to try to correct the interference by one or more of the following measures

bull Reorient or relocate the receiving antenna

bull Increase the separation between the equipment and receiver

bull Connect the equipment into an outlet on a circuit different from that to which the receiver is connected

bull Consult the dealer or an experienced radioTV technician for help

Caution Any changes or modications to this device not explicitly approved by manufacturer could void your authorityto operate this equipment

This device complies with part 15 of the FCC Rules Operation is subject to the following two conditions (1)This device may not cause harmful interference and (2) this device must accept any interference received includinginterference that may cause undesired operation

212 OVMS-33-7600G Specific Absorption Rate (SAR) information

This OVMS-33-7600G meets the governmentrsquos requirements for exposure to radio waves The guidelines are basedon standards that were developed by independent scientific organizations through periodic and thorough evaluationof scientific studies The standards include a substantial safety margin designed to assure the safety of all personsregardless of age or health FCC RF Exposure Information and Statement the SAR limit of USA (FCC) is 16 Wkg

11

Open Vehicles

averaged over one gram of tissue Device types OVMS-33-7600G has also been tested against this SAR limit Thisdevice was tested for typical body-worn operations with the back of the phone kept 0mm from the body To maintaincompliance with FCC RF exposure requirements use accessories that maintain an 0mm separation distance betweenthe userrsquos body and the back of the phone The use of belt clips holsters and similar accessories should not containmetallic components in its assembly The use of accessories that do not satisfy these requirements may not complywith FCC RF exposure requirements and should be avoided

213 OVMS-33-7600G CE Statement

EU importer information

OpenEnergyMonitorInTec F9Ffordd y Parc Parc MenaiBangorLL57 4FGUnited Kingdom

This product can be used across EU member states

Specification

12 Chapter 2 User Guide

Open Vehicles

Manufacturer Open Vehicles LtdHardware Version Software Version Frequency Range

bull 24G WIFI 2412MHz ~ 2472MHz(Max powerRated 1569dBm)

bull GSM 900 880MHz ~ 915MHz(Max powerRated 3266dBm)

bull DCS 1800 1710MHz ~ 1785MHz(Max powerRated 2975dBm)

bull WCDMA Band I 1920MHz ~ 1980MHz(Maxpower Rated 2340dBm)

bull WCDMA Band VIII 880MHz~915MHz(Maxpower Rated 2310dBm)

bull E-UTRA Band 1 1920MHz ~ 1980MHz(Maxpower Rated 2280dBm)

bull E-UTRA Band 3 1710MHz~1785MHz(Maxpower Rated 2240dBm)

bull E-UTRA Band 7 2500MHz ~ 2570MHz(Maxpower Rated 2297dBm)

bull E-UTRA Band 8 880MHz ~ 915MHz(Maxpower Rated 2240dBm)

bull E-UTRA Band 20 832MHz ~ 862MHz(Maxpower Rated 2295dBm)

bull E-UTRA Band 28 703MHz ~ 748MHz(Maxpower Rated 2237dBm)

bull E-UTRA Band 34 2010MHz ~ 2025MHz(Maxpower Rated 2279dBm)

bull E-UTRA Band 38 2570MHz ~ 2620MHz(Maxpower Rated 2296dBm)

bull E-UTRA Band 40 2300MHz ~ 2400MHz(Maxpower Rated 2348dBm)

Receiver category 3

Members applicability

1 Extreme temperature -20-45 Celcius

2 The device complies with RF specifications when the device used at 5mm form your body

3 RED 201453EU

Declaration of Conformity

Hereby Open Vehicles Ltd declares that this OVMS-33-7600G product is in compliance with essential requirementsand other relevant provisions of Directive 201453EU A copy of the Declaration of conformity can be found atwwwopenvehiclescom

21 Warnings and Notices 13

Open Vehicles

214 General Warnings

WarningOVMS is a hobbyist project not a commercial product It was designed by enthusiasts for enthusiasts Installationand use of this module requires some technical knowledge and if you donrsquot have that we recommend you contactother users in your area to ask for assistance

WarningThe OVMS module is continuously powered by the car even when the car is off While the OVMS module usesextremely low power it does continuously draw power from the carrsquos battery so it will contribute to lsquovampirersquo powerdrains

Do not allow your car battery to reach 0 SOC and if it does plug in and charge the car immediately Failure to dothis can result in unrecoverable failure of the carrsquos battery

The module can monitor the main and 12V battery and send alert notifications if the SOC or voltage drops below ahealthy level

215 Average Power Usage

The power used by the module depends on the component activation You can save power by disabling unusedcomponents This can be done automatically by the Power Management module to avoid deep discharging the 12Vbattery or you can use scripts to automate switching components off and on

The base components need approximately these power levels continuously while powered on

Component Avg Power 12V CurrentBase System 200 mW 17 mAWifi 330 mW 28 mAModem 170 mW 13 mAGPS 230 mW 19 mATotal 930 mW 78 mA

This adds up to

bull ~ 22 Wh or 2 Ah day

14 Chapter 2 User Guide

Open Vehicles

bull ~ 156 Wh or 13 Ah week

bull ~ 680 Wh or 57 Ah month

Note that depending on the vehicle type the module may also need to wake up the ECU periodically to retrieve thevehicle status Check the vehicle specific documentation sections for hints on the power usage for this and options toavoid or reduce this

22 Components

221 The OVMS Module

The OVMS v3 module is housed in a plastic enclosure held secure by four small screws Once open you can see themain OVMS v3 motherboard and an optional modem board

At one end of the module is the main DB9 connector you will use to connect to the vehicle as well as GSM (cellular)and GPS (positioning) antenna connections

At the other end of the module is the DA26 expansion connector the USB diagnostic connector and a Micro SD cardslot

Warning The USB port is a fragile PCB socket without reinforcement Handle it carefully do not apply forcewhen plugging or unplugging cables to not bend the plug If you need to use the port frequently two dots of hotglue at the port sides on the PCB can help to avoid breaking it off

If you open the module and take out the board take care to guide the port carefully and correctly into itrsquos case holewhen inserting the board into the casing again Insert the board USB port side first

If removinginstalling optional expansion boards (such as used for cellular connectivity) please take care to ensureyou secure screw down the expansion board using the four pillar posts provided Also please ensure that the cellularmodem connections are correct (follow the printed table on the modem board to know which antenna is which)

22 Components 15

Open Vehicles

WarningThe OVMS v3 enclosure is not waterproof and the components can be damaged by water Do not get the modulewet and do not connect it to your vehicle if it is wet

222 Cellular Modem Option and GSM Antenna

The cellular modem option allows you to control your vehicle when out of wifi coverage range The majority ofOVMS users choose this option and you will require it if you want to monitor your vehicle when away from home oroffice

OVMS modules sold in USA and Europe are provided with a Hologram SIM card pre-installed This low cost serviceallows you to get cellular connectivity simply It also allows you to roam between countries without worry Formodules purchased from China we recommend you purchase a Hologram SIM directly from the hologramio store(also available on Amazon)

Depending on settings verbosity towards the OVMS server rhythm of GPS tracking etc OVMS v3 will use between1 and 3 Megabytes per month of data (when using the v2 server protocol)

You do not have to use the Hologram service If you use another cellular provider the Sim Card format required is4FF Nano Micro Sim cards are hard to recut into the smaller format so please be careful to not damage the socketotherwise ask your operator for a swap (some do it for free)

If you are using the cellular option you should attach a suitable cellular antenna to the module using the antennaconnector labeled ldquoGSMrdquo

Modem Status LED

The blue LED on the modem board shows the current modem status

LED Status SIM5360 (3G) SIM7600 (4G)ON Searching network Searching networkFast blinking (200ms) Data Transmit Data Transmit 4G registeredSlow blinking (800ms) Registered network 2G3G registered networkOFF Power off Sleep Power off Sleep

223 GPSGNSS Antenna

Some OVMS vehicles can read the GPS signals from the car communication networks directly and do not require anyadditional hardware For others the OVMS v3 modem option also includes a GNSSGPS satellite tracking receiver

If you are using this option you should connect a suitable active GPS antenna to the connector labelled ldquoGPSrdquo

16 Chapter 2 User Guide

Open Vehicles

224 Vehicle Connection

The connection to the vehicle is by the DB9 connector labelled ldquoVEHICLErdquo This provides power to the OVMSmodule as well as connection to the vehicle communication networks

Different vehicles require different cables so you should refer to the appropriate vehicle section of this user guide todetermine which is correct for yours

225 OVMS Server v2

The OVMS Server v2 protocol is a proprietary protocol used to communicate between the vehicle and an OVMS v2server as well as from that server to the cellphone apps To provide compatibility with existing OVMS v2 cellphoneapps and servers OVMS v3 includes full support for the OVMS v2 protocol

226 OVMS Server v3

The OVMS Server v3 protocol is MQTT This is an industry standard protocol and means an OVMS v3 module cancommunicate with any standard MQTT server While this is the future of OVMS support for this is experimental atthe moment and production users should use OVMS Server v2 protocol

227 Upgrading from OVMS v1v2 to v3

The antenna and vehicle connectors for OVMS v3 are the same as for OVMS v2 and existing cablesantennas cangenerally be re-used for OVMS v3 Note however that the frequency ranges supported by individual 3G networksmay be different than 2G so may benefit from an antenna specifically designed for the 3G frequency ranges used

23 Installation

231 Pre-Installation Steps

WarningPrior to connecting the OVMS module to the vehicle or computer via USB if you have the GSM cellular option werecommend you connect a GSM antenna GSM systems are designed to always operate with an antenna andpowering on one without could damage the equipment

Prior to installation please make sure you have the following available

1 The OVMS v3 module in itrsquos enclosure

2 A micro-usb cable suitable for connecting to your computer

3 A laptop or desktop computer (if necessary)

23 Installation 17

Open Vehicles

4 A cable suitable for connecting to your vehicle

5 A GSM antenna (if you are using the cellular option)

6 A GPS antenna (if your vehicle type requires one)

You should also have ready access to this User Guide and wifi connectivity to the Internet

232 OVMS Module Installation

Powering the module

If you intend to configure the module on your desk before connecting it to the vehicle make sure your USB portdelivers power (around 500mA depending on modem and wifi activity) We recommend using a USB hub with aseparate power supply or a direct port of your laptop PC

Warning The v33 LTE Modem (SIMCOM 7600G) may not be able to connect or not power up at all whenpowered from USB even with a powered USB hub

If you cannot get the cellular connection to work on your desk try powering from your carrsquos OBD port first

Another option is adding a 12V supply on your desk eg using a standard RC 3S LiPo battery (connect 12V+ toOBD pin 16 and GND- to OBD pin 4) You can connect USB and OBD12V supply simultaneously be aware themodule will boot as soon as any power source is present

OVMS Server account

If you want to use the OVMS App andor server based telemetry services yoursquoll need an OVMS v2 server account Ifyou have not registered for an OVMS server account yet you can do so before starting the wizard to avoid needing toswitch networks in between There are currently two public v2 OVMS servers

1 Asia-Pacific httpswwwopenvehiclescom

2 Europe httpsdexters-webde

You will need to create a user account first Within your user account you then need to create a vehicle account Yoursquollneed to pick a unique vehicle ID for this eg your vehicle license plate number

Initial Connection (Wifi and Browser)

From the factory or after a factory reset your OVMS module will be running an access point with the followingcredentials

SSID OVMS Password OVMSinit

As this is insecure you should take care not to leave the module running unconfigured

Using your laptoptabletphone establish a wifi connection to the module You should see an IP address in the range1921684x allocated with a gateway at 19216841

Note Some smartphones (eg Android) require mobile data to be switched off to use a WiFi connection without ainterent connectivity

Launch your web browser and connect as follows

URL http19216841

Once connected you will be presented with a screen as follows

18 Chapter 2 User Guide

Open Vehicles

23 Installation 19

Open Vehicles

Setup wizard

The first thing to do is run the setup wizard Click Start setup now The wizard takes you through the initial setup infive simple steps telling you what it is doing and what to expect for each step

20 Chapter 2 User Guide

Open Vehicles

23 Installation 21

Open Vehicles

The wizard will need to reconfigure the module for the Wifi setup read the notes and be prepared to reconnect to themodule as necessary

Note we recommend not to use a password manager during the setup process Some browsers eg Chrome will fillin the module ID as the username which is wrong The login username needs to be admin

The wizard should be able to restore access after problems occurring in the process As a last resort if it fails to recoverat some point you can always do a factory reset and start over again

Manual configuration

After finishing the wizard or if you prefer to do a manual setup the configuration menus will provide single pages foreach module function These also contain advanced options for the features so itrsquos worth having a look

Vehicle Configuration

Go to Config Vehicle

Yoursquoll want to enter your vehicle type Vehicle ID (the same as you registered on the OVMS server) and distance unitsYou can also optionally enter your timezone (see httpswwwgnuorgsoftwarelibcmanualhtml_nodeTZ-Variablehtml for an article on GLIBC timezones for information on the format of this a list of suitable zone strings can alsobe found here httpsremotemonitoringsystemscatime-zone-abbreviationsphp)

OVMS Server v2 Configuration

Go to Config Server V2 to configure the connection to the OVMS v2 server you will be using

22 Chapter 2 User Guide

Open Vehicles

You should enter the server host (apiopenvehiclescom or ovmsdexters-webde usually) and vehicle password (akaserver password - as entered on the server when you registered your vehicle) The Vehicle ID field should already bethere and the other parameters are optional

Auto Start Configuration

OVMS has a powerful scripting language that can be used for complex configurations but to get started it is simplestto use the Auto Start system You get to this from the web interface by clicking Config Autostart

23 Installation 23

Open Vehicles

You will usually want to click to Enable auto start and Start server v2 The other fields should have been populatedcorrectly automatically for you If you are using the optional modem module you should also click Start modem toenable the modem

Once complete you can Save amp reboot to activate your new configuration

WarningDo not set the Wifi mode to AP+Client or Client before having configured your Wifi network

If you have configured this manually the Wifi network may not start automatically Log in using a USB terminal andeither do a factory reset (see Module Factory Reset) or (better) issue enable to enter secure mode then issue configset auto wifimode ap and reboot

Networking Options

OVMS v3 has a number of networking options to choose from You can either use these individually or combine themto provide failover and alternative network connectivity arrangements

1 Wifi Client OVMS can connect to a WiFi Access Point using standard WiFi (80211 bgn) protocols toconnect to a SSID (Access Point name) with associated password In simple client mode you can connect onlyto a single pre-specified SSID Alternatively you can use the scanning client mode to connect to any known

24 Chapter 2 User Guide

Open Vehicles

WiFi Access Point when within range (note however that this is not possible when you run both client andaccess point on the same OVMS device)

2 Wifi Access Point OVMS can operate as a WiFi Access Point itself using standard WiFi (80211 bgn) pro-tocols This allows users to connect to the OVMS module itself Note that OVMS v3 is not intended to be ahotspot and users cannot access the Internet via the OVMS module Wifi Access Point mode can be combinedwith simple Wifi Client mode to provide an access point for maintenance of the module as well as a client toaccess the Internet via another Access Point within range

3 Cellular Data OVMS supports optional modems to provide cellular connectivity These are configured viaConfig Modem

233 GSM SIM Activation (Hologram)

OVMS has partnered with Hologram and to provide a Hologram GSM SIM pre-installed in every OVMS kit purchasedfrom our partners in Europe and USA For modules purchased from China we recommend you purchase a HologramSIM directly from the hologramio store (also available on Amazon) In addition Hologram have provided OVMS acoupon code valid for US$5 off data usage

Hologram Coupon Code OVMS

To activate your Hologram SIM register at httpsdashboardhologramio then invoke ldquoActivate SIMrdquo in the dash-board

Note You donrsquot need to purchase a phone number for your SIM right now as there is no SMS support in V3 yet Forthe current status of SMS support see

bull Issue 62 SMS Notifications

bull Issue 63 SMS Command Gateway

When activating your Hologram SIM yoursquoll need to enter the ICCID written on the SIM itself You can also get thatelectronically (without having to open up the enclosure) from the OVMS web or terminal shell (Tools gt Shell) withthe following command

OVMS metric list mnetmdmiccid

The ICCID is also displayed during the setup process and on the modem configuration page when using the web userinterface

23 Installation 25

Open Vehicles

234 Firmware Update

The factory firmware that is provided with the module may be quite out of date You should perform a firmware updateto ensure that you have the latest firmware You can do this either over Wifi client connections or via an SD CARD

We recommend using the auto update system This will be preconfigured if you have used the setup wizard Theautomatic updates are done within a selectable hour of day and only if Wifi connectivity is available at the time

26 Chapter 2 User Guide

Open Vehicles

Flash from Web

You can typically just press the Flash now button and wait for completion

Flash from File

Using an SD CARD formatted as FAT download the firmware update and place it in a file called ovms3bin in theroot directory of the SD CARD Once the SD CARD is inserted the firmware update will start immediately

235 12V Monitoring

Note Since release 32006 the 12V calibration and alert setup can be done from the web UIrsquos vehicle configurationpage

As 12V batteries tend to die without warning and need to handle an additional unplanned constant load from theOVMS the module includes a 12V monitoring and alert system

Calibration

The 12V voltage is measured using the incoming voltage that powers the OVMS As the sensor used by the modulehas some manufacturing tolerances you should do an initial calibration Use a voltage meter to measure the actualvoltage somewhere suitable (eg at a 12V auxiliary equipment plug) calibrate the OVMS to show the same Thecalibration factor is set by

config set systemadc factor12v ltfactorgt

Calculate the ltfactorgt using oldFactor (displayedVoltage actualVoltage)

bull oldFactor is the old value set If you have not changed it yet it is 1957

bull displayedVoltage is the Voltage as displayed by the OVMS

bull actualVoltage is the Voltage as measured by hand using a voltmeter

The voltage is read once per second and smoothed over 5 samples so after changing the factor wait 5-10 seconds forthe new reading to settle

23 Installation 27

Open Vehicles

Configuration

The default 12V reference voltage (= fully charged amp calmed down voltage level) can be set by

config set vehicle 12vref ltvoltagegt

This config value initializes metric vb12vvoltageref on boot The metric will then be updated automati-cally if your vehicle supports the vecharging12v flag The measured reference voltage reflects the health of the12V battery and serves as the reference for the 12V alert if itrsquos higher than the configured default

The 12V alert threshold can be set by

config set vehicle 12valert ltvoltagediffgt

The 12V alert threshold is defined by a relative value to the 12v reference voltage If the actual 12V reading dropsbelow 12vref - 12valert the 12V alert is raised

The default reference voltage is 126V the default alert threshold 16V so the alert will be triggered if the voltagedrops below 110V This is suitable for standard lead-acid type batteries If yoursquove got another chemistry change thevalues accordingly

Related Metrics

Metric Example Value Meaningvb12vcurrent 06A Momentary current level at the 12V batteryvb12vvoltage 1328V Momentary voltage level at the 12V batteryvb12vvoltageref 1251V Reference voltage of the fully charged amp calmed down 12V batteryvb12vvoltagealert no If the 12V critical alert is active (yesno)vecharging12v yes If the 12V battery is charging or not (yesno)

Related Events

Event Data Purposevehiclealert12von 12V system voltage is below alert thresholdvehiclealert12voff 12V system voltage has recoveredvehiclecharge12vstart Vehicle 12V battery is chargingvehiclecharge12vstop Vehicle 12V battery has stopped charging

24 The OVMS Console

241 Console Connections

OVMS v3 includes a powerful command line console that can be accessed in various ways

1 Using a micro USB cable to a host computer

If the OVMS is not recognised via USB download the driver from SILABS website You will also need asuitable terminal emulator The baud rate is 115200 and you should not enable hardware flow control

2 TELNET (over wifi)

28 Chapter 2 User Guide

Open Vehicles

Note that for security reasons the telnet server component is not enabled in the default productionfirmware (but may be available in custom builds) If Telnet is available telnet to the IP address of themodule (or ltvehicleidgtlocal MDNS address)

3 SSH (over wifi)

SSH to the IP address of the module (or ltvehicleidgtlocal MDNS address) Note that when first bootedwith a network connection the module takes a minute or so to generate server side keys (which are storedin the config store)

4 Web Console SHELL tab

Use a web browser to connect to the IP address of the module (or ltvehicleidgtlocal MDNS address) ASHELL tab is available for direct command line console access

5 Remote Apps

The OVMS Android App currently includes a shell screen that can be used to issue command line consolecommands via the OVMS server v2 This functionality is not currently available in the iPhoneiPad App

6 SMS

Console commands can be issued via SMS

USB Console

Our recommendations for the USB console are as follows

1 You can use a Windows Linux Mac OSX workstation or an Android device with a USB OTG adapter cable

2 If your operating system does not have the SILABS USB driver you can download the driver from SILABSwebsite If you use Linux and your distribution includes the braille display driver ldquobrlttyrdquo you may need touninstall that as it claims any CP2102 device to be a braille device This applies eg to openSuSE 150

3 Plug in the module to your PClaptop using a micro USB cable Check to ensure a serial port appears (using theSILABS driver) For OSX and Linux this will normally appear as devttySLAB_USBtoUART or devttyUSB0(or 12 if other serial devices are connected) List your devices using ldquols devUSBrdquo

4 Once the serial port is available you will need a terminal emulator

bull For OSX the simplest is the built-in SCREEN utility You run this as screen -L devttySLAB_USBtoUART 115200 But note that the device path may be different for you - check with lsquolsdevUSBrsquo You can use lsquocontrol-a control-yrsquo or lsquocontrol-a k yrsquo (three key sequences) to exit the screenThe ldquo-Lrdquo option tells screen to capture a log of your session into the file ldquoscreenlogltngtrdquo

bull For Linux the SCREEN utility is also simple to get If it is not included with your distribution you can simplyyum install screen or apt-get install screen (depending on your distribution) From there the command is thesame as for OSX Alternatively you can use minicom (which is included with many linux distributions)

bull For Windows a simple approach is to download the free PUTTY terminal emulator This supports both directASYNC (over USB) connections as well as SSH (network) You can download putty using this link

bull For Android there are multiple USB serial Apps in the Play store A good recommendation is Serial USBTerminal by Kai Morich

5 Once you have established the connection press ENTER to see the ldquoOVMSgtrdquo prompt

SSH Console

A workstation (Mac Linux Window) on the same wifi network as the OVMS module can use the ssh protocol toconnect In Windows you can use the free PUTTY ssh client In Linux and OSX ssh is built-in

24 The OVMS Console 29

Open Vehicles

The syntax is simply

ssh userip

Where lsquouserrsquo is the username (normally lsquoovmsrsquo) and lsquoiprsquo is the IP address of the OVMS v3 module In environmentssupporting mDNS networking you should also be able to connect using the mDNS name ltvehicleidgtlocal Thepassword you enter is the module password

If you use ssh publicprivate key pairs you can store your public key on the OVMS v3 module to take advantage ofpasswordless login

OVMS config set sshkeys ltusergt ltpublic-keygt

In this case lsquouserrsquo is the username you use to ssh and the public key is your RSA public key (the long base64 blob oftext you find in id-rsapub between lsquossh-rsarsquo and your usernamecomment)

You can also use SCP to copy files to and from the OVMS v3 VFS

Note With OpenSSH version 88 (or later) the ssh-rsa algorithm has been disabled by default and needs to beenabled manually either on the command line

ssh -o HostkeyAlgorithms=+ssh-rsa -o PubkeyAcceptedAlgorithms=+ssh-rsa userip

or by adding a host entry to your ~sshconfig file

Host ovmsnamelocalHostkeyAlgorithms +ssh-rsaPubkeyAcceptedAlgorithms +ssh-rsa

242 Console Basics

Letrsquos use SSH to demonstrate this

$ ssh ovmsovmslocal

Welcome to the Open Vehicle Monitoring System (OVMS) - SSH ConsoleFirmware 31003-2-g7ea18b4-dirtyfactorymainHardware OVMS WIFI BLE BT cores=2 rev=ESP321

OVMS

When first connecting using USB the console will be in non-secure mode (as indicated by the ldquoOVMSgtrdquo prompt)Here only a limited number of commands are available (such as viewing network status modem status or systemtime) To get to secure mode enter the command lsquoenablersquo and provide the module password The prompt will thenchange to ldquoOVMSrdquo

OVMSgt enablePasswordSecure modeOVMS

You can enter the lsquodisablersquo command to get out of secure mode and lsquoexitrsquo to exit the console completely

When connecting via a pre-authenticated protocol such as SSH you will be in secure mode automatically

At any time you can use ldquordquo to show the available commands For example

30 Chapter 2 User Guide

Open Vehicles

OVMS Run a scriptboot BOOT frameworkcan CAN frameworkcharge Charging frameworkco CANopen frameworkconfig CONFIG frameworkdisable Leave secure mode (disable access to most commands)egpio EGPIO frameworkenable Enter secure mode (enable access to all commands)event EVENT frameworkexit End console sessionhelp Ask for helphomelink Activate specified homelink buttonlocation LOCATION frameworklock Lock vehiclelog LOG frameworkmetrics METRICS frameworkmodule MODULE frameworknetwork NETWORK frameworknotify NOTIFICATION frameworkobdii OBDII frameworkota OTA frameworkpower Power controlre RE frameworkscript Run a scriptsd SD CARD frameworkserver OVMS Server Connection frameworkmodem MODEM frameworkstat Show vehicle statusstore STORE frameworktest Test frameworktime TIME frameworkunlock Unlock vehicleunvalet Deactivate valet modevalet Activate valet modevehicle Vehicle frameworkvfs Virtual File System frameworkwakeup Wake up vehiclewifi WIFI framework

You can also use ldquordquo as part of a command to expand on the available options within that command root

OVMS wifi mode WIFI mode frameworkscan Perform a wifi scanstatus Show wifi status

OVMS wifi mode ap Acts as a WIFI Access Pointapclient Acts as a WIFI Access Point and Clientclient Connect to a WIFI network as a clientoff Turn off wifi networking

OVMS wifi mode client Usage wifi mode client ltssidgt ltbssidgt

Command tokens can be abbreviated so long as enough characters are entered to uniquely identify the command Op-

24 The OVMS Console 31

Open Vehicles

tionally pressing TAB at that point will auto-complete the token If the abbreviated form is not sufficient to be unique(in particular if no characters have been entered yet) then TAB will show a concise list of the possible subcommandsand retype the portion of the command line already entered so it can be completed

OVMS wifi ltTABgtmode scan statusOVMS wifi

Pressing TAB is legal at any point in the command if there is nothing more that can be completed automatically thenthere will just be no response to the TAB

25 Logging

251 Logging to the Console

Components of the OVMS system output diagnostic logs (information warnings etc) You can choose to displaythese logs on your connected console with the lsquolog monitor yesnorsquo command

OVMS log monitor Usage log monitor [no|yes]no Dont monitor logyes Monitor log

By default the USB console will have log monitoring lsquoyesrsquo SSH (and telnet if enabled) lsquonorsquo

The web shell does not use the log monitor command but has a checkbox in the upper right corner of the shellpanel instead The keyboard shortcut for the checkbox is L (Alt-L or Alt-Shift-L depending on your browser) Theweb frontend gets the continuous stream of log messages independent of the shell panel or the monitoring being activeand shows the last 100 messages received when opening the shell panel

Logs are output at various levels of verbosity and you can control what is shown both globally and on a per-componentbasis

OVMS log level none No logging (0)error Log at the ERROR level (1)warn Log at the WARN level (2)info Log at the INFO level (3)debug Log at the DEBUG level (4)verbose Log at the VERBOSE level (5)

(Note sorted here for level clarity)

The syntax of this command is log level ltlevelgt [ltcomponentgt] If the component is not specified thelevel applies to all components that donrsquot get a level set explicitly afterwards The levels increase in verbosity andsetting a particular level will also include all log output at a lower level of verbosity (so for example setting level infowill also include warn and error output)

A log line typically looks like this

I (32244049) ovms-server-v2 One or more peers have connectedLog message

Component nameTimestamp (milliseconds since boot)

Log level (I=INFO)

32 Chapter 2 User Guide

Open Vehicles

Log levels are applied on log message generation so a later change to a higher level will not reveal messages generatedpreviously

252 Logging to SD CARD

You can also choose to store logs on SD CARD This is very useful to capture debugging information for the develop-ers as the log will show what happened before a crash or misbehaviour

We recommend creating a directory to store logs ie

OVMS vfs mkdir sdlogs

To enable logging to a file issue for example

OVMS log file sdlogs20180420log

The destination file can be changed any time To disable logging to the file issue log close to restart loggingafter a close issue log open You may choose an arbitrary file name good practice is using some date andor bugidentification tag Note logging will append to the file if it already exists To remove a file use vfs rm

File logging does not persist over a reboot or crash (unless configured as shown below) you can use a script bound tothe sdmounted event to re-enable file logging automatically or configure automatic logging (see below)

You can use the webserver to view and download the files The webserver default configuration enables directorylistings and access to files located under the document root directory which is sd by default Any path not bound toan internal webserver function is served from the document root So you can get an inventory of your log files now atthe URL

http19216841logs

and access your log files from there or directly by their respective URLs Another option to retrieve the files withoutunmounting the SD card is by scp if you have configured SSH access

253 Logging Configuration

Use the web UI or config command to configure your log levels and file setup to be applied automatically on boot

OVMS config list loglog (readable writeable)

fileenable yesfilekeepdays 7filemaxsize 1024filepath sdlogslogfilesyncperiod 3level infolevelmodem infolevelv-twizy verboselevelwebserver debug

25 Logging 33

Open Vehicles

The log command can be used for temporary changes if you change the configuration it will be applied as a wholereplacing your temporary setup

If a maximum file size gt0 is configured the file will be closed and archived when the size is reached The archivename consists of the log file name with added suffix of the timestamp ie sdlogslog20180421-140356Using a logs directory will keep all your archived logs accessible at one place If filekeepdays is defined olderarchived logs will automatically be deleted on a daily base

Take care not to remove an SD card while logging to it is active (or any running file access) The log file should stillbe consistent as it is synchronized after every write but the SD file system currently cannot cope with SD removalwith open files You will need to reboot the module To avoid this always use the ldquoCloserdquo button or the log closecommand before removing the SD card

You donrsquot need to re-enable logging to an SD path after insertion the module will watch for the mount event andautomatically start logging to it

254 Performance Impact

SD card IO has an impact on the module performance So file logging should generally be switched off or runon a low level (ie ldquoinfordquo or ldquowarnrdquo) unless yoursquore hunting some bug or checking some details of operation Wealso recommend using a fast SD card for logging (check the speed with sd status check if you can raise configsdcard maxfreqkhz to 20000 kHz)

34 Chapter 2 User Guide

Open Vehicles

File logging is done by a separate task but flushing the file buffers to the SD card still may block the logging CPUcore or even both CPU cores for a short period To reduce the impact of this the log task by default only flushes thebuffer after 15 seconds of log inactivity This means you may lose the last log messages before a crash

To change the flush behaviour set config filesyncperiod to

bull 0 = never flush (ie only at log close log cycle)

bull lt 0 = flush every n log messages (ie -1 = flush after every message)

bull gt 0 = flush after n2 seconds idle

The log task counts the time spent for flushes and outputs it with the log status command

OVMS log statusLog listeners 3File logging status active

Log file path sdlogslogCurrent size 8170 kBCycle size 1024 kBCycle count 8Dropped messages 0Messages logged 70721Total fsync time 6511 s

This is an example for the default configuration of filesyncperiod 3 the logging here has on average taken6511 70721 = 9 ms per message

26 Configuration

OVMS stores all itrsquos configuration in a standardised protected configuration area accessed by the lsquoconfigrsquo commandThe configurations are organised as follows

ltparametergt ltinstancegt = ltvaluegt

For example

Parameter Instance Valuevehicle id OVMSBOXwifissid MYSSID MyPasswordauto init yes

Each parameter can be defined (by the component that owns it) as having readable andor writeable attributes andthese act as access control for the parameters

bull A lsquowriteablersquo parameter allows values to be created deleted and modified

bull A lsquoreadablersquo parameter allows values to be seen Instance names can be seen on non-readable parameters (it isjust the values themselves that are protected)

For example the lsquovehiclersquo parameter is readable and writeable

OVMS config list vehiclevehicle (readable writeable)

id MYCARtimezone HKT-8

But the lsquowifissidrsquo parameter is only writeable

26 Configuration 35

Open Vehicles

OVMS config list wifissidwifissid (protected writeable)

MYSSIDMyOtherSSIDMyNeighbour

The lsquoconfigrsquo command is used to manipulate these configurations as is fairly self-explanatory

OVMS config list Show configuration parametersinstancesrm Remove parameterinstanceset Set parameterinstance=value

You can add new instances to parameters simply by setting them

Beginning with firmware release 32009 a dedicated configuration section usr is provided for plugins Take care toprefix all instances introduced by a unique plugin name so your plugin can nicely coexist with others

27 WiFi Networking

The OVMS WiFi system is based on the ESP32 integrated WiFi transceiver It uses and provides WiFi protocols80211 bgn and WPA2 authentication The current hardware can only use 24 GHz frequency bands

The WiFi antenna is built into the ESP32 module (PCB antenna) Itrsquos possible to replace that by an external antennabut yoursquoll need electronics knowledge and SMD soldering skills amp equipment

271 Client amp Access Point Modes

The OVMS WiFi network can be configured as a client (connecting to existing WiFi networks) andor access point(providing itrsquos own private WiFi network) Both modes can be run simultaneously which is the recommended defaultThat way you can always connect to your module via WiFi

OVMS wifi statusPower onMode Access-Point + Client mode

STA SSID WLAN-214677 (-787 dBm) [scanning]MAC 30aea45fe7ecIP 19216821022552552550GW 19216821AP 7cff4d152f86

AP SSID DEX106EMAC 30aea45fe7edIP 19216841AP Stations 0

In client mode the module can connect to a fixed network or automatically scan all channels for known networks toconnect to (ldquoscanning moderdquo) Scanning mode is configured by enabling client mode without a specific client SSID

The module will normally receive an IP address gateway and DNS from the WiFi access point by DHCP See belowon how to connect with a manual static IP setup

36 Chapter 2 User Guide

Open Vehicles

In access point mode the module provides access for other WiFi devices on a private network with the IP subnet1921684024 The modulersquos IP address on this network is 19216841 The module does not provide aDNS or routing to a public WiFi or GSM network on this subnet

You can define multiple AP networks but only one can be active at a time

Use the wifi mode command to manually set the mode use the auto start configuration to configure your defaultmode and networks

Note The module cannot act as a mobile hotspot ie provide access to the internet via itrsquos modem connectionThatrsquos in part due to security considerations and in part due to hardware limitations If you need this considerinstalling a dedicated mobile hotspot and using that one via WiFi instead of the modem for the modulersquos internetaccess (you wonrsquot need the modem in this setup)

272 Scanning for Networks

To manually scan your environment for available WiFi networks do a wifi scan

OVMS wifi scanScanning for WIFI Access Points

AP SSID MAC ADDRESS CHAN RSSI AUTHENTICATION================================ ================= ==== ==== ==============WLAN-214677 7cff4d152f86 1 -83 WPA2_PSKTelekom_FON 78dd1209dcbe 11 -84 OPENWLAN-184248 78dd1209dcbc 11 -85 WPA2_PSK===========================================================================Scan complete 3 access point(s) found

This can also be done in the web UIrsquos WiFi client network configuration page by clicking on the Select button

After the module lost connection to a network a scan is performed automatically every 10 seconds until a new con-nection can be established If yoursquod like to see the background scans and results in the log enable log level verbosefor component esp32wifi

Scan Troubleshooting

If the module doesnrsquot find your access point or can only see it occasionally in the scan results you may need to raiseyour scan times This has been observed on some older Android hotspots

By default the module will scan each channel for 120 milliseconds To raise that set your scan time in millisecondsusing the config command like this eg to 200 milliseconds

OVMS config set network wifiscantmin 200

200 milliseconds have been reported to solve the Android hotspot issue In addition to the tmin configuration youmay need to allow more time looking for further access points after finding the first one Do so by setting tmax eg

OVMS config set network wifiscantmax 300

Note that every increase will increase the time a full scan takes so donrsquot set too high values Too high values mayresult in connection drops on the AP network of the module

27 WiFi Networking 37

Open Vehicles

273 WiFi Signal Quality

Note For best performance yoursquoll need a signal level of -85 dBm or higher

bull Open the web status page the Wifi signal level can be monitored in the ldquoLiverdquo box

bull Try moving turning tilting your router ndash centimeters can make a huge difference After each move step backfrom the router and watch how the signal develops

bull Try switching to another Wifi channel (router configuration)

bull Try adding a repeater half way from the router to the car

The module monitors the WiFi client signal quality and drops a WiFi connection (switches to modem if available) if itbecomes too bad The WiFi connection will be kept active and monitored and as the signal recovers the module willautomatically reconnect to the AP

The default threshold is to stop using the connection if it drops below -89 dBm A connection is assumed to be usableif the signal is above -87 dBm

Depending on your WiFi environment the WiFi connection may still be usable at lower signal levels but it normallywill need stable levels above -87 dBm

To tweak the thresholds use the web UI WiFi configuration or change the following configuration variables

OVMS config set network wifisqgood -870OVMS config set network wifisqbad -890

274 WiFi Mesh Configuration

In normal operation the module will try to stick to an established connection as long as possible If signal qualitydrops it will switch to the modem connection but monitor the WiFi signal and reassociate to the current AP if possible

If using a mesh network you may want to force scanning for a better mesh AP as soon as the signal drops below theldquobadrdquo threshold To do so set the network configuration wifibadreconnect to true either using the web UIor by doing

OVMS config set network wifibadreconnect yes

With this the module will perform a full WiFi reconnect cycle as soon as the signal becomes bad

This is meant for the car moving between cells of your mesh network eg if the first cell is checked in at your gatebut a much better cell becomes available in your garage car port It should not be enabled if your Wifi signal isgenerally poor as that will cause many disconnects amp reconnects

275 Static IP SSID Configuration

To connect with a static client address instead of using DHCP use the wifi ip static command

OVMS wifi ip static [ltipgt ltsubnetgt ltgatewaygt]

The gateway will also be used as the DNS

To configure persistent static details for a known SSID set these using the following configuration syntax

38 Chapter 2 User Guide

Open Vehicles

OVMS config set wifissid ltssidgtovmsstaticip ltipgtltsubnetgtltgatewaygt

You can also force connection to a specific AP by itrsquos MAC address ldquoBSSIDrdquo in WiFi terms To do so you need tosupply the MAC address as a second argument to the wifi mode client or as the third argument to the wifimode apclient command

OVMS wifi mode client ltssidgt ltbssidgt

OVMS wifi mode apclient ltapssidgt ltssidgt ltbssidgt

This currently needs manual activation by command Hint use a script for example bound to a location

276 AP Bandwidth Configuration

In normal operation the default AP bandwidth is set to 20Mhz to reduce interference and improve the signal quality Ifa wider 40Mhz bandwidth is preferred eg for high throughput logging set the network configuration wifiapbwwith the command

OVMS config set network wifiapbw 40

Once the parameter is set the module will require rebooting to take effect The default bandwidth can be restored byeither removing the parameter or setting it to 20

28 Virtual File System (VFS)

OVMS includes a Virtual File System (VFS) used to unify all storage in the system The primary configuration andscripting storage is mounted as lsquostorersquo and the SD card as lsquosdrsquo A lsquovfsrsquo set of commands is provided for basicmanipulation of these stores

OVMS vfs append VFS Append a line to a filecat VFS Display a filecp VFS Copy a fileedit VFS Edit a filels VFS Directory Listingmkdir VFS Create a directorymv VFS Rename a filerm VFS Delete a filermdir VFS Delete a directorystat VFS Status of a filetail VFS Output tail of a file

Please take care This is a very small microcontroller based system with limited storage The store area should onlybe used for storage of configurations and small scripts The sd SD CARD area is more flexibly and can be used forstoring of configuration logs firmware images etc

281 Network Access

Network access to the VFS is available via SCP or through the web server

SCP can access the whole file system and is readwrite

28 Virtual File System (VFS) 39

Open Vehicles

copy a new firmware to the sd card on an OVMS named leaf in my ssh configscp buildovms3bin leafsddev_ovms3bin

copy a config backup from OVMS named leaf to my local directoryscp leafsdbackupcfg-2019-12-05zip

In the upload example the firmware can then be loaded with the OTA flash vfs command

The web server offers read access rooted at the sd card An example retrieving that same config file from the SCPexample would look like

httpleaf-abrlocalbackupcfg-2019-12-05zip

29 Metrics

Metrics are at the heart of the OVMS v3 system They are strongly typed named parameters with values in specificunits (and able to be automatically converted to other units) For example a metric to record the motor temperaturemay be an integer in Celsius units and may be convertible to Fahrenheit

The full list of metrics available can be shown

OVMS metrics listmfreeram 4232852mhardware OVMS WIFI BLE BT cores=2 rev=ESP321mmonotonic 3568Secvplatitude 222809vplongitude 114161vpodometer 100000Kmvpsatcount 12vpspeed 0Kphvptrip 0Kmvtalert 0001vthealth 95939674vtpressure 2068432164832757917579kPavttemp 33333438degCvtype DEMO

You can filter the metrics list output for names matching a given substring for example metrics listvolt will show all voltage related metrics

A base OVMS v3 system has more than 100 metrics available (see below) and vehicle modules can add more for theirown uses (see vehicle sections)

In general vehicle modules (and some other system components) are responsible for updating the metrics and serverconnections read those metrics reformat them and send them on to servers and Apps (for eventual display to the user)Status commands (such as STAT) also read these metrics and display them in user-friendly forms

OVMS statNot chargingSOC 500Ideal range 200KmEst range 160KmODO 1000000KmCAC 1600AhSOH 100

40 Chapter 2 User Guide

Open Vehicles

For developer use there are also some other metric commands used to manually modify a metricrsquos value (for testingand simulation purposes) and trace changes

OVMS metrics list Show all metricspersist Show persistent metrics infoset Set the value of a metrictrace METRIC trace framework

Some metrics are presistent across warm reboots This prevents values such as SOC from being lost when firmware isupdated (or in the event of a crash) You can display these with metrics list -p and view general informationabout presistent metrics with metrics persist

291 Standard Metrics

Metric name Example value Descriptionmfreeram 3275588 Total amount of free RAM in bytesmhardware OVMS WIFI BLE BT Base module hardware infommonotonic 49607Sec Uptime in secondsmnetmdmiccid 89490240001766080167 SIM ICCIDmnetmdmmodel 35316B09SIM5360E Modem module hardware infomnetmdmnetwork congstar Current GSM network providermnetmdmsq -101dBm and signal qualitymnetprovider WLAN-214677 Current primary network providermnetsq -79dBm signal qualitymnettype wifi and type (nonemodemwifi)mnetwifinetwork WLAN-214677 Current Wifi network SSIDmnetwifisq -791dBm and signal qualitymserial Reserved for module serial nomtasks 20 Task count (use module tasks to list)mtimeutc 1572590910Sec UTC time in secondsmversion 32005-155-g3133466f Firmware versionmegpioinput 012345679 EGPIO input port state (ports 0 9 present=high)megpiomonitor 89 EGPIO input monitoring portsmegpiooutput 45679 EGPIO output port statesv2connected yes yes = V2 (MP) server connectedsv2peers 1 V2 clients connectedsv3connected yes = V3 (MQTT) server connectedsv3peers V3 clients connectedvb12vcurrent 0A Auxiliary 12V battery momentary currentvb12vvoltage 1229V Auxiliary 12V battery momentary voltagevb12vvoltagealert yes = auxiliary battery under voltage alertvb12vvoltageref 123V Auxiliary 12V battery reference voltagevbctemp 1313 13degC Cell temperaturesvbctempalert 00 0 Cell temperature deviation alert level [0=normal 1=warning 2=alert]vbctempdevmax 143086 -129degC Cell maximum temperature deviation observedvbctempmax 1918 17degC Cell maximum temperaturesvbctempmin 1312 12degC Cell minimum temperaturesvbcvoltage 41054095 4105V Cell voltagesvbcvoltagealert 00 0 Cell voltage deviation alert level [0=normal 1=warning 2=alert]vbcvoltagedevmax 00096-00104 00125V Cell maximum voltage deviation observed

Continued on next page

29 Metrics 41

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvbcvoltagemax 41354125 414V Cell maximum voltagesvbcvoltagemin 38753865 388V Cell minimum voltagesvbcac 907796Ah Calculated battery pack capacityvbconsumption 0Whkm Main battery momentary consumptionvbcoulombrecd 475386Ah Main battery coulomb recovered on tripchargevbcoulombrecdtotal 9475386Ah Main battery coulomb recovered total (life time)vbcoulombused 0406013Ah Main battery coulomb used on tripvbcoulombusedtotal 835406013Ah Main battery coulomb used total (life time)vbcurrent 0A Main battery momentary current (output=positive)vbenergyrecd 269691kWh Main battery energy recovered on tripchargevbenergyrecdtotal 321269691kWh Main battery energy recovered total (life time)vbenergyused 00209496kWh Main battery energy used on tripvbenergyusedtotal 31770209496kWh Main battery energy used total (life time)vbhealth General textual description of battery healthvbplevelavg 95897 Cell level - pack averagevbplevelmax 9641 Cell level - strongest cell in packvbplevelmin 94871 Cell level - weakest cell in packvbplevelstddev 0548 Cell level - pack standard deviationvbptempavg 13degC Cell temperature - pack averagevbptempmax 13degC Cell temperature - warmest cell in packvbptempmin 13degC Cell temperature - coldest cell in packvbptempstddev 0degC Cell temperature - current standard deviationvbptempstddevmax 073degC Cell temperature - maximum standard deviation observedvbpvoltageavg 41V Cell voltage - pack averagevbpvoltagegrad 00032V Cell voltage - gradient of current seriesvbpvoltagemax 4105V Cell voltage - strongest cell in packvbpvoltagemin 409V Cell voltage - weakest cell in packvbpvoltagestddev 000535V Cell voltage - current standard deviationvbpvoltagestddevmax 000783V Cell voltage - maximum standard deviation observedvbpower 0kW Main battery momentary power (output=positive)vbrangeest 99km Estimated rangevbrangefull 508km Ideal range at 100 SOC amp current conditionsvbrangeideal 48km Ideal rangevbrangespeed 216kmh Momentary ideal range gainloss (chargedischarge) speedvbsoc 963 State of chargevbsoh 85 State of healthvbtemp 13degC Main battery momentary temperaturevbvoltage 574V Main battery momentary voltagevc12vcurrent 78A Output current of DCDC-convertervc12vpower 123W Output power of DCDC-convertervc12vtemp 345degC Temperature of DCDC-convertervc12vvoltage 123V Output voltage of DCDC-convertervccharging no yes = currently chargingvcclimit 0A Maximum charger output currentvccurrent 125A Momentary charger output currentvcdurationfull 25Min Estimated time remaing for full chargevcdurationrange -1Min for sufficient rangevcdurationsoc 0Min for sufficient SOCvcefficiency 876 Momentary charger efficiency

Continued on next page

42 Chapter 2 User Guide

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvckwh 26969kWh Energy sum for running chargevckwhgrid 36969kWh Energy drawn from grid during running sessionvckwhgridtotal 25669kWh Energy drawn from grid total (life time)vclimitrange 0km Sufficient range limit for current chargevclimitsoc 80 Sufficient SOC limit for current chargevcmode standard standard range performance storagevcpilot no Pilot signal presentvcpower 125kW Momentary charger input powervcstate done charging topoff done prepare timerwait heating stoppedvcsubstate scheduledstop scheduledstart onrequest timerwait powerwait stopped interruptedvctemp 16degC Charger temperaturevctime 0Sec Duration of running chargevctimermode yes = timer enabledvctimerstart Time timer is due to start seconds since midnight UTCvctype undefined type1 type2 chademo roadster teslaus supercharger ccsvcvoltage 0V Momentary charger supply voltagevdcp yes yes = Charge port openvdfl yes = Front left door openvdfr yes = Front right door openvdhood yes = Hoodfrunk openvdrl yes = Rear left door openvdrr yes = Rear right door openvdtrunk yes = Trunk openvealarm yes = Alarm currently soundingveaux12v yes = 12V auxiliary system is on (base system awake)veawake no yes = Vehicle is fully awake (switched on by the user)vecconfig yes = ECUcontroller in configuration stateveclogin yes = Module logged in at ECUcontrollervecabintemp 20degC Cabin temperaturevecabinfan 100 Cabin fanvecabinsetpoint 24degC Cabin set pointvecabinintake fresh Cabin intake type (fresh recirc etc)vecabinvent feetface Cabin vent type (comma-separated list of feet face screen etc)vecharging12v no yes = 12V battery is chargingvecooling yes = Coolingvedrivemode 33882626 Active drive profile code (vehicle specific)vedrivetime 0Sec Seconds driving (turned on)vefootbrake 0 Brake pedal state []vegear Geardirection negative=reverse 0=neutralvehandbrake yes = Handbrake engagedveheadlights yes = Headlights onveheating yes = Heatingvehvac yes = HVAC activevelocked yes = Vehicle lockedveon no yes = Vehicle is in ldquoignitionrdquo state (drivable)veparktime 49608Sec Seconds parking (turned off)veregenbrake yes = Regenerative braking activeveservrange 12345km Distance to next scheduled maintenanceservice [km]veservtime 1572590910Sec Time of next scheduled maintenanceservice [Seconds]

Continued on next page

29 Metrics 43

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvetemp Ambient temperaturevethrottle 0 Drive pedal state []vevalet yes = Valet mode engagedvggenerating no True = currently delivering powervgclimit 0A Maximum generator input current (from battery)vgcurrent 125A Momentary generator input current (from battery)vgdurationempty 25Min Estimated time remaining for full dischargevgdurationrange -1Min for range limitvgdurationsoc 0Min for SOC limitvgefficiency 876 Momentary generator efficiencyvgkwh 26969kWh Energy sum generated in the running sessionvgkwhgrid 36969kWh Energy sent to grid during running sessionvgkwhgridtotal 25669kWh Energy sent to grid totalvglimitrange 0km Minimum range limit for generator modevglimitsoc 80 Minimum SOC limit for generator modevgmode standard Generator mode (TBD)vgpilot no Pilot signal presentvgpower 125kW Momentary generator output powervgstate done Generator state (TBD)vgsubstate Generator substate (TBD)vgtemp 16degC Generator temperaturevgtime 0Sec Duration of generator runningvgtimermode false True if generator timer enabledvgtimerstart Time generator is due to startvgtype Connection type (chademo ccs )vgvoltage 0V Momentary generator output voltagevitemp Inverter temperaturevipower 427kW Momentary inverter motor power (output=positive)viefficiency 982 Momentary inverter efficiencyvmrpm Motor speed (RPM)vmtemp 0degC Motor temperaturevpacceleration 0ms2 Vehicle accelerationvpaltitude 3278m GPS altitudevpdirection 312deg GPS directionvpgpshdop 13 GPS horizontal dilution of precision (smaller=better)vpgpslock no yes = has GPS satellite lockvpgpsmode AA ltGPSgtltGLONASSgt NADE (NoneAutonomousDifferentialEstimated)vpgpsspeed 0kmh GPS speed over groundvplatitude 513023 GPS latitudevplocation Home Name of current location if definedvplongitude 739006 GPS longitudevpodometer 579131km Vehicle odometervpsatcount 8 GPS satellite count in viewvpspeed 0kmh Vehicle speedvptrip 0km Trip odometervtalert 0001 TPMS tyre alert levels [0=normal 1=warning 2=alert]vthealth 95939674 TPMS tyre health statesvtpressure 20682164 kPa TPMS tyre pressuresvttemp 33333438degC TPMS tyre temperatures

Continued on next page

44 Chapter 2 User Guide

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionvtype RT Vehicle type codevvin VF1ACVYB012345678 Vehicle identification number

210 Over The Air (OTA) Updates

OVMS v3 includes 16MB flash storage This is partition as

4MB for factory application image (factory)4MB for the first OTA application image (ota_0)4MB for a second OTA application image (ota_1)1MB for store configuration and scripting storageThe remainder for bootloader generic non-volatile storage and other data

In general the factory application firmware is stored in flash at the factory during module production That firmwareis never changed on production modules and is always kept as a failover backup

That leaves two firmwares for Over The Air (OTA) updates If the currently running firmware is the factory one anOTA updated firmware can be written to either of the OTA partitions If the current running firmware is ota_0 thenany new OTA updates will be written to ota_1 (and similarly if ota_1 is currently running then new OTA updates willbe written to ota_0) In this way the currently running firmware is never modified and is always available as a failoverbackup

You can check the status of OTA with the lsquoota statusrsquo command

OVMS ota statusFirmware 31003-2-g7ea18b4-dirtyfactorymain (build idf v31-dev-453-rarr˓g0f978bcb Apr 7 2018 162657)Server Available 31003Running partition factoryBoot partition factory

That is showing the currently running firmware as a custom image v31003-2-g7ea18b4-dirty running in factorypartition The running currently running partition is factory and the next time the system is booted it will run fromfactory as well

As a convenience if there is currently active wifi connectivity a network lookup will be performed and the currentlyavailable firmware version on the server will be shown In this case that is the standard 31003 release (as shown inthe lsquoServer Availablersquo line)

If we wanted to boot from ota_1 we can do this with lsquoota boot ota_1rsquo

OVMS ota boot ota_1Boot from ota_1 at 0x00810000 (size 0x00400000)

OVMS ota statusFirmware 31003-2-g7ea18b4-dirtyfactorymain (build idf v31-dev-453-rarr˓g0f978bcb Apr 7 2018 162657)Server Available 31003Running partition factoryBoot partition ota_1

If the bootloader fails to boot from the specified OTA firmware it will failover and boot from factory

We can flash firmware to OTA either from a file on VFS (normally sd) or over the Internet (via http) Letrsquos try asimple OTA update over HTTP

210 Over The Air (OTA) Updates 45

Open Vehicles

OVMS ota flash httpCurrent running partition is factoryTarget partition is ota_0Download firmware from apiopenvehiclescomfirmwareotav31mainovms3bin to ota_0Expected file size is 2100352Preparing flash partitionDownloading (100361 bytes so far)Downloading (200369 bytes so far)Downloading (300577 bytes so far)Downloading (1903977 bytes so far)Downloading (2004185 bytes so far)Download complete (at 2100352 bytes)Setting boot partitionOTA flash was successful

Flashed 2100352 bytes from apiopenvehiclescomfirmwareotav31mainovms3binNext boot will be from ota_0

OVMS ota statusFirmware 31003-2-g7ea18b4-dirtyfactorymain (build idf v31-dev-453-rarr˓g0f978bcb Apr 7 2018 162657)Server Available 31003Running partition factoryBoot partition ota_0

Rebooting now (with lsquomodule resetrsquo) would boot from the new ota_0 partition firmware

OVMS ota statusFirmware 31003ota_0main (build idf v31-dev-453-g0f978bcb Apr 7 2018rarr˓131119)Server Available 31003Running partition ota_0Boot partition ota_0

211 Boot Status

OVMS maintains a record of the reason for each boot in RAM that survives a reboot It can show you how long themodule has been running for and the reason for the last reboot

OVMS boot statusLast boot was 2244 second(s) ago

This is reset 9 since last power cycleDetected boot reason SoftResetCrash counters 0 total 0 earlyCPU0 boot reason was 12CPU1 boot reason was 12

If an unexpected (not lsquomodule resetrsquo) reboot occurs within the first 10 seconds of startup (usually during the boot-timeauto-loading of modules scripts etc) the crash counters are incremented If those crash counters reach 5 (without aclean reset in between) then the auto-loading of modules is disabled for the 6th boot

In case of a crash the output will also contain additional debug information ie

Last crash abort() was called on core 1Backtrace

(continues on next page)

46 Chapter 2 User Guide

Open Vehicles

(continued from previous page)

0x40092ccc 0x40092ec7 0x400dbf1b 0x40176ca9 0x40176c6d 0x400eebd9 0x4013aed90x4013b538 0x40139c15 0x40139df9 0x4013a701 0x4013a731

If the module can access the V2 server after the crash reboot it will also store this information along with the crashcounters in the server table ldquo-OVM-DebugCrashrdquo which will be kept on the server for 30 days

Please include this info when sending a bug report along with the output of ldquoota statusrdquo and ndash if available ndash any logfiles capturing the crash event (see Logging to SD CARD) If you can repeat the crash please try to capture a log atldquolog level verboserdquo

212 Events

Internally OVMS raises events whenever significant events occur An event is a lightweight message of a name plusoptionally associated internal binary data Event names are top-down structured (so can be filtered by prefix) andsufficient to identify the source and type of the event Individual vehicle types may also issue their own events andcustom user events are also possible

To bind a script to an event save the script in directory storeeventslteventnamegt (hint directories canbe created using the web UI editor) Whenever events are triggered all the scripts in the corresponding storeeventslteventnamegt directory are executed Event scripts are executed in alphanumerical order of their namesGood practice is to prefix script names with 2-3 digit numbers in steps of 10 or 100 (ie first script named 50-)so new scripts can easily be integrated at a specific place If the event script is written in Javascript be sure to add thesuffix js to the name Other names will be executed using the standard command interpreter

If you want to introduce a custom event (eg for a plugin) prefix the event name by usrltpluginnamegtfollowed by the event purpose Example Foglight

Be aware events are processed in series from a queue so depending on the system load and the list of registeredevent listeners there may be some delay from event generation to eg a script execution

2121 Commands

bull event list [ltkeygt] ndash Show registered listeners for all or events matching a key (part of the name)

bull event trace lton|offgt ndash Enabledisable logging of events at the ldquoinfordquo level Without tracing events arealso logged but at the ldquodebugrdquo level Ticker events are never logged

bull event raise [-dltdelay_msgt] lteventgt ndash Manually raise an event optionally with a delay You canraise any event you like but you shouldnrsquot raise system events without good knowledge of their effects

2122 Standard Events

Event Data Purposeappconnected One or more remote Apps have connectedappdisconnected No remote Apps are currently connectedcanopennodeemcy lteventgt CANopen node emergency receivedcanopennodestate lteventgt CANopen node state change receivedcanopenworkerstart ltworkergt CANopen bus worker task startedcanopenworkerstop ltworkergt CANopen bus worker task stoppingclockHHMM Per-minute local time hour HH minute MM

Continued on next page

212 Events 47

Open Vehicles

Table 2 ndash continued from previous pageEvent Data PurposeclockdayN Per-day local time day N (0=Sun 6=Sat)configchanged Configuration has changedconfigmounted Configuration is mounted and availableconfigunmounted Configuration is unmounted and unavailableegpioinputltportgtltstategt EGPIO input port change (port=0 9 state=highlow)egpiooutputltportgtltstategt EGPIO output port change (port=0 9 state=highlow)gpslockacquired GPS lock has been acquiredgpslocklost GPS lock has been losthousekeepinginit Housekeeping has initialisedlocationalertflatbedmoved GPS movement of parked vehicle detectedlocationenterltnamegt ltnamegt The specified geolocation has been enteredlocationleaveltnamegt ltnamegt The specified geolcation has been leftnetworkdown All networks are downnetworkinterfacechange Network interface change detectednetworkinterfaceup Network connection is establishednetworkmgrinit Network manager has initialisednetworkmgrstop Network managed has been stoppednetworkmodemdown Modem network is downnetworkmodemup Modem network is upnetworkreconfigured Networking has been reconfigurednetworkup One or more networks are upnetworkwifidown WIFI network is downnetworkwifistabad WIFI client has bad signal levelnetworkwifistagood WIFI client has good signal levelnetworkwifiup WIFI network is upnotifylttypegtltsubtypegt An info alert error notification is sentretoolsclearedall RE frame log has been clearedretoolsclearedchanged RE frame change flags clearedretoolscleareddiscovered RE frame discovery flags clearedretoolsmodeanalyse RE switched to analysis moderetoolsmodediscover RE switched to discovery moderetoolsstarted RE (reverse engineering) toolkit startedretoolsstopped RE toolkit stoppedretoolspidscanstart RE OBD2 PID scan startedretoolspidscanstop RE OBD2 PID scan stoppedretoolspidscandone RE OBD2 PID scan completedsdinsert The SD card has just been insertedsdmounted The SD card is mounted and ready to usesdremove The SD card has just been removedsdunmounted The SD card has completed unmountingsdunmounting The SD card is currently unmountingserverv2authenticating V2 server connection is authenticatingserverv2connected V2 server connection established onlineserverv2connecting V2 server connection in progressserverv2connectwait V2 server is pausing before connectionserverv2disconnected V2 server connection has been lostserverv2stopped V2 server has been stoppedserverv2waitnetwork V2 server connection is waiting for networkserverv2waitreconnect V2 server is pausing before re-connection

Continued on next page

48 Chapter 2 User Guide

Open Vehicles

Table 2 ndash continued from previous pageEvent Data Purposeserverv3authenticating V3 server connection is authenticatingserverv3connected V3 server connection established onlineserverv3connecting V3 server connection in progressserverv3connectwait V3 server is pausing before connectionserverv3disconnected V3 server connection has been lostserverv3stopped V3 server has been stoppedserverv3waitnetwork V3 server connection is waiting for networkserverv3waitreconnect V3 server is pausing before re-connectionserverwebsocketclosed ltcntgt Web server lost a websocket clientserverwebsocketopened ltcntgt Web server has a new websocket clientsystemmodemdown Modem has been disconnectedsystemmodemgotgps Modem GPS has obtained locksystemmodemgotip Modem received IP address from DATAsystemmodeminstalled Modem type has been identified driver installedsystemmodemlostgps Modem GPS has lost locksystemmodemmuxstart Modem MUX has startedsystemmodemnetdeepsleep Modem is deep sleeping DATA networksystemmodemnethold Modem is pausing DATA networksystemmodemnetloss Modem has lost DATA networksystemmodemnetsleep Modem is sleeping DATA networksystemmodemnetstart Modem is starting DATA networksystemmodemnetwait Modem is pausing before starting DATAsystemmodempoweredon Modem is powered onsystemmodempoweringon Modem is powering onsystemmodemreceivedussd ltussdgt A USSD message has been receivedsystemmodemstop Modem has been shut downsystemshutdown System has been shut downsystemshuttingdown System is shutting downsystemstart System is startingsystemvfsfilechanged ltpathgt VFS file updated (note only sent on some file changes)systemwifiapstaconnected WiFi access point got a new client connectionsystemwifiapstadisconnected WiFi access point lost a client connectionsystemwifiapstaipassigned WiFi access point assigned an IP address to a clientsystemwifiapstart WiFi access point mode startingsystemwifiapstop WiFi access point mode stoppingsystemwifidown WiFi is shutting downsystemwifiscandone WiFi scan has been finishedsystemwifistaconnected WiFi client is connected to a stationsystemwifistadisconnected WiFi client has disconnected from a stationsystemwifistagotip WiFi client got an IP addresssystemwifistalostip WiFi client lost itrsquos IP addresssystemwifistastart WiFi client mode startingticker1 One second has passed since last tickerticker10 Ten seconds have passedticker300 Five minutes have passedticker3600 One hour has passedticker60 One minute has passedticker600 Ten minutes have passedvehiclealarmoff Vehicle alarm has been disarmed

Continued on next page

212 Events 49

Open Vehicles

Table 2 ndash continued from previous pageEvent Data Purposevehiclealarmon Vehicle alarm has been armedvehiclealert12voff 12V system voltage has recoveredvehiclealert12von 12V system voltage is below alert thresholdvehiclealertbms BMS cellpack voltstemps exceeded thresholdsvehicleasleep Vehicle systems are asleepvehicleawake Vehicle systems are awakevehicleaux12von Vehicle 12V auxiliary system is on (base system awake)vehicleaux12voff Vehicle 12V auxiliary system is offvehiclecharge12vstart Vehicle 12V battery is chargingvehiclecharge12vstop Vehicle 12V battery has stopped chargingvehiclechargefinished Vehicle charge has completed normallyvehiclechargemode ltmodegt Vehicle charge mode has been setvehiclechargepilotoff Vehicle charge pilot signal is offvehiclechargepiloton Vehicle charge pilot signal is onvehiclechargeprepare Vehicle is preparing to chargevehiclechargestart Vehicle has started to chargevehiclechargestate ltstategt Vehicle charge state has changedvehiclechargestop Vehicle has stopped chargingvehiclechargetimermodeoff Vehicle charge timer mode has been switched offvehiclechargetimermodeon Vehicle charge timer mode has been switched onvehicledrivemodeltngt Vehicle drivemode has been set to profile ltngt (vehicle specific)vehiclegearforward Vehicle has been put in forward gearvehiclegearneutral Vehicle has been put in neutral gearvehiclegearreverse Vehicle has been put in reverse gearvehicleheadlightsoff Vehicle headlights are offvehicleheadlightson Vehicle headlights are onvehiclelocked Vehicle has been lockedvehicleoff Vehicle has been switched offvehicleon Vehicle has been switched onvehiclerequiregps A vehicle has indicated it requires GPSvehiclerequiregpstime A vehicle has indicated it requires GPS timevehicletypecleared Vehicle module has been unloadedvehicletypeset lttypegt Vehicle module has been loadedvehicleunlocked Vehicle has been unlockedvehiclevaletoff Vehicle valet mode deactivatedvehiclevaleton Vehicle valet mode activated

213 Geofenced Locations

This section of the manual is still under development

214 Notifications

Notifications can be simple text messages or transport structured data To distinguish by their purpose and originnotifications have a type and a subtype

Notifications are sent by the module via the available communication channels (clientserver connections) If a channelis temporarily down (eg due to a connection loss) the notifications for that channel will be kept in memory until thechannel is available again (Note this message queue does not survive a crash or reboot of the module)

50 Chapter 2 User Guide

Open Vehicles

Channels process notifications differently depending on the way they work For example a v2 server will forward textnotifications as push messages to connected smart phones and email readers a v3 server will publish them under anMQTT topic and the webserver will display the message as a modal dialog See the respective manual sections fordetails

Notification types currently defined

bull info ndash informational text messages

bull alert ndash alert text messages

bull error ndash error code messages

bull data ndash historical data records usually CSV formatted

bull stream ndash live data streaming (high bandwidth) usually JSON formatted

The standard subtypes used are listed below these can be used to filter messages Vehicles may introduce customnotifications and replace standard notifications see the respective user guide section for details

Subtypes by convention are given in lower case with dots lsquorsquordquo as structural separators

Notification channels currently defined

bull ovmsv2 ndash server v2 connection

bull ovmsv3 ndash server v3 connection

bull ovmsweb ndash websocket connections

bull pushover ndash pushover text messaging service

Channels may have multiple active instances (ldquoreadersrdquo) for example you can open multiple websocket connectionsChannels may exclude notification types Currently stream records are only supported on a websocket connectionall other types are supported on all channels

Use notify status to see the currently registered channels (ldquoreadersrdquo) Example

OVMS notify statusNotification system has 3 readers registered

pushover(1) verbosity=1024ovmsv2(2) verbosity=1024ovmsweb(3) verbosity=65535

Notify typesalert 0 entriesdata 0 entrieserror 0 entriesinfo 0 entriesstream 0 entries

The channelrsquos ldquoverbosityrdquo defines the supported maximum length of a textual notification message on that channelNotification senders should honor this but not all may do so If messages exceed this limit they may be truncated

2141 Sending notifications

You can send custom notifications from the shell or command scripts by using the notify raise command Thecommand can send the output of another command an error code (implies type error) or any text you enter Forexample to send a custom text message do

OVMS notify raise text info usrantonwelcome Hello wonderful person

214 Notifications 51

Open Vehicles

In this case the type would be info and the subtype usrantonwelcome The type must match one of thedefined types the subtype can be chosen arbitrarily Please use a unique usr prefix for custom notifications to avoidcollisions

To send a battery status command result do

OVMS notify raise command info batterystatus stat

To send notifications from Duktape scripts use the API call OvmsNotifyRaise()

When a text (infoalert) or error notification is sent (ie has at least one listening channel eg pushover) anevent is raised once when the notification is queued The event will be named notifylttypegtltsubtypegt Forexample the second example above would come with an event notifyinfobatterystatus

2142 Suppress notifications

You can filter the channels to be used for notifications by their subtypes By default no subtypes are filtered on anychannel so all notifications are sent to all clients

To disable (suppress) notifications create a config entry based on the respective subtype that lists the channels toinclude or exclude

OVMS config set notify ltsubtypegt ltchannelsgt

ltchannelsgt options are

a) explicit inclusion eg ovmsv2pushover (only enable these)

b) explicit exclusion eg -ovmsv3-ovmsweb (only disable these)

c) - (dash) to disable all

d) empty to enable all

Example to disable the OTA update notifications on all channels do

OVMS config set notify otaupdate -

52 Chapter 2 User Guide

Open Vehicles

2143 Standard notifications

Type Subtype Purpose Contentalert alarmsounding Vehicle alarm is soundingalert alarmstopped Vehicle alarm has stoppedalert batt12valert 12V Battery criticalalert batt12vrecovered 12V Battery restoredalert battbmsalert Battery packcell alert (critical voltagetemperature deviation)alert battsocalert Battery SOC criticalinfo chargedone stat on charge finishedinfo chargestarted stat on start of chargeinfo chargetoppingoff stat on start of topping off chargephaseinfo chargestopped stat on planned charge stopalert chargestopped stat on unplanned charge stopdata debugcrash Transmit crash backtraces (rarr -OVM-DebugCrash)data debugtasks Transmit task statistics (rarr -OVM-DebugTasks)info drivetripreport Trip driving statistics (see Trip report)alert flatbedmoved Vehicle is being transported while parked - possible theftflatbedinfo heatingstarted stat on start of heating (battery)data loggrid Grid (chargegenerator) history log (see below) (rarr -LOG-Grid)data logtrip Trip history log (see below) (rarr -LOG-Trip)alert modemno_pincode No PIN code for SIM card configuredalert modemwrongpincode Wrong pin codeinfo otaupdate New firmware availabledownloadedinstalledinfo pushover Connection failure message delivery responsestream retoolslistupdate RE toolkit CAN frame list updatestream retoolsstatus RE toolkit general status updateinfo valetdisabled Valet mode disabledinfo valetenabled Valet mode enabledalert valethood Vehicle hood opened while in valet modealert valettrunk Vehicle trunk opened while in valet modealert vehicleidle Vehicle is idling stopped turned on

2144 Grid history log

The grid history log can be used as a source for long term statistics on your charges and typical energy usages and tocalculate your vehicle energy costs

Log entries are created on each change of the charge or generator state (vcstate vgstate)

You need to enable this log explicitly by configuring a storage time via config param notify loggridstoretime (in days) or via the web configuration page Set to 0empty to disable the log Already stored logentries will be kept on the server until expiry or manual deletion

Note the stability of the total energy counters included in this log depends on their source and persistence on thevehicle andor module If they are kept on the module they may lose their values on a power outage

bull Notification subtype loggrid

bull History record type -LOG-Grid

bull Format CSV

bull Archive time config notify loggridstoretime (days)

214 Notifications 53

Open Vehicles

bull Fieldscolumns

ndash pos_gpslock

ndash pos_latitude

ndash pos_longitude

ndash pos_altitude

ndash pos_location

ndash charge_type

ndash charge_state

ndash charge_substate

ndash charge_mode

ndash charge_climit

ndash charge_limit_range

ndash charge_limit_soc

ndash gen_type

ndash gen_state

ndash gen_substate

ndash gen_mode

ndash gen_climit

ndash gen_limit_range

ndash gen_limit_soc

ndash charge_time

ndash charge_kwh

ndash charge_kwh_grid

ndash charge_kwh_grid_total

ndash gen_time

ndash gen_kwh

ndash gen_kwh_grid

ndash gen_kwh_grid_total

ndash bat_soc

ndash bat_range_est

ndash bat_range_ideal

ndash bat_range_full

ndash bat_voltage

ndash bat_temp

ndash charge_temp

ndash charge_12v_temp

54 Chapter 2 User Guide

Open Vehicles

ndash env_temp

ndash env_cabintemp

ndash bat_soh

ndash bat_health

ndash bat_cac

ndash bat_energy_used_total

ndash bat_energy_recd_total

ndash bat_coulomb_used_total

ndash bat_coulomb_recd_total

2145 Trip history log

The trip history log can be used as a source for long term statistics on your trips and typical trip power usages as wellas your battery performance in different environmental conditions and degradation over time

Entries are created at the beginning and end of each ldquoignitionrdquo cycle (veon change) Configure a minimum triplength for logging by the config variable notify logtripminlength or via the web UI If your vehicle doesnot support the vptrip metric set the minimum trip length to 0

The log entry at the beginning of a trip is created to track non-driving SOC changes vampire drains and BMS SOCcorrections that occurred in between If yoursquore just interested in the actual drive results filter the records eg bypos_trip gt 01 or env_drivetime gt 10 (by default log entries will be created 3 seconds after the veonstate change)

You need to enable this log explicitly by configuring a storage time via config param notify logtripstoretime (in days) or via the web configuration page Set to 0empty to disable the log Already stored logentries will be kept on the server until expiry or manual deletion

bull Notification subtype logtrip

bull History record type -LOG-Trip

bull Format CSV

bull Archive time config notify logtripstoretime (days)

bull Fieldscolumns

ndash pos_gpslock

ndash pos_latitude

ndash pos_longitude

ndash pos_altitude

ndash pos_location

ndash pos_odometer

ndash pos_trip

ndash env_drivetime

ndash env_drivemode

ndash bat_soc

ndash bat_range_est

214 Notifications 55

Open Vehicles

ndash bat_range_ideal

ndash bat_range_full

ndash bat_energy_used

ndash bat_energy_recd

ndash bat_coulomb_used

ndash bat_coulomb_recd

ndash bat_soh

ndash bat_health

ndash bat_cac

ndash bat_energy_used_total

ndash bat_energy_recd_total

ndash bat_coulomb_used_total

ndash bat_coulomb_recd_total

ndash env_temp

ndash env_cabintemp

ndash bat_temp

ndash inv_temp

ndash mot_temp

ndash charge_12v_temp

ndash tpms_temp_min

ndash tpms_temp_max

ndash tpms_pressure_min

ndash tpms_pressure_max

ndash tpms_health_min

ndash tpms_health_max

2146 Trip report

The trip report outputs some core statistics of the current or most recent trip (drive cycle) It can be queried any timeusing the stat trip command or be configured to be sent automatically on turning the vehicle off

Use the web UI (Config rarr Notifications) or set config variable notify reporttripenable to yes andoptionally a minimum trip length in notify logtripminlength (defaults to 02 km) If your vehicle doesnot support the vptrip metric set the minimum trip length to 0

The statistics available depend on your vehicle type (ie metrics support of that vehicle adaption) Vehicles also mayoverride the report to provide custom statistics By default a full trip report will contain

bull Trip length

bull Average driving speed

bull Overall altitude difference (start to end point)

56 Chapter 2 User Guide

Open Vehicles

bull Energy consumption in Wh per kmMi

bull Recuperation percentage (in relation to energy used)

bull SOC difference amp new SOC

bull Estimated range difference amp new range

bull Average acceleration amp deceleration

The average driving speed is calculated only from speeds above 5 kph (3 mph) (to exclude slow speed rolling) andthe acceleration amp deceleration averages exclude values below 25 kphs (16 mphs) (constant speed cruising)

215 Time

This section of the manual is still under development

216 SSLTLS

Warning Letrsquos Encrypt root certificate expiration on September 30 2021

To prevent losing TLS connectivity with an LE secured server (like dexters-webde) with module firmwareversions 32016 or earlier you need to install the new root certificate manually Sorry for the inconvenience

See below Letrsquos Encrypt Root Certificate Update

2161 SSLTLS Trusted Certificate Authorities

A default minimal list of trusted certificate authorities (CA) is provided with the firmware you can see the currentloaded list with the tls trust list command

OVMS tls trust listAddTrust External CA Root length 15211521 byte certificate AddTrust External CA Root

cert version 3serial number 01issuer name C=SE O=AddTrust AB OU=AddTrust External TTP Network

rarr˓CN=AddTrust External CA Rootsubject name C=SE O=AddTrust AB OU=AddTrust External TTP Network

rarr˓CN=AddTrust External CA Rootissued on 2000-05-30 104838expires on 2020-05-30 104838signed using RSA with SHA1RSA key size 2048 bitsbasic constraints CA=truekey usage Key Cert Sign CRL Sign

If you want to add to this list you can place the PEM formatted root CA certificate in the storetrustedcadirectory on your config partition using the text editor Then reload the list with

OVMS tls trust reloadReloading SSLTLS trusted CA listSSLTLS has 4 trusted CAs using 5511 bytes of memory

215 Time 57

Open Vehicles

On boot the trusted Certificate Authorities provided in firmware and put in your storetrustedca directorywill be automatically loaded and made available

These trusted certificate authorities are used by the various module in the OVMS system when establishing SSLTLSconnections (in order to verify the certificate of the server being connected to)

2162 How to get the CA PEM for a Server

Download from CA

If you know the CA check their download section

Using a Browser

This only works for https servers

1 Open the website you want to access

2 Open the encryption info (eg Chrome lock icon at URL rarr show certificate)

3 Display the certificate chain (eg Chrome tab ldquoDetailsrdquo first element)

4 Select the last entry before the actual server certificate

5 Export the certificate in PEM format (usually the default)

6 Install the file contents as shown above

Using OpenSSL or GNU TLS CLI

This works for all servers and ports

openssl s_client -connect HOSTNAMEPORT -servername HOSTNAME -showcerts ltdevnull | sed -ne -BEGIN CERTIFICATE--END CERTIFICATE-p

or

gnutls-cli --print-cert --port PORT HOSTNAME ltdevnull | sed -ne -BEGIN CERTIFICATE--END CERTIFICATE-p

Substitute HOSTNAME and PORT accordingly eg https = port 443 The sed just strips the other info from theoutput and can be omitted to check for errors or details

There should be two certificates in the output look for BEGIN and END markers The first one is the server certificatethe second one the CA certificate Copy that second certificate into the editor take care to include the BEGIN andEND lines

2163 Letrsquos Encrypt Root Certificate Update

If running firmware version 32016 or earlier you need to install the new Letrsquos Encrypt root certificate (ldquoISRGRoot X1rdquo) manually to enable encrypted connections to servers secured by a Letrsquos Encrypt certificate

1 Save the certificate text shown below to file storetrustedcaisrgx1

2 Issue command tls trust reload or reboot the module

Certificate text

58 Chapter 2 User Guide

Open Vehicles

-----BEGIN CERTIFICATE-----MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2VhcmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygch77ct984kIxuPOZXoHj3dcKivVqbvYATyjb3miGbESTtrFjRQSa78f0uoxmyF+0TM8ukj13Xnfs7jEvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6UA5TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sWT8KOEUt+zwvo7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hmELNKjD+Jo2FR3qyHB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UCB5iPNgiV5+I3lg02dZ77DnKxHZu8AlJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUvKBds0pjBqAlkd25HN7rOrFleaJ1ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWnOlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTnjh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbwqHyGO0aoSCqI3Haadr8faqU9GYrOPNk3sgrDQoofb4hVC1CLQJ13hef4Y53CIrU7m2Ys6xt0nUW7vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEBwQEAwIBBjAPBgNVHRMBAf8EBTADAQHMB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkqhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaSV9lZLubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ3BebYhtF8GaV0nxvwuo77xPy9auJGpsMiuX1+mvoiBOv2XqkSsisRcOjKKNFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7UrTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l++sKAIuvtd7u+Nxe5AW0wdeRlN8NwdCjNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVcoyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui01lvh+wjChP4kqKOJ2qxq4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9Ut7y0Ff9yi0GE44Za4rF2LN9d11TPAmRGunUHBcnWEvgJBQl9nJEiU0ZsnvgcubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57demyPxgcYxneR44KJ4EBs+lVDR3veyJm+kXQ99b21+jh5Xos1AnX5iItreGCc=-----END CERTIFICATE-----

217 Scripting

2171 Command Scripts

Lists of commands can be entered into a script file and stored in the VFS for execution (in the storescriptsdirectory) These are called lsquocommand scriptsrsquo and are simple sequential lists of OVMS commands A commandscript can be executed with

OVMS ltscriptgtOVMS script run ltscriptgt

Command scripts can also be stored in the storeeventslteventnamegt directory structure Whenever eventsare triggered all the scripts in the corresponding storeeventslteventnamegt directory are executed Eventscripts are executed in alphanumerical order of their names Good practice is to prefix script names with 2-3 digitnumbers in steps of 10 or 100 (ie first script named 50-) so new scripts can easily be integrated at a specificplace

Output of background scripts without console association (eg event scripts) will be sent to the log with tag scriptat ldquoinfordquo level

Note that the developer building firmware can optionally set the OVMS_DEV_SDCARDSCRIPTS build flag If thatis set then the system will also check sdscripts and sdevents for scripts This should not be used forproduction builds as you could hack the system just by plugging in an SD card

217 Scripting 59

Open Vehicles

In addition to command scripts more sophisticated scripting capabilities may be enabled if the JavaScript environmentis enabled in the build This is discussed in the next section of this guide

2172 JavaScripting

OVMS v3 includes a powerful JavaScript engine In addition to the standard relatively fixed firmware flashed tothe module JavaScripting can be used to dynamically load script code to run alongside the standard firmware Thisjavascript code can respond to system events and perform background monitoring and other such tasks

The simplest way of running javascript is to place a piece of javascript code in the storescripts directory withthe file extension js Then the standard mechanism of running scripts can be employed

OVMS ltscriptjsgtOVMS script run ltscriptjsgt

Short javascript snippets can also be directly evaluated with

OVMS script eval ltcodegt

Such javascript code can also be placed in the storeeventslteventnamegt directories to be automaticallyexecuted when the specified event is triggered The script file name suffix must be js to run the Javascript interpreter

Note The scripting engine used is Duktape Duktape supports ECMAScript E5E51 with some additions from laterECMAScript standards Duktape does not emulate a browser environment so you donrsquot have window or documentobjects etc just core Javascript plus the OVMS API and plugins

Duktape builtin objects and functions httpsduktapeorgguidehtmlduktapebuiltins

2173 Persistent JavaScript

When a javascript script is executed it is evaluated in the global javascript context Care should be taken that localvariables may pollute that context so it is in general recommended that all JavaScript scripts are wrapped

(function() user code

)()

It is also possible to deliberately load functions and other code into the global context persistently and have thatcode permanently available and running When the JavaScript engine initialises it automatically runs a special startupscript

storescriptsovmsmainjs

That script can in turn include other code If you make a change to such persistent code and want to reload it you canwith

OVMS script reload

2174 JavaScript Modules

The OVMS JavaScript engine supports the concept of modules (using the nodejs style of exports) Such modules canbe written like this

60 Chapter 2 User Guide

Open Vehicles

exportsprint = function(obj ind) var type = typeof objif (type == object ampamp ArrayisArray(obj)) type = arrayif (ind) ind =

switch (type) case string

print( + objreplace(g ) + )break

case arrayprint([n)for (var i = 0 i lt objlength i++) print(ind + )exportsprint(obj[i] ind + )if (i = objlength-1) print()print(n)

print(ind + ])break

case objectprint(n)var keys = Objectkeys(obj)for (var i = 0 i lt keyslength i++) print(ind + + keys[i] + )exportsprint(obj[keys[i]] ind + )if (i = keyslength-1) print()print(n)

print(ind + )break

defaultprint(obj)

if (ind == ) print(n)

By convention modules such as this are placed in the storescriptslib directory as ltmodulenamegtjsThese modules can be loaded with

JSON = require(libJSON)

And used as

JSONprint(this)

To automatically load a custom module on startup add the MyPlugin = require(libMyPlugin) lineto ovmsmainjs

There are a number of internal modules already provided with the firmware and by convention these are providedunder the intltmodulenamegt namespace The above JSON module is for example provided as intJSON andautomatically loaded into the global context These internal modules can be directly used (so JSONprint(this)works directly)

217 Scripting 61

Open Vehicles

2175 Testing JavaScript Modules

Use the editor (see Tools menu) to test or evaluate arbitrary Javascript code This can be done on the fly ie withoutsaving the code to a file first Think of it as a server side Javascript shell

Testing modules normally involves reloading the engine as the require() call caches all loaded modules untilrestart To avoid this during module development use the following template code This mimics the require() callwithout caching and allows to do tests within the same evaluation run

Load modulemymodule = (function()exports =

insert module code here

return exports)()

Module API testsmymodulemyfunction1()JSONprint(mymodulemyfunction2())

As the module is actually loaded into the global context this way just like using require() anything else using themodule API (eg a web plugin) will also work after evaluation

2176 Heap Memory

Due to limitations of the general esp-idf system memory management Duktape will normally use the custom memorymanager umm_malloc by Ralph Hempel

umm_malloc needs a dedicated chunk of the system memory to work with The default for Duktape is 512 KB(taken from SPIRAM) which is normally sufficient even for extended scripting If you need more RAM the sizecan be changed by config set module duktapeheapsize ltsize_in_KBgt Maximum allowed size is1024 KB The heap size needs to be configured at Duktape startup and cannot be changed while Duktape is runningTo reconfigure the heap size set the new configuration and do a script reload

Call meminfo() to query the current heap memory usage status The function returns an object containing somestandard and some memory library internal info The shell command script meminfo outputs the object in JSONformat Example

OVMS script meminfo

totalBytes 524224usedBytes 273344freeBytes 250880largestFreeBytes 180608memlib ummummTotalEntries 2723ummUsedEntries 2615ummFreeEntries 108ummTotalBlocks 16382ummUsedBlocks 8542ummFreeBlocks 7840ummMaxFreeContiguousBlocks 5644ummUsageMetric 108ummFragmentationMetric 27

62 Chapter 2 User Guide

Open Vehicles

ldquolargestFreeBytesrdquo is the largest block of contiguous memory available Note these values will change by someamount between the garbage collection runs done every 60 seconds the maximum usage will be just before thegarbage collection and the base line just after

ldquomemlibrdquo tells about the memory manager in use the following fields are the internal state variables and statistics ofthat manager (having the memlib name as a name prefix) These can be useful to monitor the memory managementload and performance

If running a firmware configured to use the default system memory manager the output will look like this

OVMS script meminfo

totalBytes 4072176usedBytes 415996freeBytes 3656180largestFreeBytes 3635864memlib syssysMinimumFreeBytes 3653072sysAllocatedBlocks 6013sysFreeBlocks 454sysTotalBlocks 6467

2177 Internal Objects and FunctionsMethods

A number of OVMS objects have been exposed to the JavaScript engine and are available for use by custom scriptsvia the global context

The global context is the analog to the window object in a browser context it can be referenced explicitly as thison the JavaScript toplevel or as globalThis from any context

You can see the global context objects methods functions and modules with the JSONprint(this) method

OVMS script eval JSONprint(this)

performance now function now() [native code]

assert function () [native code] print function () [native code] write function () [native code] meminfo function () [native code] OvmsCommand Exec function Exec() [native code]

OvmsConfig Delete function Delete() [native code] Get function Get() [native code] Instances function Instances() [native code] Params function Params() [native code] Set function Set() [native code]

OvmsEvents Raise function Raise() [native code]

OvmsLocation Status function Status() [native code]

(continues on next page)

217 Scripting 63

Open Vehicles

(continued from previous page)

OvmsMetrics AsFloat function AsFloat() [native code] AsJSON function AsJSON() [native code] Value function Value() [native code]

OvmsNotify Raise function Raise() [native code]

OvmsVehicle ClimateControl function ClimateControl() [native code] Homelink function Homelink() [native code] Lock function Lock() [native code] SetChargeCurrent function SetChargeCurrent() [native code] SetChargeMode function SetChargeMode() [native code] SetChargeTimer function SetChargeTimer() [native code] StartCharge function StartCharge() [native code] StartCooldown function StartCooldown() [native code] StopCharge function StopCharge() [native code] StopCooldown function StopCooldown() [native code] Type function Type() [native code] Unlock function Unlock() [native code] Unvalet function Unvalet() [native code] Valet function Valet() [native code] Wakeup function Wakeup() [native code]

JSON format function () [ecmascript code] print function () [ecmascript code]

PubSub publish function () [ecmascript code] subscribe function () [ecmascript code] clearAllSubscriptions function () [ecmascript code] clearSubscriptions function () [ecmascript code] unsubscribe function () [ecmascript code]

Global Context

bull assert(conditionmessage) Assert that the given condition is true If not raise a JavaScript exceptionerror with the given message

bull print(string) Print the given string on the current terminal If no terminal (for example a backgroundscript) then print to the system console as an informational message

bull write(stringUint8Array) Write the given string or Uint8Array to the current output channel (ieterminalHTTP connection) Use this to transfer binary data to a reader

bull meminfo() Returns an object containing the current heap memory status (see Heap Memory)

bull performancenow() Returns monotonic time since boot in milliseconds with microsecond resolution

64 Chapter 2 User Guide

Open Vehicles

JSON

The JSON module extends the native builtin JSONstringify and JSONparse methods by a format and aprint method to format andor print out a given javascript object in JSON format Both by default insert spacingand indentation for readability and accept an optional false as a second parameter to produce a compact version fortransmission

bull JSONprint(data) Output data (any Javascript data) as JSON readable

bull JSONprint(data false) compact (without spacingindentation)

bull str = JSONformat(data) Format data as JSON string readable

bull str = JSONformat(data false) compact (without spacingindentation)

bull JSONstringify(value[ replacer[ space]]) see MDN JSONstringify

bull JSONparse(text[ reviver]) see MDN JSONparse

Note The JSON module is provided for compatibility with standard Javascript object dumps and for readability Ifperformance is an issue consider using the Duktape native builtins JSONstringify() Duktapeenc() andJSONparse() Duktapedec() (see Duktape builtins and Duktape JSON for explanations of these)

For example Duktapeenc(JC data) is equivalent to JSONformat(data false) except for therepresentation of functions Using the JX encoding will omit unnecessary quotings

Warning All Duktape JSON encoders and decoders have a very high performance penalty and should beavoided for large objects or frequent encodingdecoding with large being any object larger than a handful ofconfiguration or state variables

For general data storage and exchange with the web UI use the CBOR serialization instead

CBOR

CBOR is a binary serialization format and especially with Duktape the better alternative over JSON for storage anddata transmission if human readability isnrsquot required

ldquoCBORrdquo stands for ldquoConcise Binary Object Representationrdquo See httpscborio for details on the specification andavailable implementations CBOR isnrsquot necessarily more compact in storage space but can be encoded and decodedmuch faster and with much less memory overhead as JSON

Duktape implements CBOR support by the builtin CBORencode() and CBORdecode() methods

bull enc = CBORencode(data) Encode data (any Javascript data) to CBOR format (result is an ArrayBuffer)

bull data = CBORdecode(enc) Decode CBOR format (ArrayBufferUint8Array) to Javascript data

CBOR support in Duktape is still considered experimental but the underlying implementation is mature

CBOR also isnrsquot part of the standard browser builtin Javascript APIs yet so the OVMS web framework includes thecbor-js library by Patrick Gansterer (same API as on the Duktape side)

The webserver command API supports binary output from commands amp Javascript API methods and the output canbe passed to CBORdecode() directly

Example

The following scheme shows how to transmit a javascript data object from the module backend into the web frontend

217 Scripting 65

Open Vehicles

Module backendbackendgetdata = function ()

var mydata = pi 3141 fib [ 011235813 ] write(CBORencode(mydata))

Web frontendloadjs( command backendgetdata() output binary )done((stream) =gt

var mydata = CBORdecode(stream))

For full examples see the ldquoAuxBatMonrdquo and ldquoPwrMonrdquo plugins

Note When loading CBOR data via VFSLoad() you need to set the binary option to true so the loader willreturn a Uint8Array instead of a standard string

HTTP

The HTTP API provides asynchronous GET amp POST requests for HTTP and HTTPS Requests can return text andbinary data and follow 301302 redirects automatically Basic authentication is supported (add username amp passwordto the URL) digest authentication is not yet implemented

The handler automatically excludes the request objects from garbage collection until finished (successfailure) so youdonrsquot need to store a global reference to the request

bull req = HTTPRequest(cfg) Perform asynchronous HTTPHTTPS GET or POST request

Pass the request parameters using the cfg object

ndash url standard URLURI syntax optionally including user auth and query string

ndash post optional POST data set to an empty string to force a POST request Note you needto provide this in encoded form If no Content-Type header is given it will default tox-www-form-urlencoded

ndash headers optional array of objects containing key-value pairs of request headers NoteUser-Agent will be set to the standard OVMS user agent if not present here

ndash timeout optional timeout in milliseconds default 120 seconds

ndash binary optional flag true = perform a binary request (see response object)

ndash done optional success callback function called with the response object as argument with thispointing to the request object

ndash fail optional error callback function called with the error string as argument with this point-ing to the request object

ndash always optional final callback function no arguments this = request object

The cfg object is extended and returned by the API (req) It will remain stable at least until the requesthas finished and callbacks have been executed On completion the req object may contain an updatedurl and a redirectCount if redirects have been followed Member error (also passed to the failcallback) will be set to the error description if an error occurred The always callback if present is calledin any case after a done or fail callback has been executed Check thiserror in the alwayscallback to know if an error occurred

On success member object response will be present and contain

66 Chapter 2 User Guide

Open Vehicles

ndash statusCode the numerical HTTP Status response code

ndash statusText the HTTP Status response text

ndash headers array of response headers each represented by an object ltnamegt ltvaluegt

ndash body only for text requests response body as a standard string

ndash data only for binary requests response body as a Uint8Array

Notes any HTTP response from the server is considered success check responsestatusCode forserver specific errors Callbacks are executed without an output channel so all print outputs will bewritten to the system log Hint use JSONprint(this false) in the callback to get a debug logdump of the request

Examples

simple POST ignore all resultsHTTPRequest( url httpsmartpluglocalswitch post state=onampwhen=nowrarr˓ )

fetch and inspect a JSON objectHTTPRequest(

url httpsolarcontrollerlocalstatusfmt=jsondone function(resp)

if (respstatusCode == 200) var status = JSONparse(respbody)if (status[power] gt 5000)OvmsVehicleStartCharge()

else if (status[power] lt 3000)OvmsVehicleStopCharge()

)

override user agent log completed request objectHTTPRequest(

url httpsdexters-webdeftestjsonheaders [ User-Agent Mr What Zit Tooya ]always function() JSONprint(this false)

)

bull HTTPrequest() Legacy alias for HTTPRequest() please do not use

Note SSL requests (https) can take up to 12 seconds on an idle module SSL errors also may not reflect the actualerror for example an empty server response with code 400 may be reported as a general ldquoSSL errorrdquo If you get ldquoSSLerrorrdquo on a valid request you may need to install a custom root CA certificate see SSLTLS

VFS

The VFS API provides asynchronous loading and saving of files on store and sd Text and binary data issupported Currently only complete files can be loaded the saver supports an append mode In any case the data tosaveload needs to fit into RAM twice as the buffer needs to be converted tofrom Javascript

The handler automatically excludes the request objects from garbage collection until finished (successfailure) so youdonrsquot need to store a global reference to the request

217 Scripting 67

Open Vehicles

Loading or saving protected paths (storeovms_config) is not allowed Saving to a path automaticallycreates missing directories

See AuxBatMon 12V History Chart for a complete application usage example

bull req = VFSLoad(cfg) Perform asynchronous file load

Pass the request parameters using the cfg object

ndash path full file path eg sdmydatatelemetryjson

ndash binary optional flag true = perform a binary request returned data will be an Uint8Array)

ndash done optional success callback function called with the data content read as the single argumentthis pointing to the request object

ndash fail optional error callback function called with the error string as argument with this point-ing to the request object

ndash always optional final callback function no arguments this = request object

The cfg object is extended and returned by the API (req) It will remain stable at least until the requesthas finished and callbacks have been executed On success the req object contains a data property (alsopassed to the done callback) which is either a string (text mode) or a Uint8Array (binary mode)

Member error (also passed to the fail callback) will be set to the error description if an error occurredThe always callback if present is called in any case after a done or fail callback has been executedCheck thiserror in the always callback to know if an error occurred

Example

Load a custom telemetry object from a JSON file on SD cardvar telemetryVFSLoad(path sdmydatatelemetryjsondone function(data) telemetry = Duktapedec(jx data) process telemetry

fail function(error) print(Error loading telemetry + error)

)

bull req = VFSSave(cfg) Perform asynchronous file save

Pass the request parameters using the cfg object

ndash data the string or Uint8Array to save

ndash path full file path (missing directories will automatically be created)

ndash append optional flag true = append to the end of the file (also creating the file as necessary)

ndash done optional success callback function called with no arguments this pointing to the requestobject

ndash fail optional error callback function called with the error string as argument with this point-ing to the request object

ndash always optional final callback function no arguments this = request object

The cfg object is extended and returned by the API (req) It will remain stable at least until the requesthas finished and callbacks have been executed

68 Chapter 2 User Guide

Open Vehicles

Member error (also passed to the fail callback) will be set to the error description if an error occurredThe always callback if present is called in any case after a done or fail callback has been executedCheck thiserror in the always callback to know if an error occurred

Example

Save the above telemetry object in JSON format on SD cardVFSSave(

path sdmydatatelemetryjsondata Duktapeenc(jx telemetry)fail function(error)

print(Error saving telemetry + error)

)

Warning File IO especially saving can cause short freezes of the module

Minimize save frequency and if possible avoid saving while the vehicle is in operation (driving charging) byusing a check like

Saving to VFS may cause short blockings so only allow when vehicle is offfunction allowSave()

return OvmsMetricsValue(veon) ampamp OvmsMetricsValue(vccharging)

Note Saving to and loading from SD card

When storing plugin data on an SD card the plugin needs to take care of the SD card being mounted later in the bootprocess than the scripts are loaded Plugins additionally may need to take into account that the user may replace theSD card any time

When trying to save or load from an unmounted SD error will be set to volume not mounted If this happensduring plugin initialization the plugin should subscribe to the SD mount event to retry the loadsave as soon as the SDcard becomes available

Code scheme

var storeFile = sdusrhistorycborvar listen_sdmount = nullvar history =

function loadStoreFile() VFSLoad(path storeFilebinary truedone function(data)

print(storeFile + loadedn)history = CBORdecode(data)startRecording()

fail function(error)

print(storeFile + + thiserror + n)if (listen_sdmount ampamp thiserror == volume not mounted)

retry once after SD mountlisten_sdmount = PubSubsubscribe(sdmounted loadStoreFile)

else

(continues on next page)

217 Scripting 69

Open Vehicles

(continued from previous page)

startRecording()

)

function startRecording() if (listen_sdmount) PubSubunsubscribe(listen_sdmount)listen_sdmount = null

PubSubsubscribe(tickerEvent ticker) for example

if (storeFile) loadStoreFile()

else startRecording()

PubSub

The PubSub module provides access to a Publish-Subscribe framework In particular this framework is used to deliverevents to the persistent JavaScript framework in a high performance flexible manner An example script to print outthe ticker10 event is

var myTicker=function(msgdata) print(Event +msg+n)

PubSubsubscribe(ticker10myTicker)

The above example created a function myTicker in global context to print out the provided event name Then thePubSubsubscribe module method is used to subscribe to the ticker10 event and have it call myTickerevery ten seconds The result is ldquoEvent ticker10rdquo printed once every ten seconds

PubSub interprets events similar to MQTT as hierarchical topics with dots separating the levels It delivers the eventsin multiple passes with each new pass removing the last dotted part of the topic (ie bottom-up) so the most specificsubscriptions will be called first The handler is always called with the original eventtopic name So to eg catchall events vehiclecharge you can simply subscribe to vehiclecharge and inspect the actual eventname in your handler

PubSubsubscribe(vehiclecharge function (event) print(Got charging related event + event)

)

bull id = PubSubsubscribe(topic handler) Subscribe the function handler to messages of thegiven topic Note that types are not limited to OVMS events The method returns an id to be used tounsubscribe the handler

bull PubSubpublish(topic [data]) Publish a message of the given topic All subscribed handlers willbe called with the topic and data as arguments data can be any Javascript data

bull PubSubunsubscribe(id | handler | topic) Cancel a specific subscription all subscriptions ofa specific handler or all subscriptions to a topic

70 Chapter 2 User Guide

Open Vehicles

OvmsCommand

bull str = OvmsCommandExec(command) The OvmsCommand object exposes one method ldquoExecrdquo Thismethod is passed a single parameter as the command to be executed runs that command and then returnsthe textual output of the command as a string For example

print(OvmsCommandExec(boot status))Last boot was 14 second(s) ago

This is reset 0 since last power cycleDetected boot reason PowerOn (114)Crash counters 0 total 0 early

OvmsConfig

bull array = OvmsConfigParams() Returns the list of available configuration parameters

bull array = OvmsConfigInstances(param) Returns the list of instances for a specific parameter

bull string = OvmsConfigGet(paraminstancedefault) Returns the specified parame-terinstance value

bull object = OvmsConfigGetValues(param [prefix]) Gets all param instances matching theoptional prefix with their associated values If a prefix is given the returned property names will havethe prefix removed Note all values are returned as strings you need to convert them as needed

bull OvmsConfigSet(paraminstancevalue) Sets the specified parameterinstance value

bull OvmsConfigSetValues(param prefix object) Sets all properties of the given object asparam instances after adding the prefix Note non-string property values will be converted to their stringrepresentation

bull OvmsConfigDelete(paraminstance) Deletes the specified parameter instance

Beginning with firmware release 32009 a dedicated configuration parameter usr is provided for plugins Youcan add new config instances simply by setting them for example by OvmsConfigSet(usr mypluginlevel 123) or by the config set command

Read plugin configuration example

Set default configurationvar cfg = level 100 enabled no

Read user configurationObjectassign(cfg OvmsConfigGetValues(usr myplugin))

if (cfg[enabled] == yes) print(Im enabled at level + Number(cfg[level]))

Keep in mind to prefix all newly introduced instances by a unique plugin name so your plugin can nicely coexist withothers

OvmsEvents

This provides access to the OVMS event system While you may raise system events the primary use is to raisecustom events Sending custom events is a lightweight method to inform the web UI (or other plugins) about simplestate changes Use the prefix usr on custom event names to prevent conflicts with later framework additions

217 Scripting 71

Open Vehicles

Another use is the emulation of the setTimeout() and setInterval() browser methods by subscribing to adelayed event Pattern

function myTimeoutHandler() raise the timeout event again here to emulate setInterval()

PubSubsubscribe(usrmyplugintimeout myTimeoutHandler)

start timeoutOvmsEventsRaise(usrmyplugintimeout 1500)

bull OvmsEventsRaise(event [delay_ms]) Signal the event optionally with a delay (millisecondsmust be given as a number) Delays are handled by the event system the method call returns immediately

OvmsLocation

bull isatlocation = OvmsLocationStatus(location) Check if the vehicle is currently in a loca-tionrsquos geofence (pass the location name as defined) Returns true or false or undefined if thelocation name passed is not valid

Note to get the actual GPS coordinates simply read metrics vplatitude vplongitude and vpaltitude

OvmsMetrics

bull str = OvmsMetricsValue(metricname [decode]) Returns the typed value (default) or stringrepresentation (with decode = false) of the metric value

bull num = OvmsMetricsAsFloat(metricname) Returns the float representation of the metric value

bull str = OvmsMetricsAsJSON(metricname) Returns the JSON representation of the metric value

bull obj = OvmsMetricsGetValues([filter] [decode]) Returns an object of all metrics match-ing the optional name filtertemplate (see below) by default decoded into Javascript types (ie numericalvalues will be JS numbers arrays will be JS arrays etc) The object returned is a snapshot the valueswonrsquot be updated

The filter argument may be a string (for substring matching as with metrics list) an array of fullmetric names or an object of which the property names are used as the metric names to get The objectwonrsquot be changed by the call see Objectassign() for a simple way to merge objects Passing anobject is especially convenient if you already have an object to collect metrics data

The decode argument defaults to true pass false to retrieve the metrics string representations insteadof typed values

With the introduction of the OvmsMetricsGetValues() call you can get multiple metrics at once and let thesystem decode them for you Using this you can for example do

Get all metrics matching substring vbc (vehicle battery cell)var metrics = OvmsMetricsGetValues(vbc)print(Temperature of cell 3 + metrics[vbctemp][2] + degCn)print(Voltage of cell 7 + metrics[vbcvoltage][6] + Vn)

Get some specific metricsvar ovmsinfo = OvmsMetricsGetValues([mversion mhardware])JSONprint(ovmsinfo)

72 Chapter 2 User Guide

Open Vehicles

This obsoletes the old pattern of parsing a metricrsquos JSON representation using eval() JSONparse() orDuktapedec() you may still find in some plugins Example

var celltemps = eval(OvmsMetricsAsJSON(vbctemp))print(Temperature of cell 3 + celltemps[2] + degCn)

Warning Never use eval() on unsafe data eg user input eval() executes arbitrary Javascript so canbe exploited for code injection attacks

OvmsNotify

bull id = OvmsNotifyRaise(type subtype message) Send a notification of the given type andsubtype with message as contents Returns the message id allocated or 0 in case of failure Examples

send an info notification to the userOvmsNotifyRaise(info usrmypluginstatus Alive and kicking)

send a JSON stream to a web pluginOvmsNotifyRaise(stream usrmypluginupdate JSONformat(streamdatararr˓false))

send a CSV data record to a serverOvmsNotifyRaise(data usrmypluginrecord -MyStatus086400Alive)

OvmsVehicle

The OvmsVehicle object is the most comprehensive and exposes several methods to access the current vehicle Theseinclude

bull str = OvmsVehicleType() Return the type of the currently loaded vehicle module

bull success = OvmsVehicleWakeup() Wakeup the vehicle (return TRUE if successful)

bull success = OvmsVehicleHomelink(buttondurationms) Fire the given homelink button

bull success = OvmsVehicleClimateControl(onoff) Turn onoff climate control

bull success = OvmsVehicleLock(pin) Lock the vehicle

bull success = OvmsVehicleUnlock(pin) Unlock the vehicle

bull success = OvmsVehicleValet(pin) Activate valet mode

bull success = OvmsVehicleUnvalet(pin) Deactivate valet mode

bull success = OvmsVehicleSetChargeMode(mode) Set the charge mode (ldquostandardrdquo ldquostoragerdquo ldquorangerdquo ldquoperformancerdquo)

bull success = OvmsVehicleSetChargeCurrent(limit) Set the charge current limit (in amps)

bull success = OvmsVehicleSetChargeTimer(onoff start) Set the charge timer

bull success = OvmsVehicleStartCharge() Start the charge

bull success = OvmsVehicleStopCharge() Stop the charge

bull success = OvmsVehicleStartCooldown() Start a cooldown charge

bull success = OvmsVehicleStopCooldown() Stop the cooldown charge

217 Scripting 73

Open Vehicles

bull result = OvmsVehicleObdRequest(arguments) Perform OBDUDS request (synchronous)

Pass the request parameters using the arguments object

ndash txid the CAN ID to send the request to (or 0x7df for broadcast)

ndash rxid the CAN ID to expect the response at (or 0 for broadcast)

ndash request the request to send either a hex encoded string or an Uint8Array

ndash bus optional CAN bus device name default ldquocan1rdquo

ndash timeout optional timeout in milliseconds default 3000

ndash protocol optional protocol to use default 0 = ISOTP_STD ndash see vehicleh for other protocols

The result object will have these properties

ndash error 0 = no error else the error code with negative ranges being system errors positive codes areOBDUDS response error codes (NRCs)

ndash errordesc a human readable error description

ndash response only on success the binary response (Uint8Array)

ndash response_hex only on success hex encoded response (string)

Example

Establish diagnostic session with an ECUvar res = OvmsVehicleObdRequest( txid 0x765 rxid 0x7cf request 1003 rarr˓)if (reserror)print(reserrortext)

elseprint(resresponse_hex)

2178 Test Utilities

You can use the web UI editor and shell to edit upload and test script files If you need many test cycles a convenientalternative is to use shell scripts to automate the process

If yoursquove configured ssh public key authentication you can simply use scp to upload scripts and ssh to executecommands

binbash Upload amp execute a script file

FILE=testjsPATH=storescripts

OVMS_HOST=yourovmslocal

SCP=usrbinscp -qSSH=usrbinssh

Upload$SCP $FILE $OVMS_HOST$PATH$FILE

Execute$SSH $OVMS_HOST script run $FILE

74 Chapter 2 User Guide

Open Vehicles

Customize to your needs If you want to test a plugin simply replace the script run command by scriptreload followed by some script eval calls to your plugin API

Note this may be slow as the ssh session needs to be negotiated for every command

A faster option is using the OVMS HTTP REST API The following script uses curl to upload and execute a script

binbash Upload amp execute a script file

FILE=testjsPATH=storescripts

OVMS_HOST=httpyourovmslocalOVMS_USER=adminOVMS_PASS=yourpassword

CURL=usrbincurl -c auth -b authSED=usrbinsedDATE=usrbindate

Loginif [[ -e auth ]] then

AUTHAGE=$(($($DATE +s) - $($DATE +s -r auth)))else

AUTHAGE=3600fiif [[ $AUTHAGE -ge 3600 ]] thenRES=$($CURL $OVMS_HOSTlogin --data-urlencode username=$OVMS_USER --data-

rarr˓urlencode password=$OVMS_PASS 2gtdevnull)if [[ $RES =~ Error ]] thenecho -n LOGIN ERROR echo $RES | $SED -e sltligt([^lt])1grm authexit 1

fifi

UploadRES=$($CURL $OVMS_HOSTedit --data-urlencode path=$PATH$FILE --data-rarr˓urlencode content$FILE 2gtdevnull)if [[ $RES =~ Error ]] thenecho -n UPLOAD ERROR echo $RES | $SED -e sltligt([^lt])1grm authexit 1

fi

Execute$CURL $OVMS_HOSTapiexecute --data-urlencode command=script run $FILE

217 Scripting 75

Open Vehicles

218 Factory Reset

2181 Module Configuration

A standard factory reset erases the configuration store After a factory reset you will be able to access the USBconsole with an empty module password and the ldquoOVMSrdquo wifi access point with the initial password ldquoOVMSinitrdquo Werecommend using the setup wizard to configure the module or restoring a configuration backup as soon as possible1as the module is accessible by anyone knowing the initial password

The standard factory reset does not revert OTA firmware installs See below for methods to switch back to andoptionally replace the factory firmware

Method 1 Command

If you have console command access a factory reset can be accomplished with this command

OVMS module factory resetReset configuration store to factory defaults and lose all configuration data (yn)rarr˓yStore partition is at 00c10000 size 00100000Unmounting configuration storeErasing 1048576 bytes of flashFactory reset of configuration store complete and reboot now

That command will erase all configuration store and reboot to an empty configuration

Note to issue this command from the web shell or a remote shell (App Server ) you need to skip the confirmationstep by adding the option -noconfirm ie

OVMS module factory reset -noconfirm

Method 2 SD card

If you donrsquot have console access you can perform a factory reset by placing an empty file named factoryresettxt in the root directory of an SD card and insert that SD into the (running) module The file will be deleted and themodule will reboot within about 30 seconds

Method 3 Switch S2

You can also open the module case remove any SD card (important) power on the module wait 10 seconds thenpush and hold switch ldquoS2rdquo for 10 seconds ldquoS2rdquo is located here

1 Wait for the SSH key generation to finish after reboot before attempting to restore the backup Trying to run both processes concurrently maycrash the module Key generation takes about 2 minutes look for log message ldquoSSH server key installedrdquo

76 Chapter 2 User Guide

Open Vehicles

Method 4 USB

If you donrsquot have console access and donrsquot have an SD card you can perform a factory reset from a PC via USB usingthe esptoolpy tool from the Espressif ESP-IDF toolkit (see below for installation)

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 erase_region 0xC10000 0x100000

Note the port needs to be changed to the one assigned by your system ie devttyUSB0 on a Linux system orCOMx on Windows After using esptoolpy to manually erase the config region you should go into the console and dothe module factory reset step to properly factory reset

Note Methods 1 2 and 3 need a running system ie will not work if your module cannot boot normally In this casefirst try method 4 If that doesnrsquot help also switch back to the factory firmware as shown below

2182 Module Factory Firmware

You can switch back to factory firmware with this command

OVMS ota boot factoryBoot from factory at 0x00010000 (size 0x00400000)

Or without console access (lost module password) using the esptoolpy from the Espressif ESP-IDF toolkit

218 Factory Reset 77

Open Vehicles

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 erase_region 0xd000 0x2000

Note the device needs to be changed to the one assigned by your system ie devttyUSB0 on a Linux system orCOMx on Windows

2183 Flash Factory Firmware via USB

esptoolpy can also be used to flash a new factory firmware Download the firmware file ovms3bin you wantto flash then issue

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 --before default_reset --after hard_reset write_flash --compress --flash_mode dio --flash_freq 40m --flash_size detect 0x10000 ovms3bin

Note if you were running an OTA partition before you also need to switch back to the factory partition as shownabove

2184 Full Reflash via USB

If you accidentally did an erase_flash or erased the wrong region you will need to do a full reflash of your module(including the boot loader and partitioning scheme)

The need for a full reflash will typically show by the USB output of the module boot being just something like

rst0x10 (RTCWDT_RTC_RESET)boot0x3f (SPI_FAST_FLASH_BOOT)flash read err 1000ets_mainc 371ets Jun 8 2016 002257

To do a full reflash download the three bin files from the release you want to flash eg from

httpsovmsdexters-webdefirmwareotav32edge

Then issue

esptoolpy --chip esp32 --port devttySLAB_USBtoUART --baud 921600 --before default_reset --after hard_reset write_flash --compress --flash_mode dio --flash_freq 40m --flash_size detect 0x1000 bootloaderbin 0x10000 ovms3bin 0x8000 partitionsbin

replacing the port and file paths accordingly for your system

If this fails open a support ticket on httpswwwopenvehiclescom and attach a log of the boot process or install thedeveloper environment and do a make flash

2185 Installing esptoolpy

The esptoolpy package and installation instructions can be found here

httpsgithubcomespressifesptool

78 Chapter 2 User Guide

Open Vehicles

The package normally can be installed without manual download using the python package manager ldquopiprdquo ie onUnixLinux

sudo pip install esptool

Warning You can brick your module using the esptool Only use the commands shown above

219 OBDII ECU

2191 Purpose

The OBDII interface is a connector electrical specification and protocol used for viewing the operation and statusof a car It is mandated in all light duty vehicles sold in North America beginning in 1996 and while the focus ofthe information it provides is for monitoring the emissions of Internal Combustion Engines it has proven to be ahandy port for connecting a variety of aftermarket displays and monitors to a car Electric Vehicles have no need foremissions monitoring so often omit the port from the car thus making the these aftermarket devices incompatibleThe OBDII ECU capability of the OVMS v3 is used to create a simulated OBDII port which can be used to attachmany of these aftermarket devices to the car

2192 Cabling

The cable and OBDII connector are not provided with the OVMSv3 module and can be built using the diagram belowAlternatively you can purchase the OVMS V3 HUD OBD II-F Cable from FastTech

DA26 OBDII Female Signal name6 14 CAN3-L16 6 CAN3-H8 4 amp 5 Chassis amp Signal Ground18 16 +12v switched output to HUDdongle

NB Also place a 120 ohm resistor between OBDII pins 14 amp 6 for bus termination

2193 Setup

From the Web Interface check the ldquoStart OBD2ECUrdquo box and select CAN3 from the dropdown menu (if using thewiring diagram above) This will enable the OBDII ECU Task to run the next time the OVMSv3 module is poweredon or reset Also check the ldquoPower on external 12Vrdquo box in order to feed 12v power through to the device Click onSave at the bottom of the page

From the command line the following commands are available

obdii ecu start can3 Starts the OBDII ECU taskobdii ecu stop Stops the OBDII ECU taskobdii ecu list Displays the parameters being served and their current valueobdii ecu reload Reloads the map of parameters after a config change

power ext12v on Turns on power feed to the devicepower ext12v off Turns off power feed to the device

219 OBDII ECU 79

Open Vehicles

2194 Operation

During operation an OBDII device for example a Head-Up Display (HUD) or OBDII Diagnostic module will makeperiodic requests usually a few times per second for a set of parameters The OVMSv3 module will reply to thoseparameters with the metric if configured to do so on an individual basis These parameters can be common itemssuch as vehicle speed engine RPM and engine coolant temperature but because of the differences between ICE andEV vehicles many of the parameters do not have equivalent values in an EV Speed and engine (motor) RPM can bedirectly mapped but there is typically no ldquoengine coolantrdquo That parameter (in fact most parameters) can be mappedto some other value of interest For example the Engine Coolant display on the HUD can be configured to displaymotor or battery temperature instead Engine Load (PID 4 a percentage value) is mapped by default to battery Stateof Charge (also a percentage) However note that not all vehicle metrics may be supported by all vehicles

Parameters requested by the OBDII device are referred to by ldquoPID valuerdquo Note that each PID has a specific range ofallowed values and that it is not possible to directly represent values outside that range For example PID 5 (Enginecoolant temperature) has a range of -40 to +215 it would not be possible to map the full range of motor RPMs to thisparameter Values outside the allowed range are limited to the range boundary value The complete table of possibleparameters are described here httpsenwikipediaorgwikiOBD-II_PIDsMode_01

Vehicle metrics are referred to by name See the table in Appendix 1 for a list of available metrics which vehiclesreport them and which of those are of a format that can be mapped by the OBDII ECU task

2195 Defaults and customization

By default the following mapping of PID value to OVMSv3 metric is used

PID (Dec) PID (Hex) Requested Parameter Mapped Metric Value Metric Name4 0x04 Engine Load Battery SOC vbsoc5 0x05 Coolant Temp Motor Temp vmtemp12 0x0c Motor RPM Motor RPM vmrpm13 0x0d Vehicle Speed Vehicle Speed vpspeed16 0x10 MAF Air Flow 12v Battery vb12vvoltage

The OBDII ECU task supports the remapping and reporting of PIDs 4-18 31 33 47 and 51 (all decimal) PIDs 0and 32 are used by the OBDII protocol for management and not available for assignment Other PIDs return zero

PIDs requested for which no mapping has been established are ignored by the OBDII ECU task As an aid for discov-ering which PIDs are being requested the configuration parameter lsquoautocreatersquo may be used to populate entries intothe obdii ecu list display (lsquoconfig set obd2ecu autocreate yesrsquo) Such autocreated entries are marked as ldquoUnimple-mentedrdquo and return zero to the device They are not added to the configured (saved) obd2ecumap and get cleared ateach boot or reset They may be mapped to a supported metric if desired using

config set obd2ecumap ltPIDgt ltmetric namegt

Example

OVMS config set obd2ecumap 5 vbtemp(map battery temp to engine coolant temp)

OVMS vfs edit storeobd2ecu10(script for fuel pressure PID see below)

OVMS obdii ecu reloadOBDII ECU pid map reloaded

(continues on next page)

80 Chapter 2 User Guide

Open Vehicles

(continued from previous page)

OVMS obdii ecu list

PID Type Value Metric0 (0x00) internal 00000004 (0x04) internal 95000000 vbsoc5 (0x05) metric 16000000 vbtemp10 (0x0a) script 000000011 (0x0b) unimplemented 000000012 (0x0c) internal 0000000 vmrpm13 (0x0d) internal 0000000 vpspeed16 (0x10) internal 13708791 vb12vvoltage32 (0x20) internal 0000000

Types ldquointernalrdquo means default internal handling of the PID ldquometricrdquo means a user-set mapping of PID to thenamed metric ldquounimplementedrdquo are PIDs requested by the device but for which no map has been set ldquoscriptrdquomeans the user has configured a script to handle the PID

2196 Special handling

Several PIDs are handled specially by the OBDII ECU task

bull PIDs 0 and 32 are bit masks that indicate what other PIDs are being reported by the OBDII ECU task These aremaintained internally based on the default mapped and scripted PID table Note that some OBDII devices usePID 0 as a test for ECU presence and operating mode (standard or extended) and ignore the returned valuesThe OBDII ECU task supports both modes

bull PID 12 Engine RPM is often monitored by the OBDII device to detect when the car is turned off Since anEVrsquos motor is not rotating when the car is stopped a HUD may decide to power down when it sees the RPMdrop below a particular value or if there is no variation (jitter) in its value To prevent this the OBDII ECU taskwill source a fake value of 500 rpm plus a small periodic variation if the car is not moving (vehicle speed isless than 1) To actually let the device turn off see ldquoExternal Power Controlrdquo below

bull PID 16 MAF Air Flow is commonly used by OBDII devices to display fuel flow by measuring the amount ofair entering the engine in support of combustion Since this is irrelevant to an EV the OBDII ECU task mapsthis metric to a simple integer Most HUDs displays limit this to a range of 0-199 literhr which is acceptable todisplay the +12v battery voltage Since the conversion factors are complicated this value is at best approximatein spite of its implied precision

bull Mode 9 PID 2 VIN is used to report the carrsquos DMV VIN to the attached OBDII device Since the rest ofthe parameters reported by the OBDII ECU task are simulated and some OBDII devices may use the VIN fortracking purposes the reporting of the VIN may be turned off by setting the privacy flag to ldquoyesrdquo The commandis lsquoconfig set obd2ecu privacy yesrsquo Setting it to lsquonorsquo which is the default allows the reporting of the VIN

bull Mode 9 PID 10 ECU Name is statically mapped to report the OVMSv3rsquos Vehicle ID field (vehicle name notVIN) This string may be customized to any printable string of up to 20 characters if not used with the OVMSv2 or v3 mobile phone applications (lsquoconfig set vehicle id car_namersquo)

2197 Metric Scripts

Should one desire to return a value not directly available by a single named metric it is possible to map a PID to a shortscript where combinations of metrics constants etc may be used to create a custom value Note that the restrictionson PID value ranges still applies Also note that the special handling for PID 12 (engine RPM) is not applied in theOBDII ECU task so it must be included in the script if driving a HUD

219 OBDII ECU 81

Open Vehicles

Scripts should be placed in the directory storeobd2ecuPID where PID is the decimal value of the PID to be pro-cessed Example for creating a ldquokw per kmrdquo sort of metric

ret1=OvmsMetricsAsFloat(vpspeed)ret2=OvmsMetricsAsFloat(vbpower)out=00if (ret1 gt 0) out=ret2ret1 out

Put this text in a file storeobd2ecu4 to map it to the ldquoEngine Loadrdquo PID See ldquoSimple Editorrdquo chapter for file editingor use lsquovfs appendrsquo commands (tedious) Note however that Vehicle Power (vbpower) is not supported on all cars(which is why this is not the default mapping for this PID)

Warning The error handling of the scripting engine is very rough at this writing and will typically cause a full modulereboot if anything goes wrong in a script

2198 External Power Control

Since the OVMSv3 module remains powered at all times and the normal means for deducing that a car has beenturned off donrsquot work on an EV (see PID 12 above) an external OBDII device needs to be explicitly turned on andoff This is currently done with short event scripts The following commands configure the OVMSv3 to make theexternal 12v feed follow the vehicle onoff state or use the vfs edit command to create or modify the files

vfs mkdir storeeventsvfs mkdir storeeventsvehicleonvfs mkdir storeeventsvehicleoff

vfs append power ext12v on storeeventsvehicleonext12vvfs append power ext12v off storeeventsvehicleoffext12v

220 EGPIO

2201 Hardware

The OVMS has 10 general purpose IO ports provided by a MAX7317 IO expander

The MAX7317 ports can be individually configured as either an open-drain output or an overvoltage-protected Schmittinput Being open-drain you need to add pull-up resistors for input and output switch uses to get a defined high level(eg 10K to 33V) See the datasheet for details on maximum current amp voltage ratings

Depending on your hardware configuration up to 4 ports may be used by the module 6 are generally free to use

Port Signal(s) ExpPin Default usage0 MDM_EN 15 Modem enable1 SW_CTL ndash Ext12V control (SW_12V)2 CAN1_EN + EIO_1 17 CAN1 transceiver enable3 MDM_DTR + EIO_2 19 Modem sleep control4 EIO_3 21 -free-5 EIO_4 20 -free-6 EIO_5 18 -free-7 EIO_6 16 -free-8 EIO_7 14 -free-9 EIO_8 12 -free-

82 Chapter 2 User Guide

Open Vehicles

SW_CTL (port 1) controls a BTS452R power switch which could deliver a nominal output of 25W or 18A and up to40W or 29A short term at the SW_12V pin but the main fuse of the module (located at the corner near the DB9 plug)limits the 12V current total sum of the board plus any external hardware to continuous 075A on a revision 31 boardand 10A on a revision 32 board The unswitched EXT_12V pin is also behind the fuse

The module including modem needs a 12V current share of ~80mA in full operation Calculate with 100mA to beon the safe side That leaves continuous 065A on a revision 31 board and 09A on a revision 32 board for externaldevices and addons powered by the module The fuse has a little headroom but donrsquot rely on that

SW_12V is meant to power auxiliary devices from the OVMS for example head-up displays Of course you can aswell power a standard 12V automotive relay or fan directly from this without additional hardware

The EGPIO (EIO) ports are not connected directly to the DA26 connector but are available atthe internal expansion port To route an EGPIO port to the DA26 connector connect it to oneof the GEP_17 lines at the expansion port either directly or via some additional driver

Fig 1 Expansion Port (Prototype PCB)Fig 2 DA26 Connector

Example to route EIO_8 (port 9) to GEP_7 (pin 21 on the DA26) seta jumper on pins 10+12 on the expansion port

2202 Commands

EGPIO control is provided by the egpio command set

bull egpio output ltportgt ltlevelgt [ltportgt ltlevelgt] ndash set output level(s)

bull egpio input ltportgt [ltportgt ] ndash query inputlevel(s)

bull egpio status ndash show output input amp monitor status

bull egpio monitor lton|offgt [ports] ndash enabledisablemonitoring

bull egpio monitor status ndash show current monitoring status

220 EGPIO 83

Open Vehicles

To configure a port for input it needs to be switched to output levelhigh (1) That is done automatically by the input and monitor com-mands

If you set multiple outputs the ports will be set one at a time so outputlevels will change with a slight delay You can use this behaviour to setdata lines before a clock line eg when sending bits serially into a shiftregister

Note The MAX7317 needs active polling to detect input state changes Monitoring is disabled by default it can beenabled manually or configured to start automatically on module init Without monitoring only manual input querieswill update the input state trigger input events and input metric updates

2203 Configuration

Parameter Instance Descriptionauto egpio yes = Start monitoring on boot (default no)egpio monitorports List of ports to monitor by default (space separated)egpio monitorinterval Polling interval in milliseconds (min 10 default 50)

The default interval of 50 ms (= 20 Hz) means an input signal needs to be at least 50 ms long to be detected Thispolling frequency produces a CPU load of ~05 on core 1 and is normally sufficient to detect even very short buttonpushes

2204 Metrics

Metric name Example value Descriptionmegpioinput 012345679 EGPIO input port state (ports 0 9 present=high)megpiomonitor 89 EGPIO input monitoring portsmegpiooutput 45679 EGPIO output port state

Hint to process these metrics from Javascript read them into an array using eval() and test for the presence of aport number using eg the includes() method in a browser plugin Duktape does not support includes() youcan test indexOf(port) instead

Example

var input = eval(OvmsMetricsAsJSON(megpioinput))if (inputindexOf(9) lt 0)

print(Input port 9 (EIO8) is currently lown)

2205 Events

Event Data Purposeegpioinputltportgtltstategt ndash EGPIO input port change (port=0 9 state=highlow)egpiooutputltportgtltstategt ndash EGPIO output port change (port=0 9 state=highlow)

84 Chapter 2 User Guide

Open Vehicles

Hint to listen to events from Javascript bind to msgevent on a receiver object from browser context or usePubSub from module context

Example

PubSubsubscribe(egpioinput9low function()print(Input port 9 (EIO8) is now lown)

)

221 TPMS

OVMS v3 includes a capability to read and write sets of TPMS wheel sensors IDs from the vehicle TPMS ECU andstore in your configuration Support for this is vehicle-specific and may require optional hardware boards so pleasefollow your individual vehicle guides for further information

The command to read the current TPMS wheel sensor IDs from the car is

OVMS tpms read SET

(replace SET with your own identifier for this set of wheels such as lsquosummerrsquo lsquowinterrsquo etc)

You can check the stored wheel sensor ID sets with

OVMS tpms list

If you change wheels you can write the new wheel IDs to the TPMS ECU in the car with

OVMS tpms write SET

(replace SET with your own identifier for this set of wheels such as lsquosummerrsquo lsquowinterrsquo etc)

Note that in most cases the car must be switched on for the above commands to work Please refer to your vehiclespecific user guide for more information on this

Note also that OVMS doesnrsquot have any radio capable of receiving TPMS signals and cannot read the IDs from thewheel sensors themselves OVMS can only read the IDs from the TPMS ECU in the car itself You can howeverdrop by pretty much any garage (or use any of a large number of TPMS tools) to trigger and read these IDs from thewheels Once your garage gives you the sensor IDs (each expressed as an 8 character hexadecimal ID) you can enterthem into OVMS as

OVMS tpms set SET ID1 ID2 ID3 ID4 (replace SET with your own identifier for this set of wheelsand ID1 with the hexadecimal sensor ID)

222 Optional K-Line Expansion Board

The optional K-Line Expansion Board is available to extend the capabilities of the OVMS system It can be used totalk to vehicle ECUs using K-Line communication standards

221 TPMS 85

Open Vehicles

There are two installation options

1 If you are using a modem module you install the K-Line Expansion Board on top of the modem Unscrew thefour black screws holding the modem in place In your K-Line expansion board kit you will find four brassstand offs with holes at one end and small bolts at the other Use these to screw down the modem Now orientthe K-line Expansion Board so the top left corner (marked with a white triangle) matches the white triangle onthe modem board Carefully push the K-Line Expansion Board into place (making sure that the pins align andare not bent) Once done the four black screws can be used to secure it in place

2 If you are not using a modem module you install the K-Line Expansion Board directly onto the main OVMSboard Screw the provided standoffs into the main board and Carefully attach the provided pin headers intothe main OVMS board Now orient the K-line Expansion Board so the top left corner (marked with a whitetriangle) matches the white triangle on the main OVMS board Carefully push the K-Line Expansion Board intoplace (making sure that the pins align and are not bent) Once done the four black screws can be used to secureit in place

86 Chapter 2 User Guide

Open Vehicles

Next the K-Line expansion board will need to be configured to match your vehiclersquos K-Line bus and ECU hardwarerequirements Refer to your vehicle specific guide for information on what your vehicle requires

bull S1 is used to turn onoff the extra lsquomasterrsquo mode components For most vehicles this should be OFF

bull SW1 is used to select the power source for the K-Line bus It can be 0 (no power connected) 1 (5v powerfrom USB bus) 2 (5v power converted from vehiclersquos 12v power) or 3 (12v power direct from the vehicle)For most vehicles either 2 or 3 is used

The K-Line bus from the vehicle is connected via a vehicle specific cable This connection is usually to pin 1 on theDB9 connector On OVMS modules v32 and later (as well as v31 boards labelled on board as July 2018 or later)this is internally connected to GEP7 (General Expansion Pin 7) This is necessary to bring the K-Line bus up to theinternal expansion pins (for the K-Line Expansion Board to be able to reach it)

If you have an earlier board there is a relatively simply wiring modification that can be made to upgrade to this

1 You will need a soldering iron solder and a small length of insulated wire

2 Pin 1 on the DB9 connector is the K-Line pin from the vehicle

3 Pin 21 on the DA26 connector is GEP 7 (which is also connected to a pin on internal expansion connector)

4 On the underside of the board you can solder a jumper wire between DB9 pin 1 and DA26 pin 21 to makethis connection

Please refer to the vehicle specific guides for further information on this

222 Optional K-Line Expansion Board 87

Open Vehicles

88 Chapter 2 User Guide

CHAPTER 3

Plugins

The OVMS can easily be extended by plugins Plugins may consist of any combination of module scripts (Javascript)and web UI extensions (HTML)

Installation currently needs to be done manually but is simple See below and the plugin documentation on specificsteps and on how to use the plugin functions A plugin store with simplified download and optional automatic updatingwill be provided in the future

This page is intended as an overview of all plugins currently available in the OVMS repository If yoursquore a plugindeveloper and want to add your plugin here please submit a pull request containing your plugin directory Organizeyour files and include a READMErst as shown here

31 ABRP abetterrouteplannercom

Send live data to abetterrouteplannercom

Overview

abetterrouteplanner is probably the best website to plan a route with an EV and optimize the number of stops neededand where to charge your vehicle

Moreover it has a wonderful functionality to update your plan taking into account your live data to adjust withthe real consumption of the vehicle by connecting an obd device and soft like EVNotify or Torque Pro

This plugin sends your live data from the OVMS box

Author David S Arnold

New in version 12 Your own parameters (car model abrp token but also api-url) are now stored as config param-eters you can consult them using the shell with config list usr or modify with config set command

89

Open Vehicles

Contents

bull ABRP abetterrouteplannercom

ndash Installation

ndash Script code

ndash Usage

311 Installation

You can use the embedded website toolsshell and toolseditor of the OVMS box to create the directory and file Thiseditor will allow you to paste the plugin code from the documentation

Files to be created in storescripts

bull ovmsmainjs if not already exists

bull sendlivedata2abrpjs by copying the file below

Next configure your car model API URL amp token

Note ABRP only supports live data feeds for some car models You can request a notification when support has beenadded for your car Do not feed live data using other car models Also ABRP has not yet added this OVMS pluginas a general data source so you need to disguise as ldquoTorquerdquo

If using the ABRP 4 UI

bull Login to abetterrouteplanner

bull Open ldquoSettingsrdquo enable detailed setup

bull Add your car (if ABRP has no live support for your car model it will display ldquoLive data not availablerdquo)

bull Click ldquoLink Torquerdquo click ldquoNextrdquo 3 times

bull Set the ldquoWebserver URLrdquo by config set usr abrpurl Note according to Iterniothe URL httpapiiterniocom1tlmsend should generally be used here instead of theTorque specific one displayed

bull Set the ldquoUser Email Addressrdquo (API token) by config set usr abrpuser_token

If using ABRP classic UI

bull Login to abetterrouteplanner in classic view

bull In Settingsmore Settings therersquos an item lsquoLive Car Connectionrsquo with 2 buttons lsquoSetuprsquo and lsquoView livedatarsquo

bull Click on Setup (if there is no Setup button live data support isnrsquot available for your car model)

bull Click on Torque

bull Set the ldquoWebserver URLrdquo by config set usr abrpurl

bull Set the ldquoUser Email Addressrdquo (API token) by config set usr abrpuser_token

Determine your car model code

bull Open API car models list

90 Chapter 3 Plugins

Open Vehicles

bull To improve readability optionally paste the page into JSONlintcom

bull Search for your car brand and model the code is the field following the car specification for examplerenaultzoe2052r110

bull Set the code by config set usr abrpcar_model

Finally reboot your OVMS module This was a one-time configuration

Yoursquore now ready Test it with the shell page in the embedded web server using the command script eval abrpinfo() and then with the command script eval abrponetime() You can also do it with the mobile app

312 Script code

This is a javascript code to extract in the file sendlivedata2abrpjs

Warning note the minimum firmware version 32008-147

1 2 storescriptssendlivedata2abrpjs3 4 Module plugin5 Send live data to a better route planner6 This version uses the embedded GSM of OVMS so theres an impact on data

rarr˓consumption7 requires OVMS firmware version 32008-147 minimum (for HTTP call)8 9 Version 13 2020 inf0mike (forum httpswwwopenvehiclescom)

10 11 Enable12 - install at above path13 - add to storescriptsovmsmainjs14 abrp = require(sendlivedata2abrp)15 - script reload16 17 Usage18 - script eval abrpinfo() =gt to display vehicle data to be sent to abrp19 - script eval abrponetime() =gt to launch one time the request to abrp server20 - script eval abrpsend(1) =gt toggle send data to abrp21 - (0) =gt stop sending data22 - script eval abrpresetConfig() =gt reset configuration to defaults23 24 Version 13 updates25 - Fix for rounding of fractional SOC causing abrp to report SOC off by 126 - Fix for altitude never being sent27 - New convenience method to reset config to defaults28 29 Version 12 updates30 - based now on OVMS configuration to store user token car model and url31 - review messages sent during charge32 - send a message when vehicle is on before moving to update abrp33 34 Version 11 fix and update35 - fixed the utc refreshing issue36 - send notifications37 - send live data only if necessary

(continues on next page)

31 ABRP abetterrouteplannercom 91

Open Vehicles

(continued from previous page)

38 39

40

41

42 43 Declarations44 CAR_MODEL find your car model here httpsapiiterniocom1tlmget_carmodels_

rarr˓listapi_key=32b2162f-9599-4647-8139-66e9f952837045 OVMS_API_KEY API_KEY to access to ABRP API given by the developer46 MY_TOKEN Your token (corresponding to your abrp profile)47 TIMER_INTERVAL to subscribe to a ticker event48 URL url to send telemetry to abrp following httpsiterniocomindexphp

rarr˓iternio-telemetry-api49 CR Carriage Return for console prints50 51 objTLM JSON object containing data read52 objTimer timer object53 54

55 const CAR_MODEL = 56 const OVMS_API_KEY = 32b2162f-9599-4647-8139-66e9f952837057 const MY_TOKEN = ----58 const TIMER_INTERVAL = ticker60 every minute59 const EVENT_MOTORS_ON = vehicleon60 const URL = httpapiiterniocom1tlmsend61

62 const DEFAULT_CFG = 63 url URL64 user_token MY_TOKEN65 car_model CAR_MODEL66 67

68 const CR = n69

70 var objTLM71 var objTimer objEvent72 var sHasChanged = 73 var bMotorsOn = false74

75 initialise from default76 var abrp_cfg = JSONparse(JSONstringify(DEFAULT_CFG))77

78 check if json object is empty79 function isJsonEmpty(obj) 80 for(var key in obj) 81 if(objhasOwnProperty(key))82 return false83 84 return true85 86

87 Read amp process config88 function readConfig() 89 check if config exist90 var read_cfg = OvmsConfigGetValues(usr abrp)91 print(JSONstringify(read_cfg) + CR)92 if (isJsonEmpty(read_cfg) == true)

(continues on next page)

92 Chapter 3 Plugins

Open Vehicles

(continued from previous page)

93 no config yet set the default values94 OvmsConfigSetValues(usrabrpabrp_cfg)95 else 96 config existing97 abrp_cfgurl = read_cfgurl98 abrp_cfguser_token = read_cfguser_token99 abrp_cfgcar_model = read_cfgcar_model

100 101 102

103 Make json telemetry object104 function InitTelemetryObj() 105 return 106 utc 0107 soc 0108 soh 0109 speed 0110 car_model abrp_cfgcar_model111 lat 0112 lon 0113 alt 0114 ext_temp 0115 is_charging 0116 batt_temp 0117 voltage 0118 current 0119 power 0120 121 122

123 Fill json telemetry object124 function UpdateTelemetryObj(myJSON) 125 if(myJSON)126 if the data object is undefined or null then return early127 return false128 129 var read_num = 0130 var read_str = 131 var read_bool = false132

133 sHasChanged = 134

135 if (bMotorsOn) 136 sHasChanged = _MOTORS-ON137 bMotorsOn = false138 139

140 using Mathfloor avoids rounding up of 5 values to next whole number141 as some vehicles report fractional values Abrp seems to only support integer

rarr˓values142 read_num = Mathfloor(Number(OvmsMetricsValue(vbsoc)))143 if (myJSONsoc = read_num) 144 myJSONsoc = read_num145 sHasChanged += _SOC + myJSONsoc + 146 147

148 read_num = Number(OvmsMetricsValue(vbsoh))(continues on next page)

31 ABRP abetterrouteplannercom 93

Open Vehicles

(continued from previous page)

149 if (myJSONsoh = read_num) 150 myJSONsoh = read_num151 sHasChanged += _SOH + myJSONsoh + 152 153

154 if ( (myJSONsoh + myJSONsoc) == 0 ) 155 Sometimes the canbus is not readable and abrp doesnt like 0 values156 print(canbus not readable reset module and then put motors on + CR)157 return false158 159

160 myJSONlat = OvmsMetricsAsFloat(vplatitude)toFixed(3)161 above code line works except when value is undefined after reboot162

163 read_num = OvmsMetricsAsFloat(vplatitude)164 read_num = read_numtoFixed(3)165 if (myJSONlat = read_num) 166 myJSONlat = read_num167 sHasChanged += _LAT + myJSONlat + deg168 169

170 read_num = Number(OvmsMetricsAsFloat(vplongitude))171 read_num = read_numtoFixed(3)172 if (myJSONlon = read_num) 173 myJSONlon = read_num174 sHasChanged += _LON + myJSONlon + deg175 176

177 read_num = Number(OvmsMetricsAsFloat(vpaltitude))178 read_num = read_numtoFixed(1)179 if (read_num lt= (myJSONalt - 2) || read_num gt= (myJSONalt + 2)) 180 myJSONalt = read_num181 sHasChanged += _ALT + myJSONalt + m182 183

184 read_num = Number(OvmsMetricsValue(vbpower))185 myJSONpower = read_numtoFixed(1)186

187 myJSONspeed=Number(OvmsMetricsValue(vpspeed))188 myJSONbatt_temp=Number(OvmsMetricsValue(vbtemp))189 myJSONext_temp=Number(OvmsMetricsValue(vetemp))190 myJSONvoltage=Number(OvmsMetricsValue(vbvoltage))191 myJSONcurrent=Number(OvmsMetricsValue(vbcurrent))192

193 myJSONutc = Mathtrunc(Datenow()1000)194 myJSONutc = OvmsMetricsValue(mtimeutc)195

196 read_bool = Boolean(OvmsMetricsValue(vccharging))197 vccharging is also on when regen =gt not wanted here198 read_str = OvmsMetricsValue(vcstate)199 if ( (read_str == charging) || (read_str == topoff) ) 200 myJSONis_charging = 1201 read_str = OvmsMetricsValue(vcmode)202 if (sHasChanged = ) 203 sHasChanged += _CHRG + read_str + ( + OvmsMetricsValue(vccharging)

rarr˓+ )204 print(Charging in mode + read_str + CR)

(continues on next page)

94 Chapter 3 Plugins

Open Vehicles

(continued from previous page)

205 206 else 207 myJSONis_charging = 0208 209

210 myJSONcar_model = abrp_cfgcar_model211

212 return (sHasChanged == )213 214

215 Show available vehicle data216 function DisplayLiveData(myJSON) 217 var newcontent = 218 newcontent += altitude = + myJSONalt + m + CR GPS altitude219 newcontent += latitude = + myJSONlat + deg + CR GPS latitude220 newcontent += longitude= + myJSONlon + deg + CR GPS longitude221 newcontent += ext temp = + myJSONext_temp + degC + CR Ambient

rarr˓temperature222 newcontent += charge = + myJSONsoc + + CR State of charge223 newcontent += health = + myJSONsoh + + CR State of health224 newcontent += bat temp = + myJSONbatt_temp + degC + CR Main battery

rarr˓momentary temperature225 newcontent += voltage = + myJSONvoltage + V + CR Main battery

rarr˓momentary voltage226 newcontent += current = + myJSONcurrent + A + CR Main battery

rarr˓momentary current227 newcontent += power = + myJSONpower + kW + CR Main battery

rarr˓momentary power228 newcontent += charging = + myJSONis_charging + CR yes = currently

rarr˓charging229 print(newcontent)230 231

232 function InitTelemetry() 233 objTLM = InitTelemetryObj()234 sHasChanged = 235 236

237 function UpdateTelemetry() 238 var bChanged = UpdateTelemetryObj(objTLM)239 if (bChanged) DisplayLiveData(objTLM) 240 return bChanged241 242

243 function CloseTelemetry() 244 objTLM = null245 sHasChanged = 246 247

248 http request callback if successful249 function OnRequestDone(resp) 250 print(response=+JSONstringify(resp)+CR)251 OvmsNotifyRaise(info usrabrpstatus ABRP + sHasChanged)252 253

254 http request callback if failed255 function OnRequestFail(error)

(continues on next page)

31 ABRP abetterrouteplannercom 95

Open Vehicles

(continued from previous page)

256 print(error=+JSONstringify(error)+CR)257 OvmsNotifyRaise(info usrabrpstatus ABRP + JSONstringify(error))258 259

260 Return full url with JSON telemetry object261 function GetUrlABRP() 262 var urljson = abrp_cfgurl263 urljson += 264 urljson += api_key= + OVMS_API_KEY265 urljson += amp266 urljson += token= + abrp_cfguser_token267 urljson += amp268 urljson += tlm= + encodeURIComponent(JSONstringify(objTLM))269 print(urljson + CR)270 return urljson271 272

273 Return config object for HTTP request274 function GetURLcfg() 275 var cfg = 276 url GetUrlABRP()277 done function(resp) OnRequestDone(resp)278 fail function(err) OnRequestFail(err)279 280 return cfg281 282

283 function SendLiveData() 284 if (UpdateTelemetry()) 285 HTTPRequest( GetURLcfg() )286 287 288

289 function Reactivate_MotorsOn() 290 bMotorsOn = true291 SendLiveData()292 293

294 function InitTimer() 295 objTimer = PubSubsubscribe(TIMER_INTERVAL SendLiveData)296 objEvent = PubSubsubscribe(EVENT_MOTORS_ON SendLiveData)297 298

299 function CloseTimer() 300 PubSubunsubscribe(objEvent)301 PubSubunsubscribe(objTimer)302 objEvent = null303 objTimer = null304 305

306 API method abrponetime()307 Read and send data but only once no timer launched308 exportsonetime = function() 309 readConfig()310 InitTelemetry()311 SendLiveData()312 CloseTelemetry()

(continues on next page)

96 Chapter 3 Plugins

Open Vehicles

(continued from previous page)

313 314

315 API method abrpinfo()316 Do not send any data just read vehicle data and writes in the console317 exportsinfo = function() 318 readConfig()319 InitTelemetry()320 UpdateTelemetry()321 CloseTelemetry()322 323

324 API method abrpresetConfig()325 Resets stored config to default326 exportsresetConfig = function() 327 OvmsConfigSetValues(usrabrp DEFAULT_CFG)328 print(JSONstringify(abrp_cfg))329 OvmsNotifyRaise(info usrabrpstatus ABRPconfig changed)330 331

332 API method abrpsend()333 Checks every minut if important data has changed and send it334 exportssend = function(onoff) 335 if (onoff) 336 readConfig()337 if (objTimer = null) 338 print(Already running + CR)339 return340 341 print(Start sending data + CR)342 InitTelemetry()343 SendLiveData()344 InitTimer()345 OvmsNotifyRaise(info usrabrpstatus ABRPstarted)346 else 347 if (objTimer == null) 348 print(Already stopped + CR)349 return350 351 print(Stop sending data + CR)352 CloseTimer()353 CloseTelemetry()354 OvmsNotifyRaise(info usrabrpstatus ABRPstopped)355 356

313 Usage

How to make it run

bull install as described in lsquoInstallationrsquo

bull add to storescriptsovmsmainjs abrp = require(sendlivedata2abrp)

bull script reload

With command lines in the OVMS android or iOS app in the messages part

31 ABRP abetterrouteplannercom 97

Open Vehicles

bull script eval abrpinfo() =gt to display vehicle data to be sent to abrp

bull script eval abrponetime() =gt to launch one time the request to abrp server

bull script eval abrpsend(1) =gt toggle send data to abrp

bull script eval abrpsend(0) =gt stop sending data

bull script eval abrpresetConfig() =gt reset configuration to defaults

Also in the messages part configuration can be updated with

bull config set usr abrpcar_model ltvaluegt

bull config set usr abrpurl ltvaluegt

bull config set usr abrpuser_token ltvaluegt

32 AuxBatMon 12V History Chart

Web chart showing last 24 hours of 12V battery metrics (similar to Android App)

Version 23 by Michael Balzer ltdexterdexters-webdegt

The module plugin records the relevant 12V battery metrics (voltage reference voltage current charger and environ-ment temperatures) once per minute for up to 24 hours by default

The web plugin renders these recordings into a time series chart and continues feeding live updates into the chart Thechart is zoomable and can be panned along the X axis

Since version 20 metrics history data is stored in a file and restored automatically on rebootreload This needsOVMS firmware gt= 32008-235 to work (will fallback to no saving on earlier versions)

98 Chapter 3 Plugins

Open Vehicles

Version 23 changes the file and transfer encoding from JSON to CBOR Upgrading is strongly recommended asthis has a substantial performance gain for both the module (scripting engine) and the web user interface (loading thechart)

321 Installation

1 Save auxbatmonjs as storescriptslibauxbatmonjs

2 Add line to storescriptsovmsmainjs

bull auxbatmon = require(libauxbatmon)

3 Issue script reload or evaluate the require line

4 Install auxbatmonhtm web plugin recommended setup

bull Type Page

bull Page usrauxbatmon

bull Label 12V History

bull Menu Tools

bull Auth Cookie

322 Configuration

No live config currently You can customize the sample interval (default 60 seconds) and the history size (default24 hours) by changing the constants in the code Take care to match a customization in both the module and the webplugin

The persistent history storage file is storeusrauxbatmoncbor by default It needs ~30 kB with the defaultconfiguration If space is tight on your store partition you can change the file location to sd in the sourcecode

323 Plugin API

auxbatmondump(CBOR) -- dump recorded history data in CBOR format (binary)auxbatmondump() -- dump recorded history data in JSON formatauxbatmondump() -- get a copy of the history data object

33 ChgInd Charge State Indicator

Control three LEDs to indicate charging amp SOC level

Version 10 by Michael Balzer ltdexterdexters-webdegt

Following an idea by ldquogreen_foxrdquo on the german Twizy forum (not limited to the Twizy) to implement an externallyvisible charge indicator

Use a red a green and a blue LED to signal charge state

bull OFF = not charging

bull RED = charging SOC below 20

33 ChgInd Charge State Indicator 99

Open Vehicles

bull YELLOW (RED+GREEN) = charging SOC 20 80

bull GREEN = charging SOC above 80

bull BLUE = fully charged (held for 15 minutes)

This plugin uses three EGPIO lines to control the three LEDs (KISS) By using a shift register this could be reducedto two lines by using a serial protocol to one line The latter would need protocol support in the EGPIO (todo)

331 Installation

1 Save chgindjs as storescriptslibchgindjs

2 Add line to storescriptsovmsmainjs

bull chgind = require(libchgind)

3 Issue script reload or evaluate the require line

332 Configuration

EGPIO ports to useconst LED_red = 4 EIO_3const LED_green = 5 EIO_4const LED_blue = 6 EIO_5

Time to hold BLUE state after charge stopconst holdTimeMinutes = 15

333 Plugin API

chgindset(state) -- set LED state (offredyellowgreenblue)

34 Edimax Smart Plug Control

Smart Plug control for Edimax models SP-1101W SP-2101W et al

Version 20 by Michael Balzer ltdexterdexters-webdegt

Note may need HTTPrequest() digest auth support to work with newer Edimax firmware (untested)

The smart plug can be bound to a defined location Automatic periodic recharging or charge stop can be configuredvia main battery SOC level andor 12V battery voltage level The plugin can also switch off power at the charge stopevent of the main andor 12V battery

341 Installation

1 Save edimaxjs as storescriptslibedimaxjs

2 Add line to storescriptsovmsmainjs

bull edimax = require(libedimax)

3 Issue script reload

100 Chapter 3 Plugins

Open Vehicles

4 Install edimaxhtm web plugin recommended setup

bull Type Page

bull Page usredimax

bull Label Edimax Smart Plug

bull Menu Config

bull Auth Cookie

5 Install edimax-statushtm web plugin recommended setup

bull Type Hook

bull Page status

bull Hook bodypost

The edimax-statushtm plugin adds power control to the Status pagersquos vehicle panel

342 Configuration

Use the web frontend for simple configuration

Param Instance Descriptionusr edimaxip Edimax IP addressusr edimaxuser username admin by defaultusr edimaxpass password 1234 by defaultusr edimaxlocation optional restrict auto switch to this locationusr edimaxsoc_on optional switch on if SOC atbelowusr edimaxsoc_off optional switch off if SOC ataboveusr edimaxchg_stop_off optional yes = switch off on vehiclechargestopusr edimaxaux_volt_on optional switch on if 12V level atbelowusr edimaxaux_volt_off optional switch off if 12V level ataboveusr edimaxaux_stop_off optional yes = switch off on vehiclecharge12vstop

343 Usage

script eval edimaxget()script eval edimaxset(on | off)script eval edimaxinfo()

Note get() amp set() do an async update (if the location matches) the result is logged Use info() to show thecurrent state

344 Events

usredimaxonusredimaxoffusredimaxerror

34 Edimax Smart Plug Control 101

Open Vehicles

35 Foglight Speed Adaptive Foglight

Automatic speed adaptive fog light using OVMS GPIO port

bull foglightjs ndash module script

bull foglighthtm ndash web dashboard extension

Details httpsdocsopenvehiclescomenlatestcomponentsovms_scriptdocsfoglighthtml

36 PwrMon Trip Power Chart

Web chart showing average speed power amp energy use on the road

Version 12 by Michael Balzer ltdexterdexters-webdegt

The plugin calculates average speed (kph) power (kW) amp energy use (Wpk = Whkm) from the odometer altitudeand energy counters (metrics vbenergyused amp vbenergyrecd) so the vehicle needs to provide thesewith reasonable precision amp resolution

The optional module plugin continuously records and stores the metrics history so the chart can load the last 20 km(by default) when opened The chart will then continue to add live metrics data Without the module plugin the chartwill only display live data

The chart is zoomable and can be panned along the X axis The four data series can be selected and shownhidden asusual by clicking on the series names in the legend click into the chart to highlight a specific data point

The live data may be more accurate than the data stored by the module plugin as it will react directly to the odometerchange while the module plugin can only check the odometer once per second

Version 12 changes the file and transfer encoding from JSON to CBOR Upgrading is strongly recommended asthis has a substantial performance gain for both the module (scripting engine) and the web user interface (loading thechart)

102 Chapter 3 Plugins

Open Vehicles

361 Installation

1 Install pwrmonhtm web plugin recommended setup

bull Type Page

bull Page usrpwrmon

bull Label Trip Power Chart

bull Menu Tools

bull Auth Cookie

2 Optionally

bull Save pwrmonjs as storescriptslibpwrmonjs

bull Add line to storescriptsovmsmainjs

ndash pwrmon = require(libpwrmon)

bull Issue script reload or evaluate the require line

362 Configuration

No live config currently You can customize the sample interval (default 03 km) and the history size (default 20 km)by changing the constants in the code The storage file and interval (1 km) can also be changed

On the web plugin you can customize the live sample interval (default 03 km doesnrsquot need to match the moduleplugin) and the initial zoom (default 8 km)

The persistent history storage file is storeusrpwrmoncbor by default It needs ~10 kB with the defaultconfiguration If space is tight on your store partition you can change the file location to sd in the sourcecode or disable the file by setting an empty string as the filename

363 Plugin API

pwrmondump(CBOR) -- dump recorded history data in CBOR format (binary)pwrmondump() -- dump (print) recorded history data in JSON formatpwrmondata() -- get a copy of the history data object

37 RegenMon Regen Brake Monitor

Live monitoring for regenerative brakelight amp acceleration level

bull regenmonhtm

Details httpsdocsopenvehiclescomenlatestcomponentsovms_webserverdocsregenmonhtml

38 REPIDScan OBD2 PID Scanner UI

Web UI for the OVMS3 RE toolkitrsquos OBD2 PID scanner

Version 21 by Michael Balzer ltdexterdexters-webdegt

37 RegenMon Regen Brake Monitor 103

Open Vehicles

bull 10 Initial release

bull 20 Highlight differences between scan results

bull 21 PID step support

This is a web frontend for the re obdii scan commands

Some basic usage notes are included but you really should have some knowlegde of how accessing ECU and otheronboard devices via OBD-IIUDS works Some pointers to get started

bull httpsenwikipediaorgwikiOBD-II_PIDs

bull httpsenwikipediaorgwikiUnified_Diagnostic_Services

You will need OVMS firmware release 32015-324 or higher to be able to use all features

The UI allows to easily define and keep multiple scans along with notes Scan results of two successive runs can becompared directly The UI checks if vehicle NONE is loaded and shows a button to switch to that otherwise The CANbuses can be started from the UI as well

Scan results are shown in plain text form as delivered by the underlying commands

Feel free to improve and extend (and submit your results)

381 Installation

1 Install repidscanhtm web plugin recommended setup

104 Chapter 3 Plugins

Open Vehicles

bull Type Page

bull Page usrrepidscan

bull Label RE PID Scanner

bull Menu Tools

bull Auth Cookie

382 Usage

Warning The scanner allows to use any poll type Requests will be sent with PIDs only though but somedevices may fail to validate the request length so be careful not to use any write or control poll types

The OBD2 PID scanner performs a series of OBDUDS requests for a range of PIDs and displays the results OnlyPIDs with positive results (responses) will be shown in the results

Enter all values hexadecimal (case irrelevant) Default RXID is TXID+8 try RXID range 500-7FF if you donrsquot knowthe responding ID To send broadcast requests set TXID to 7DF and RXID to 7E8-7EF The PID range must matchthe poll type PID constraints (816 bit)

Click ldquoStartrdquo to run a scan Only one scan can be active at a time but you donrsquot need to stop a scan to start anotherrun

Scan results will be shown automatically when the scan has been completed Scanning a large range of PIDs may takesome time to get intermediate results click ldquoStatusrdquo You can also start the scan do something else and return to thetool later

Differences between two scans are highlighted in both result tabs with added PIDs being marked green (yellow innight mode) and byte value changes being marked red No highlighting is applied if the scans donrsquot share any PIDs

On the next scanner start the previous results (if any) will be copied to the ldquoPreviousrdquo tab You can switch tabs by themouse or keyboard to compare them and look for differences eg after having changed some control on the car

All inputs and outputs can be saved to and loaded from files on the module or SD card Use this to define your areasof interest so you can easily re-run a previously defined scan the next day File format is plain readable JSON so youcan continue analysis or prepare scans offline

Notes to avoid clashing of scan polls with vehicle polls use the scanner only with the vehicle module NONE TheCAN bus to use needs to have been started in active mode The scanner does not send session or tester presencemessages if you need these use the re obdii tester tool or the obdii canX request command

39 Renault Twizy

391 Dashboard-Tuneslider

Add recuperation control to the dashboard

bull dashboard-tunesliderhtm

Details httpsdocsopenvehiclescomenlatestcomponentsovms_webserverdocsplugin-twizydashboard-tunesliderhtml

39 Renault Twizy 105

Open Vehicles

392 eDriver BMS Monitor

Status monitor for the Twizy custom eDriver BMS by Pascal Ripp

Version 20 by Michael Balzer ltdexterdexters-webdegt

This is a simple web page plugin to display the standard battery cell info along with the additional custom data providedby the eDriver BMS on one page

Additional custom data

bull Main state

bull Error state

bull BMS internal temperature

bull AUX relay state

bull Cell balancing states

Note these are read from their respective custom metrics xrtbms see Custom Metrics

Overall SOC voltage current and coulombenergy counters are also shown to simplify battery capacity and currentsensor calibration

Check out the eDriver BMS Manual for details or contact Pascal in case of questions

Installation

1 Install edrvmonhtm web plugin recommended setup

bull Type Page

bull Page usredrvmon

bull Label eDriver BMS Monitor

bull Menu Vehicle

bull Auth Cookie

106 Chapter 3 Plugins

Open Vehicles

History

bull V20 ndash Added cell balancing time totals + SOC amp voltage usecharge range

bull V10 ndash Initial release

393 Page-Command

only command options as UI

Version 02 Matthias Greiling ltmatthiasgreilingdegt

Details

This view only presents commands to OVMS While driving you can choose between different drive modes Thecoloured area indicates the active drive mode Activate an other mode by touching or clicking the grey bordered areaTo change again simply click or touch again the same or another ares Furthermore you can limit the speed online topredefined values The speed limit signs are common in germany and display kmh Just activate the sign you want tobe limited to - another touch will deactivates the limit of the chosen one

Installation

1 Install page-commandhtml web plugin recommended setup

bull Type Page

bull Page usrcommand

bull Label

bull Menu Main

bull Auth Cookie

39 Renault Twizy 107

Open Vehicles

History

bull V02 ndash Simplfy backgrounds icons of command row

bull V01 ndash Initial release

394 WifiConsole

Backend for WifiConsole hardware extension

bull WifiConsolejs

Details httpsgithubcomdexterbgWifiConsole

310 VW e-Up Mii Citigo

3101 ECUToolkit VW e-Up ECU Access

Library and web UI for diagnostics and configuration of the e-Up Mii Citigo ECUs

bull Library version 05 by Michael Balzer ltdexterdexters-webdegt

bull Web UI version 01 by Michael Balzer ltdexterdexters-webdegt

108 Chapter 3 Plugins

Open Vehicles

You will need OVMS firmware release 32016-226 or higher to be able to use this

The library is meant as a general tool to access the VW ECUs It provides means to simplify sending OBDUDScommands to ECUs by ID and to automate diagnostic session loginlogout It provides methods to set the workshopcode (WSC) do security authorization do scans and codings

The web UI allows to open multiple tools for different ECUs and saveload the current setup including the tool states

Feel free to improve and extend (and submit your results)

Warning

Warning Use at your own risk This ECU toolkit is based on reverse engineering I havenrsquot had access to anyofficial documentation Itrsquos only been used and tested on few vehicles chances are there will be issues with othervehicle configurations

Note If yoursquore interested in a fully featured VW ECU tool consider buying the excellent third party tools VCDS(httpswwwross-techcomvag-com) or OBDeleven (httpsobdelevencom) which fully support all VW vehiclesincluding of course the e-Up These tools also can decode most DTCs and provide detailed information on faultconditions

310 VW e-Up Mii Citigo 109

Open Vehicles

Installation

1 Save xvu-ecujs as storescriptslibxvu-ecujs

bull Add to storescriptsovmsmainjs

ndash xvu = ecu require(libxvu-ecu)

ndash or in case you already have the xvu namespace object just add the ecu part

bull Issue script reload or evaluate the require line

2 Install xvu-ecu-toolhtm web plugin recommended setup

bull Type Page

bull Page xvuecutoolkit

bull Label ECU Toolkit

bull Menu Vehicle

bull Auth Cookie

Usage

You can use the toolkit without ignition on if you just want to review some stored backup or dry run some coding tests

The web UI shows the list of known ECUs on the left side (or upper side on mobile devices) The list can be filteredto only show ECUs installed in the car by clicking the ldquordquo button this will need ignition on so the library can accessthe CAN gateway

Open a tool by selecting the ECU to investigate then clicking the tool button below the list To switch between toolsclick on the tool tab title To close a tool click the cross mark on the tool tabrsquos title

You can save the toolkit state (ie all open tools including their data) to a file on the OVMS SD card or store partitionLoading replaces the current toolkit state by the one loaded so discards any unsaved content

Click the menu box title to collapse or expand the box Loading will automatically collapse the menu box on mobiledevices

Enable the debug log messages to see which OBDUDS commands are performed The log will be shown in the panelfooter The read only mode inhibits OBDUDS commands doing PID changes DTC clearing or security accessesThey will still be logged so you can see what would be done

If you encounter issues send me a debug log

Scan tool

The Scan tool is considered to be safe as no write operations are involved

Scan results include the current hardware amp software versions the codings and DTCs so are useful as a backup forlater reference

To do a scan turn the ignition on select the ECU to scan and click the Scan button A new tab will open and thescan will start immediately Scans take from 5 - 15 seconds depending on the number of subsystems and other systemactivity The results will be shown in the tab

110 Chapter 3 Plugins

Open Vehicles

Coding tool

The Coding tool allows to change the ECU configuration ECUs may accept invalid codings that possibly can causehardware damage so be cautious ECUs will record all your write operations Even though the toolkit reuses the lastworkshop code found in the ECU by default there still will be a log entry carrying the date of the change

Use the full coding input field to copy amp paste codings for backups amp restores eg from a former scan result Afterpasting click outside the field to validate the coding and update the bits

Subsystem codings are included in the ECU coding other than in the scan result where they are shown at the respectivesubsystem You can paste amp write only the main coding the subsystem will then not be changed

Select a byte position to view and change the individual bits of that byte Only labels for bits known to work onthe VW e-Up models have been added up to now source of this is the german GoingElectric forum amp wiki (httpswwwgoingelectricde)

To submit a changed coding to the ECU click ldquoWriterdquo Most codings donrsquot need a security code so leave the fieldempty unless ldquoWriterdquo aborts with a security clearance error Security codes can be found in the forums and officialrepair manuals

Library API

Documentation on the API methods is in preparation

As this is currently an alpha release the API is work in progress and likely to change

If yoursquore interested in using whatrsquos considered stable now or possibly even contribute please read the source andcontact me

311 Installing Module Plugins

A module plugin normally consists of a single Javascript file that needs to be placed in the storescriptslibdirectory The plugin is then loaded by a require() call which can be done manually as needed or automaticallyon boot by adding it to the storescriptsovmsmainjs file

1 Menu Tools rarr Editor

2 Cancel the open dialog

3 Paste the plugin source into the editor

4 Save as rarr storescriptslib using the name as shown in the plugin documentation

5 Open rarr (one level up) rarr ovmsmainjs

6 Add the require() call as shown in the plugin documentation

7 Save

8 Reload JS Engine

The plugin is now installed and activated

Hint you can now try out the commands provided by the plugin directly from the editor Clear the editor fill in thecommand or Javascript snippet click Evaluate JS The output will be shown below the input field

To deactivate a plugin comment out the require() call by prefixing the line with and do another JS enginereload To remove a plugin remove the require() call and delete the file using vfs rm storescriptslib

311 Installing Module Plugins 111

Open Vehicles

312 Installing Web Plugins

A web plugin normally consists of a single HTML file Web plugins can be meant to render new pages or to hook intoan existing page They need an initial registration to work

1 Menu Config rarr Web Plugins

2 (add)

3 Set type and name as suggested in the plugin documentation

4 Save

5 Edit

6 Set attributes as suggested in the plugin documentation

7 Paste the plugin source into the content area

8 Save

The plugin is now installed and activated

Hint you can use the text editor (tools menu) to change or update an already installed web plugin Simply edit theplugin file in folder storeplugin directly the system will reload the plugin as soon as you save it

To deactivate a web plugin set the state to ldquooffrdquo To remove a plugin click rarr Save

112 Chapter 3 Plugins

CHAPTER 4

BMW i3 i3s

Vehicle Type BMWI3

This vehicle type supports the BMW i3 and i3s models All model years should be supported

The OVMS support was developed Jan 2021

It was developed against the authorrsquos 2018 120Ah i3s BEV I would welcome engagement from the owner of a REXtype to further develop metrics related to the REX engine Testing by drivers of LHD models as well as those withthe smaller batteries will also be helpful

As of this release this vehicle support is read-only and cannot send commands to the car

41 Support Overview

ldquotbardquo item are still on the to-do list and are not currently supported

113

Open Vehicles

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable OBD-II cable left-handed cable worked best in my RHD carGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (or any compatible antenna)SOC Display YesRange Display YesCabin Pre-heatcool Control tbaGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display tbaCharge Status Display YesCharge Interruption Alerts YesCharge Control tbaLockUnlock Vehicle tbaValet Mode Control NoOthers 12v battery voltagecurrent battery true SOC etc

42 WARNINGS

421 Alarm behaviour

As standard the i3 will sound the alarm if anything is left connected to the OBD-II port when the car is locked

A tool like Bimmercode will allow you to disable this Alternatively you will need to disconnect the OVMS unit beforelocking the car

A future version may add a command to allow you to disable this alarm directly from your OVMS shell

422 12V Battery drain

The i3 has a small 20Ah AGM 12v battery Whilst care has been taken to minimize OVMSrsquo power usage OVMScould eventually drain this battery if the car is left unplugged and locked OVMS will also send an alert if 12V dropsunder 12V alert threshold (See 12V Calibration section)

HOWEVER If you are going to leave the car for a fews days it is recommended to unplug OVMS

43 Car status

The car is accessible over the OBD-II port when it is running (ignition on) and for a short time (40 seconds or so) afterit is turned off or the car is ldquotweakedrdquo (lock button pushed connected-drive command received etc)

Unfortunately this means that when your car is standing or charging OVMS only has intermittent access to data fromthe car

By observation whilst the car is charging it wakes up now and then (seems to be every 30 minutes) So at those timeswe can update our SOC etc

114 Chapter 4 BMW i3 i3s

Open Vehicles

Metrics ldquoveawakerdquo tells you if the car is awake or not Metric ldquoxi3sagerdquo will tell you how many minutes have passedsince we last received data from the car

You may also refer to metric xi3spollermode as follows

Mode Meaning0 Car is asleep - no OBD-II data traffic1 Car OBD-II is awake - we are seeing data traffic2 Car is ready to drive or driving3 Car is charging

44 Custom metrics

Metric name Example value Descriptionxi3sage 5Min How long since we last got data from the carxi3spollermode 0 OBD-II polling mode as explained abovexi3vbpocvavg 40646V Main battery pack - average open-circuit voltagexi3vbpocvmax 4067V Main battery pack - highest open-circuit voltagexi3vbpocvmin 4063V Main battery pack - lowest open-circuit voltagexi3vbrangebc 245km Available range per trip computer (based on current driving mode and style)xi3vbrangecomfort 217km Available range if you use Comfort modexi3vbrangeecopro 245km Available range if you use EcoPro modexi3vbrangeecoproplus 247km Available range if you use EcoPro+ modexi3vbsocactual 85 Actual physical state-of-charge of the main battery packxi3vbsocactualhighlimit 937 Highest physical charge level permitted (shown as 100 SOC)xi3vbsocactuallowlimit 105 Minimum physical charge level permitted (shown as 0 SOC)xi3vcchargecablecapacity 0A Maximum power capacity of connected charge cable per the charging interfacexi3vcchargeledstate 0 Colour of the ldquoring lightrdquo on the charging interfacexi3vcchargeplugstatus Not connected Charging cable connectedxi3vccurrentdc 0A Power flowing on the DC side of the AC chargerxi3vccurrentdclimit 0100003A Limitxi3vccurrentdcmaxlimit 16A Maximum limitxi3vccurrentphase1 0A Power being drawn on AC phase 1xi3vccurrentphase2 0A Power being drawn on AC phase 2xi3vccurrentphase3 0A Power being drawn on AC phase 3xi3vcdcchargevoltage 0V Voltage seen on the DC charger inputxi3vcdccontactorstatus open DC contactor state (closed implies we are DC charging)xi3vcdccontrolsignals 0 DC charger control signals (always see 0)xi3vcdcinprogress no DC charging in progressxi3vcdcplugconnected no Is DC charger plug connected (doesnrsquot seem to work)xi3vcderatingreasons 0 Reasons why charging rate is deratedxi3vcerror 0 Charging error codesxi3vcfailsafetriggers 0 Failsafe trigger reasonsxi3vcinterruptionreasons 0 Charging interruption reasonsxi3vcpilotsignal 0A Charge rate pilot signal being received from EVSExi3vcreadytocharge no Are we ready to chargexi3vctempgatedriver 40degC Charger gatedrive mosfet temperaturexi3vcvoltagedc 84V Charger output DC voltage being seen (for AC charging not DC)xi3vcvoltagedclimit 420V Maximum permitted DC voltge

Continued on next page

44 Custom metrics 115

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxi3vcvoltagephase1 0V Voltage seen on AC charger input phase 1xi3vcvoltagephase2 0V Voltage seen on AC charger input phase 2xi3vcvoltagephase3 0V Voltage seen on AC charger input phase 3xi3vdchargeportdc no Is the charger port DC cover open (doesnrsquot seem to work)xi3veautorecirc no Ventilation is in ldquoauto-recirculaterdquo modexi3veobdtraffic no Are we seeing OBD-II frames from the carxi3vptripconsumption 127Whkm Average consumption for the current or most recent tripxi3vpwheel1_speed 0kmh Wheel 1 speedxi3vpwheel2_speed 0kmh Wheel 2 speedxi3vpwheel3_speed 0kmh Wheel 3 speedxi3vpwheel4_speed 0kmh Wheel 4 speedxi3vpwheel_speed 0kmh Average wheel speed

45 To be researched

Can we startstop charging

Can we pre-heat

Can we lockunlock the car

Can we disable the OBD-II alarm

Still looking for the trip regen kWh

Can we get the voltage state of each individual cells rather than just the battery min max average

116 Chapter 4 BMW i3 i3s

CHAPTER 5

DBC Based Vehicles

Vehicle Type DBC

The DBC based vehicle reads a specified DBC file describing CAN bus messages and produces vehicle metrics fromthat It is under development experimental and not generally available

51 Support Overview

Function Support StatusHardware This is vehicle specific The DBC vehicle module can be configured to use any or all of

the 3 CAN busesVehicle Cable Vehicle specificGSM Antenna Standard GSM antennaGPS Antenna Vehicle specific Standard OVMS GPS supportedSOC Display Yes if DBC maps itRange Display Yes if DBC maps itGPS Location Yes if DBC maps it otherwise OVMS GPSSpeed Display Yes if DBC maps itTemperature Display Yes if DBC maps itBMS v+t Display Not currently supportedTPMS Display Yes if DBC maps itCharge Status Display Yes if DBC maps itCharge InterruptionAlerts

Yes if DBC maps it

Charge Control Not supported by DBC format maybe by extensionCabin Pre-heatcoolControl

Not supported by DBC format maybe by extension

LockUnlock Vehicle Not supported by DBC format maybe by extensionValet Mode Control Not supported by DBC format maybe by extensionOthers None

117

Open Vehicles

52 Contents

521 DBC Introduction

DBC is a CAN data description file format introduced by Vector Informatik GmbH DBC files are text files so can becreated and edited using a simple text editor like the one built into the OVMS web UI

DBC files can be used to support vehicles that donrsquot have a dedicated native adaption yet This is done using thegeneric DBC vehicle type which can use DBC files to translate CAN data into metrics

This section tries to show you how to create and use a DBC specification on the OVMS Of course yoursquoll need to knowhow to decode your vehiclersquos CAN frames first You can use the OVMS RE (reverse engineering) toolkit to identifywhich messages are on the bus and which changes correlate to actions and status on the car

Therersquos also a very good general introduction to DBC from CSS Electronics including an explanatory video httpswwwcsselectronicscomscreenpagecan-dbc-file-database-introlanguageen

DBC files only specify the passive (reading) part they donrsquot provide a means to define transmissions If you need tosend frames to request certain information you can still use the OVMS DBC engine to decode the results (instead ofdoing the decoding in C++ code) So a DBC file can be used as a base for a real vehicle module To request OBD2data during development you can use the re obdii commands

Basic Example

Warning The DBC support is usable but considered to be an alpha release The way it works may change in thefuture

This example is taken from the Twizy which sends some primary BMS status data at CAN ID 0x155 (341) Note theTwizy module actually does not use DBC this is just an example how you would decode this message if using DBC

Message example 05 96 E7 54 6D 58 00 6F

bull Byte 0 charge current limit [A] scaled by 5 no offset 05rarr 25A

bull Bytes 1+2 momentary battery current [A] big endian lower 12 bits scaled by -025 offset +500 _6 E7 rarr5825A

bull Bytes 4+5 SOC [] big endian scaled by 00025 no offset 6D 58rarr 6998

These can be translated to metrics directly

bull Charge current limit vcclimit

bull Momentary battery current vbcurrent

bull Battery SOC vbsoc

Create DBC File

Copy amp paste the following into a new editor window

VERSION DBC Example 10

BS_ 500000 00

BO_ 341 BMS_1 8 Vector__XXX

(continues on next page)

118 Chapter 5 DBC Based Vehicles

Open Vehicles

(continued from previous page)

SG_ v_c_climit 7|80+ (50) [0|35] A Vector__XXXSG_ v_b_current 11|120+ (-025500) [-500|1000] A Vector__XXXSG_ v_b_soc 39|160+ (000250) [0|100] Vector__XXX

What does this mean

bull BS_ defines the bus speed (500 kbit in this example) and bit timings (unused)

bull BO_ defines the data object a CAN frame of length 8 with ID 341 (0x155) (ldquoBMS_1rdquo is just an arbitrary name)

bull SG_ lines define the signals (values) embedded in the object (see below)

bull Vector__XXX is just a placeholder for any senderreceiver (currently unused by the OVMS)

Signals are defined by their

bull Name (= metric name with replaced by _)

bull Start position (bit position) and bit length (7|8)

bull Endianness 0 = big endian (most significant byte first) 1 = little endian (least significant byte first) (Note theDBC format documentation is wrong on this)

bull Signedness + = unsigned - = signed

bull Scaling and offset (-025500) =gt real value = raw value -025 + 500

bull Minimummaximum [-500|1000] = valid real values are in the range -500 to 1000

bull Unit eg A (ignoredirrelevant defined by the metric)

The metric to set can be given as the name of the signal You may use the metric name directly on the OVMS but toconform to the DBC standard replace the dots by _

Bit positions are counted from byte 0 upwards by their significance regardless of the endianness The first messagebyte has bits 0 7 with bit 7 being the most significant bit of the byte The second byte has bits 8 15 with bit 15being the MSB and so on

[ 7 6 5 4 3 2 1 0 ] [ 15 14 13 12 11 10 9 8 ] [ 23 22 21 20 `----- Byte 0 ----acute `------- Byte 1 --------acute `----- Byte 2

For big endian values signal start bit positions are given for the most significant bit For little endian values the startposition is that of the least significant bit

Note On endianness ldquobig endianrdquo means a byte sequence of 0x12 0x34 decodes into 0x1234 (most significantbyte first) ldquolittle endianrdquo means the same byte sequence decodes into 0x3412 (least significant byte first) ldquoBigendianrdquo is the natural way of writing numbers ie with their most significant digit coming first ldquolittle endianrdquo isvice versa Endianness only applies to values of multiple bytes single byte values are always written naturally ldquobigendianrdquo

Use DBC File

Save the DBC example as storedbctwizy1dbc (the directory will be created by the editor)

Open the shell To see debug logs issue log level debug dbc-parser and log level debug v-dbc

Note the DBC parser currently isnrsquot graceful on errors a wrong DBC file may crash the module So you shouldonly enable automatic loading of DBC files on boot when yoursquore done developing and testing it

52 Contents 119

Open Vehicles

So letrsquos first try if the DBC engine can parse our file The dbc autoload command loads all DBC files from thestoredbc directory

OVMS dbc autoloadAuto-loading DBC filesD (238062) dbc-parser VERSION parsed as DBC Example 10D (238062) dbc-parser BU_ parsed 1 nodesD (238062) dbc-parser BO_ parsed message 341D (238072) dbc-parser SG_ parsed signal v_c_climitD (238072) dbc-parser SG_ parsed signal v_b_currentD (238082) dbc-parser SG_ parsed signal v_b_soc

Looks good dbc list can tell us some statistics

OVMS dbc listtwizy1 DBC Example 10 1 message(s) 3 signal(s) 56 coverage 1 lock(s)

The coverage tells us how much of our CAN data bits are covered by signal definitions

Now letrsquos load the file into the DBC vehicle

OVMS config set vehicle dbccan1 twizy1Parameter has been set

OVMS vehicle module NONEI (1459922) v-none Generic NONE vehicle module

OVMS vehicle module DBCI (249022) v-dbc Pure DBC vehicle moduleI (249022) v-dbc Registering can bus 1 as DBC twizy1

Nice Letrsquos simulate receiving our test frame and check the decoded metrics

OVMS can can1 rx standard 155 05 96 E7 54 6D 58 00 6FOVMS me li vbsocvbsoc 6998OVMS me li vbcurrentvbcurrent 5825AOVMS me li vcclimitvcclimit 25A

So the decoding apparently works

To configure DBC mode for autostart we now just need to set the DBC vehicle mode to be loaded on vehicle startupand to enable autoloading of the DBC files from storedbc You can do so either by using the user interface pageConfig rarr Autostart (check ldquoAutoload DBC filesrdquo and set the vehicle type to ldquoDBCrdquo) or from the shell by

OVMS config set auto dbc yesOVMS config set auto vehicletype DBC

Try a reboot to see if everything works

You can now add more objects and signals to your DBC file

Note During development of a DBC file yoursquoll need to reload the file frequently The DBC engine locks the currentlyused vehicle so yoursquoll need to unload the DBC vehicle (vehicle module NONE) then reload the DBC file (dbcautoload) then reactivate the DBC vehicle (vehicle module DBC)

120 Chapter 5 DBC Based Vehicles

CHAPTER 6

DEMO Vehicle

Vehicle Type DEMO

The demonstration vehicle can be used to verify module functionality but is mostly used for development purposesThe vehicle itself updates system metrics with simulated data It can respond to charge and other similar commands

61 Support Overview

Function Support StatusHardware Demonstration data only no vehicle connectionVehicle Cable None not required (other than power)GSM Antenna Standard GSM antennaGPS Antenna None not requiredSOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display YesBMS v+t Display Not currently supportedTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control YesCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle YesValet Mode Control YesOthers None

121

Open Vehicles

122 Chapter 6 DEMO Vehicle

CHAPTER 7

Fiat 500e

Vehicle Type FT5E

The Fiat 500e vehicle support will be documented here

71 Support Overview

Function Support StatusHardware tbaVehicle Cable tbaGSM Antenna tbaGPS Antenna tbaSOC Display tbaRange Display tbaGPS Location tbaSpeed Display tbaTemperature Display tbaBMS v+t Display tbaTPMS Display tbaCharge Status Display tbaCharge Interruption Alerts tbaCharge Control tbaCabin Pre-heatcool Control tbaLockUnlock Vehicle tbaValet Mode Control tbaOthers tba

123

Open Vehicles

124 Chapter 7 Fiat 500e

CHAPTER 8

Hyundai Ioniq vFL

Hyundai Ioniq Electric (28 kWh)

bull Vehicle Type HIONVFL

bull Log tag v-hyundaivfl

bull Namespace xhi

bull Maintainers Michael Balzer

bull Sponsors Henri Bachmann

bull Credits EVNotify

125

Open Vehicles

81 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display NoGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display PartialBMS v+t Display YesSOH Display YesTPMS Display NoCharge Status Display YesCharge Interruption Alerts YesCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

82 Custom Metrics

Metric name Example value Descriptionxhibsocbms 785 Internal BMS SOCxhicstate 128 Charge state flags

83 Debug Logs

To see all PID poll results in your log set log level verbose for component v-hyundaivfl

126 Chapter 8 Hyundai Ioniq vFL

CHAPTER 9

Jaguar IPace

Vehicle Type IPace

Support for Jaguar IPace is provided by this module (c) 2021 by Didier Ernotte

91 Support Overview

Function Support StatusHardwareVehicle CableGSM AntennaGPS AntennaSOC Display YesRange DisplayGPS Location (not yet)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display (not yet)Charge Interruption AlertsCharge ControlCabin Pre-heatcool ControlLockUnlock Vehicle NoValet Mode Control NoOthers

127

Open Vehicles

92 Custom Metrics

xji_v_bat_capacity_soh_min xji_v_bat_capacity_soh_max xji_v_bat_power_soh xji_v_bat_power_soh_minxji_v_bat_power_soh_max xji_v_bat_max_regen

128 Chapter 9 Jaguar IPace

CHAPTER 10

Kia e-Niro

Vehicle Type KN

The Kia e-Niro vehicle support will be documented here

101 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable 9658635 Kia OBD-II to DB9 Data Cable for OVMSGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display Yes (based on consumption of past 20 trips longer than 1km)GPS Location YesSpeed Display Not currently supportedTemperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control Not currently supportedCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle YesValet Mode Control Not currently supportedOthers ODO Not currently supported

129

Open Vehicles

102 OBD-II cable

The Kia e-Niro have one CAN-bus available on the OBD-II port D-can You can use the standard OBD-II to DB9cable from Fasttech

In case you want to build your own cable herersquos the pinout

J1962-M DB9-F Signal4 3 Chassis Power GND6 7 CAN-0H (C-can High)14 2 CAN-0L (C-can Low)16 9 +12V Vehicle Power

A simple approach is to buy an OBDII (J1962-M) pigtail and solder the DB9-F connector end appropriately

103 Configuration

TODO Configuration is quite similar to the Kia Soul so please check that out Please use the Web based configuration

104 Estimated Range

Currently there is no known way to get the estimated range directly from the car so the estimated range is calculatedby looking at the consumption from the last 20 trips that are longer than 1 km

105 12V battery drain

OVMS will eventually drain the 12V battery but steps have been taken to minimize the drain However if you aregoing to leave the car for a fews days it is recommended to unplug OVMS OVMS will send an alert if 12V dropsunder 12V alert threshold See 12V Calibration section

130 Chapter 10 Kia e-Niro

CHAPTER 11

Kia Soul EV

Vehicle Type KS

The Kia Soul EV vehicle support will be documented here

111 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable 9658635 Kia OBD-II to DB9 Data Cable for OVMSGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display Temperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control Not currently supportedCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle YesValet Mode Control Not currently supportedOthers

131

Open Vehicles

112 OBD-II cable

The Kia Soul EV have two different CAN-busses available on the OBD-II port C-can and M-can

C-can is the main can-bus and M-can is the multimedia bus The latter one is not necessary for OVMS but somemetrics are fetched from the M-bus and these metrics will be empty if you donrsquot have the proper cable The standardOBD-II to DB9 cable from Fasttech supports only C-can so make sure you buy the Kia Soul specific one

In case you want to build your own cable herersquos the pinout

J1962-M DB9-F Signal1 5 CAN-1H (M-can High)4 3 Chassis Power GND6 7 CAN-0H (C-can High)9 4 CAN-1L (M-can Low)14 2 CAN-0L (C-can Low)16 9 +12V Vehicle Power

A simple approach is to buy an OBDII (J1962-M) pigtail and solder the DB9-F connector end appropriately

113 Configuration

There are a few Kia Soul EV specific settings that you have to consider in order to get the most out of OVMS Theseare battery size real life ideal range remote command pincode and charge port remote control

114 Battery size

Up until the 2018 version of Kia Soul all models had a 27kWh battery The 2018-version have a 30kWh batteryOVMS is by default set up with 27000Wh but you can change this configuration to fit your car using this commandin the OVMS-shell

config set xks cap_act_kwh 27000

NB Even though it says cap_act_kwh the number must be in Wh

115 Real life ideal range

Even though the Kia Soul EV is equipped with a pretty good and conservative GOM most experienced drivers knowhow far the car can go on a charge This is what we call the ideal range You can set the ideal range in kilometersexperienced at 20 degrees celsius by using this command

config set xks maxrange 160

This setting is set to 160 km by default and matches the author driving a 2015 Kia Soul Classic in 20 degrees insouthern Norway Your mileage may vary so please set it accordingly

The ideal range as shown in the OVMS APP are then derived from this number multiplied by the state of charge andadjusted using a combination of the outside temperature and the battery temperature

132 Chapter 11 Kia Soul EV

Open Vehicles

116 Open charge port using key fob

By default OVMS listens for the the third button on the key fob and opens the charge port if Pressed If you donrsquotwant this behaviour you can disable it by using this command

config set xks remote_charge_port 0

117 Security pin code for remote commands

Remote commands like lock and unlock doors among others require a pin code This pin code can be set using theweb configuration or using this command

config set password pin 1234

Please set this pin as soon as possible

118 Soul specific metrics

NB Not all metrics are correct or tested properly This is a work in progress

There are a lot of extra metrics from the Kia Soul Herersquos the current ones

Metric Descriptionxksbcellvoltmax The highest cell voltagexksbcellvoltmaxno The cell number with the highest voltagexksbcellvoltmin The lowest cell voltagexksbcellvoltminno The cell number with the lowest voltagexksbcelldetmax The highest registered cell deterioration in percentxksbcelldetmaxno The cell with the highest registered deteriorationxksbcelldetmin The lowest registered cell deterioration in percentxksbcelldetminno The cell with the lowest registered deteriorationxksbmintemp The lowest temperature in the batteryxksbmaxtemp The highest temperature in the batteryxksbinlettemp The air temperature at the air inlet to the batteryxksbheat1temp The temperature of the battery heater 1xksbheat2temp The temperature of the battery heater 2xksbbmssoc The internal state of charge from BMSxkscpower Charge power in kWxkscspeed The charge speed in kilometer per hourxksldcoutvolt The voltage out of the low voltage DC converterxksldcinvolt The voltage into the low voltage DC converterxksldcoutamps The power drawn from the low voltage DC converterxksldctemp The temperature of the LDCxksobcpilotduty The duty cycle of the pilot signalxkselowbeam Low beam onoffxksehighbeam High beam onoffxkseinsidetemp Actual cabin temperaturexkseclimatetemp Climate temperature settingxkseclimatedriveronly Climate is set to driver onlyxkseclimateresirc Climate is set to recirculate

Continued on next page

116 Open charge port using key fob 133

Open Vehicles

Table 1 ndash continued from previous pageMetric Descriptionxkseclimateauto Climate is set to autoxkseclimateac Air condition onoffxkseclimatefanspeed Climate fan speedxkseclimatemode Climate modexksepreheattimer1enabled Preheat timer 1 enableddisabledxksepreheattimer2enabled Preheat timer 2 enableddisabledxksepreheating Preheating onoffxkseposdisttodest Distance to destination (nav unit)xkseposarrivalhour Arrival time hour part (nav unit)xkseposarrivalminute Arrival time minute part(nav unit)xkseposstreet Current street Or Next streetxksvseatbeltdriver Seat belt sensorxksvseatbeltpassenger Seat belt sensorxksvseatbeltbackright Seat belt sensorxksvseatbeltbackleft Seat belt sensorxksvtractioncontrol Traction control onoffxksvcruisecontrolenabled Cruise control enableddisabledxksvemergencylights Emergency lights enableddisabledxksvsteeringmode Steering mode Sport comfort normalxksvpowerusage Power usage of the carxksvtripconsumptionkWh100km Battery consumption for current tripxksvtripconsumptionkmkWh Battery consumption for current trip

Note that some metrics are polled at different rates than others and some metrics are not available when car is off Thismeans that after a restart of the OVMS some metrics will be missing until the car is turned on and maybe driven forfew minutes

Climate and navigation-metrics are fetched from navigation unit and needs the Kia Soul compatible OBDII-cable

119 Soul specific shell commands

There are a few shell commands made for the Kia Soul Some are read only others can enable functions and some areused to write directly to a ECU and must therefore be used with caution

1191 Read only commands

xks trip

Returns info about the last trip from you put the car in drive (D or B) and til you parked the car

xks tpms

Shows the tire pressures

xks aux

Prints out the voltage level of the auxiliary battery

xks vin

134 Chapter 11 Kia Soul EV

Open Vehicles

Prints out some more information taken from the cars VIN-number Not complete

1192 Active Commands

xks trunk ltpin codegt

Opens up the trunk

xks chargeport ltpin codegt

Opens up the charge port

xks ParkBreakService ltonoffgt

Not yet working

xks IGN1 ltonoffgtltpingt

Turn on or off IGN1-relay Can be used to wake up part of the car

xks IGN2 ltonoffgtltpingt

Turn on or off IGN2-relay Can be used to wake up part of the car

xks ACC ltonoffgtltpingt

Turn on or off ACC-relay Can be used to wake up part of the car

xks START ltonoffgtltpingt

Turn on or off START-relay Can be used to wake up part of the car

xks headlightdelay ltonoffgt

Turn onoff the ldquofollow me homerdquo head light delay function

xks onetouchturnsignal lt0=Off 1=3 blinks 2=5 blinks 3=7 blinksgt

Configure one touch turn signal settings

xks autodoorunlock lt1=Off 2=On vehicle off 3=On shift to P 4=On driver doorunlockgt

Configure auto door unlock settings

xks autodoorlock lt0=Off 1=On speed 2=On shiftgt

Configure auto door unlock settings

119 Soul specific shell commands 135

Open Vehicles

1193 ECU-write commands

These commands are for the extra playful people Use with caution

xks sjb ltb1gtltb2gtltb3gt

Send command to smart junction box

xks bcm ltb1gtltb2gtltb3gt

Send command to body control module

1110 12V battery drain

OVMS will eventually drain the 12V battery but steps have been taken to minimize the drain However if you aregoing to leave the car for a fews days it is recommended to unplug OVMS

136 Chapter 11 Kia Soul EV

CHAPTER 12

Maxus eDeliver3

Vehicle Type MED3

The Maxus eDeliver3 will be documented here

121 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display NoTemperature Display Yes (External Temp and Battery)BMS v+t Display NoTPMS Display NoCharge Status Display NoCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

137

Open Vehicles

138 Chapter 12 Maxus eDeliver3

CHAPTER 13

Mercedes-Benz B250E W242

Vehicle Type SE

The Mercedes-Benz B-Klasse Electric Drive will be documented here

131 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display NoRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display NoBMS v+t Display NoTPMS Display NoCharge Status Display NoCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

139

Open Vehicles

132 Contents

1321 Standard Metrics

Metric name Notesms_v_mot_rpmms_v_env_throttle Resolution of 04 ms_v_pos_speed Resolution of 01 kmhms_v_pos_odometerResolution of 01 kmms_v_bat_12v_voltageResolution of 01 Vms_v_bat_power Car reports percents so the kW is just calculated by multiplying by 132 kW Negative side is

saturated to -50 kW This is just guess workms_v_bat_range_estms_v_bat_consumptionInstantious consumption Whkmms_v_tpms__pms_v_env_cabinsetpointThere are two figures left and right Using just one for now

1322 Custom Metrics

Metric name Example value Descriptionxmbvdisplaytripreset 27332km Dashbord Trip value since Resetxmbvdisplaytripstart 175km Dashbord Trip value since Start (today)xmbvdisplayconsumptionstart 259 kWh Dashbord Trip consumption since Start (today)xmbvdisplayaccel 89 Eco score on acceleration over last 6 hoursxmbvdisplayconst 18 Eco score on constant driving over last 6 hoursxmbvdisplaycoast 100 Eco score on coasting over last 6 hoursxmbvdisplayecoscore 69 Eco score shown on dashboard over last 6 hoursxmbvfl_speed 3783 kmh Front Left wheel speedxmbvfr_speed 3785 kmh Front Right wheel speedxmbvrl_speed 3780 kmh Rear Left wheel speedxmbvrr_speed 3782 kmh Rear Right wheel speed

140 Chapter 13 Mercedes-Benz B250E W242

CHAPTER 14

MG EV

Vehicle Types MG EV (UKEU) amp MG EV (TH)

These vehicle types support the MG ZS EV (2019-) MG5 is not yet supported in this build

141 Variants

MG ZS EVs sold in different countries seem to possess different behaviours This is why we have developed 2 differentvehicle types to support the different requirements

1411 Known Countries

Coun-try

Zombiemode

Requires GWM authenti-cation

Poll BCM causesalarm

Suggested vehicle type touse

UKEU Y N Y UKEUThai-land

N Y N TH

Aus-tralia

N N N TH

Zombie mode is when the gateway module (GWM) enters the locked state and no PIDs can be accessed This happens for UKEU cars when

1 Charger is plugged in without power car is locked and goes to sleep

2 Charger is then powered on and car starts charging

GWM authentication is required for Thai cars as GWM will be locked and no PIDs can be accessed (simiarly toZombie mode but this happens all the time rather than just during the above scenario) Note GWM authenticationdoes not work as a mitigation for UKEUrsquos Zombie mode

When the BCM is polled UKEU carsrsquo alarm (horn) can go off so this is disabled in the UKEU code

141

Open Vehicles

1412 Other Countries

For cars from other countries to decide which vehicle type you should use start off by trying the MG EV (TH) typefirst because Zombie mode mitigation has its side effects (see module notes below) and polling the BCM allows theOVMS to get more data from the car

You can follow these steps to see which variant may be suitable for your car

1 Select MG EV (TH) and use the car as you would normally Keep an eye on shell for log prints to see ifany problems occur

2 If the alarm goes off sometimes (like when doors are locked using remote) try switch to MG EV (UKEU)

3 If you do not get any alarm try put the car into Zombie mode

4 If OVMS is unable to get data (like no charging details appear on the app) try switch to MG EV (UKEU)

142 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 2019-Vehicle Cable Right hand OBDII cable (RHD) Left hand OBDII cable (LHD)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (or any compatible antenna)SOC Display YesRange Display Yes (BMS calculated and WLTP range from SoC)Cabin Pre-heatcool Control NoGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control NoLockUnlock Vehicle NoValet Mode Control NoOthers Daytime Running Light Control

143 Shell Commands

softver Get software version of ECUsdrl [on | off] Turn onoff daytime running lightsdrln [on | off] Turn onoff daytime running lights without doing BCM authentication first (for de-

bugging purposes)auth [all | gwm |bcm]

Authenticate with specified ECU lsquoauth allrsquo will authenticate GWM then BCM

142 Chapter 14 MG EV

Open Vehicles

144 Module notes

The code for each vehicle type has these behaviours

Vehicle type Zombie mode mitigation GWM authentication Poll BCMUKEU Y N NTH N Y Y

The MG EV module now monitors (and automatically calibrates) the 12V status and will automatically start pollingthe car for data when the 12V battery voltage is equal to or greater than 129V When it is below 129V it willautomatically stop polling (after a 50s delay) to not drain the 12V battery

Poll states

0 Lis-tenOnly

the OVMS module is quiet and stops sending polls

1 Charg-ing

the OVMS module sends charging specific queries

2 Driving the OVMS module sends driving specific queries3 Backup the OVMS module cannot get data from the car when it is charging so just retries SoC queries

This is unused in TH code

1441 UKEU spec

The car is accessible over the OBD port when it is running (ignition on) and for around 40 seconds after it is turnedoff or the car is ldquotweakedrdquo (lock button pushed etc)

The OBD port may be kept awake by using the ldquotester presentrdquo message to the gateway ECU This keeps a lot ofsystems awake and draws roughly 5A on the 12V bus so itrsquos not a good idea to do

The Gateway (GW GWM) is the keeper of all the data of the car and will enter a locked state when it is woken by thecar starting charging and the car is locked This we have called ldquoZombie Moderdquo and we have developed an overridefor this

This override however causes a few strange things to happen

bull If Zombie mode override is active the car will not unlock the charge cable To fix this dusrupt the chargeand wait 50s for OVMS to go back to sleep and the cable should release (or unplug OVMS)

bull Zombie mode override resets the ldquoAccumulated Total Triprdquo on the Cluster

bull Zombie mode override sets the gearshift LEDs switch on

145 Development notes

Developers welcome Follow the developerrsquos guide on httpswwwopenvehiclescomdevelopers to get started Joinour slack group (see below) to discuss the nerdy details

146 Community channels

Forum httpswwwmgevscom

144 Module notes 143

Open Vehicles

Slack httpsmgevhackersslackcom

144 Chapter 14 MG EV

CHAPTER 15

Mitsubishi Trio

Vehicle Type MI

This should be used to support the Mitsubishi i-Miev (Citroen C-Zero Peugeot iOn) vehicles

151 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) moduleVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display NoBMS v+t Display YesTPMS Display Not currently supportedCharge Status Display YesCharge Interruption Alerts YesCharge Control NoCabin Pre-heatcool Control Not currently supportedLockUnlock Vehicle Not currently supportedValet Mode Control Not currently supportedOthers

145

Open Vehicles

152 Trio specific metrics

NB Not all metrics are correct or tested properly This is a work in progress

Metric Descriptionxmibpowermin The battery minimum power usagexmibpowermax The battery maximum power usagexmielowbeam Low beam light statusxmiehighbeam High beam light statusxmiefrontfog Front fog light statusxmierearfog Rear fog light statusxmierightblinker Right blinker statusxmieleftblinker Left blinker statusxmiewarninglight Warning light statusxmickwhdc Charge energy on DC side in kWhxmickwhac Charge energy on AC side in kWhxmicefficiency Charge efficiency (DCAC)xmicpowerac Charge power on AC side in kWxmicpowerdc Charge power on DC side in kWxmictime Charge time (hmmss)xmicsocstart Charge start soc in xmicsocstop Charge stop soc in xmieheatingamp Heating energy usage in Axmieheatingwatt Heating energy usage in Wxmieheatingtempreturn Heater return water temperaturexmieheatingtempflow Heater flow water temperaturexmieacamp AC energy usage in Axmieacwatt AC energy usage in Wxmietrippark Trip start odometer in kmxmietripparkenergyused Energy used in kWhxmietripparkenergyrecuperated Recuperated energy in kWhxmietripparkheatingkwh Heater energy usage on trip in kWhxmietripparkackwh AC energy usage on trip in kWhxmietripparksocstart Trip start socxmietripparksocstop Trip stop socxmietripcharge Trip start odometer in km since chargexmietripchargeenergyused Energy used in kWh since chargexmietripchargeenergyrecuperated Recupe energy in kWh since chargexmietripchargeheatingkwh Heating usage in kWh since chargexmietripchargeackwh AC energy usage in kWh since chargexmietripchargesocstart Trip start soc since chargexmietripchargesocstop Trip stop soc since charge

Note that some metrics are polled at different rates than others and some metrics are not available when car is off Thismeans that after a restart of the OVMS some metrics will be missing until the car is turned on and maybe driven forfew minutes

146 Chapter 15 Mitsubishi Trio

Open Vehicles

153 Custom Commands

1531 Read only commands

xmi trip

Returns info about the last trip from you start the car with key

xmi tripc

Returns info about the trip since last charge

xmi aux

Prints out the voltage level of the auxiliary battery

xmi vin

Prints out some more information taken from the cars VIN-number

154 Trio Regen Brake Light Hack

1541 Parts required

bull 1x DA26 Sub-D 26HD Plug amp housing Note housings for Sub-D 15 fit for 26HD eg Assmann-WSW-A-HDS-26-LL-Z Encitech-DPPK15-BK-K-D-SUB-Gehaeuse

bull 1x 12V Universal Car Relay + Socket eg Song-Chuan-896H-1CH-C1-12V-DC-Kfz-Relais GoodSky-Relaissockel-1-St-GRL-CS3770

bull 1x 1 Channel 12V Relay Module With Optocoupler Isolation 12V 1 channel relay module with OptocouplerIsolation

Car wire-tap connectors car crimp connectors 05 mm2 wires zipties shrink-on tube tools

Note if you already use the switched 12V output of the OVMS for something different you can use one of the freeEGPIO outputs That requires additionally routing an EGPIO line to the DA26 connector at the expansion slot (egusing a jumper) and using a relay module (2b relay shield) with separate power input instead of the standard carrelay

I use 2b (relay shield) variant Be aware the MAX71317 outputs are open drain so you need a pull up resistor to eg+33 According to the data sheet the current should stay below 6 mA

Inside OVMS Box Connect JP1 Pin10 (GEP7) to Pin12 (EGPIO_8) with jumper

In DA26 connector

pin 24(+33) ----- [ 680 Ohms ] ---+--- [ Relay board IN ]|

pin 21 (EGPIO_8)pin 9 ----- [Relay board DC+]pin 8 ----- [Relay board DC-][Relay board COM] ----- Brake pedal switch one side[Relay board NO] ----- Brake pedal switch other side

153 Custom Commands 147

Open Vehicles

1542 Configuration

See OVMS web user interface menu Trio rarr Brake Light

Set the port as necessary and the checkbox to enable the brakelight

For monitoring and fine tuning use the bdquoregenmonldquo web plugin httpsgithubcomopenvehiclesOpen-Vehicle-Monitoring-System-3blobmastervehicleOVMSV3componentsovms_webserverdevregenmonhtm

148 Chapter 15 Mitsubishi Trio

Open Vehicles

154 Trio Regen Brake Light Hack 149

Open Vehicles

150 Chapter 15 Mitsubishi Trio

CHAPTER 16

Nissan Leafe-NV200

Vehicle Type NL

This vehicle type supports the Nissan Leaf (24kWh amp 30kWh) and Nissan e-NV200 (24kWh amp 40kWh)

161 Support Overview

1611 Hardware

Item Support StatusModule Any OVMS v3 (or later) module Vehicle support 2011-2017 (24kWh amp 30kWh LEAF 24kWh amp

40KWh e-Nv200 amp custom battery eg Muxsan)VehicleCable

1779000 Nissan Leaf OBD-II to DB9 Data Cable for OVMS

GSM An-tenna

1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)

GPS An-tenna

1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)

1612 Controls

Function Support StatusCharge Control Start and stop chargeCabin Pre-heatcool Control Yes1 (see info below)LockUnlock Vehicle Yes3 (see info below)Valet Mode Control Not currently supported

1 OVMS currently supports 2011-2017 Nissan LEAF and all models of Nissan e-NV2003 LockUnlock will work if CAR can bus is awake this can be activated by turning on AC

151

Open Vehicles

1613 Additional Features

Fea-ture

Description

BMSCellMon-itor

Allows to monitor individual battery cells in a configurable chart Can be accessed from web user interfaceaccessible over WiFi

ChargetoLimit

Allows to automatically stop the charge when target SOC (state of charge) andor range is reached Allparameters can be controlled trough metrics or web user interface Meanwhile Range and SOC can becontrolled from the app as well by adjusting fields 10 (SOC) and 11 (range) in feature section accessibletrough app settings

1614 Metrics

Item Support StatusSOC Yes (by default based on GIDS)4

Range Yes (by default based on GIDS)GPS Location Yes (from modem module GPS)Speed Yes (from vehicle speed PID)Cabin Temperature Yes (from vehicle temperature PIDs)Ambient Temperature Yes (from vehicle temperature PIDs)SetPoint Temperature Yes (from vehicle hvac PIDs)2

HVAC Fan Speed Yes (from vehicle hvac PIDs)2

HVAC HeatingCooling Status Yes (from vehicle hvac PIDs)2

HVAC On Status Yes (from vehicle hvac PIDs)2

HVAC Temperature Setpoint Yes (from vehicle hvac PIDs)2

HVAC Ventilation Mode Yes (from vehicle hvac PIDs)2

BMS v+t YesTPMS Yes (If hardware available)Charge Status YesCharge Interruption Alerts Yes

162 Remote Climate Control

1621 2014-2022 e-NV200 models

OVMS remote climate support will lsquojust workrsquo on e-Nv200 VisiaAcenta which donrsquot have a Nissan satnav headunitFor Tekna models which are fitted with a Nissan satnav headunit follow the instructions below for a 2013-2016 LEAFto unplug the TCU

IMPORTANT for remote climate to work on the e-NV200 the model year in OVMS should be set to 2015 regardlessof the the actual model year of the vehicle CAN writing also needs to be enabled

The model year can be set in the web interface or via the command

4 ZE0 (2011-2013) vehicles are required to choose SoC display from ldquorelative to fixed valuerdquo ldquodashboard displayrdquo SoC method does not workwith these vehicles

2 Some HVAC Status Items have been only verified with 2013-2016 MY cars and will only work if the year is set in configuraiton Also HVACneeds to be in ON position before powering down the vehicle for the metrics to work during pre-heat

152 Chapter 16 Nissan Leafe-NV200

Open Vehicles

config set xnl modelyear 2015

1622 2011-2012 LEAF models (ZE0)

Gen1 LEAFs (ZE0 2011-2012) require a hardware modification to enable remote climate control if the vehicle is notplugged in and charging If you are ok with this you donrsquot need to do anything further

If you want to to enable remote climate control once the charge has finished or if the vehicle is not plugged in youneed to do the following hardware modification A cable wired to the pin 11 of Nissan TCU (Telematics Control Unit)needs to receive +12V so that ldquoEV System Activation Request Signalrdquo can be generated which in turn allows to triggerclimate control independently This can be achieved by wiring the pin 18 (Ext 12V) from the OVMS DA26 socket tothe cable going to pin 11 of the TCU by using a standard single conductor wire The connection on the OVMS DA26side can be made by using dedicated DA26 connector or a standard round 1mm jumper cable Herersquos how to wire itup

Meanwhile on the TCU side the cable can be soldered or spliced in to by using a connector of your choice Whendone the original TCU can be left unplugged See this page for additional pictures

162 Remote Climate Control 153

Open Vehicles

If you have a ldquosmartrdquo EVSE (or one connected to a ldquosmartrdquo outlet you can sometimes wake up the EV system byturning it off then back on This obviously only helps if your vehicle is plugged in but may be useful for some users

1623 2013-2016 LEAF models (AZE0-01)

To use OVMS to activate remote climate the Nissan TCU (Telematics Control Unit) module must be unplugged iffitted eg satnav headunit (only on Acenta and Tekna models) The TCU is located behind the glovebox on LHD carsor on the right hand side of the drivers foot well on RHD cars The large white plug on the rear of the TCU should beunplugged push down tab in the middle and pull to unplug see video for RHD cars and this page for LHD cars

Note Unplugging the TCU will disable Nissan EV connect CARWINGS features eg Nissan mobile app All othercar functions will not be effected eg GPS maps radio Bluetooth microphone all work just the same as beforeOVMS can be used to more than substitute the loss of Nissan Connect features The TCU can be plugged back in atany point in the future if required

OVMS remote climate support will lsquojust workrsquo on LEAF Visia models and VisiaAcenta e-NV200 since these modelsdo not have a TCU fitted In the US these base models are called S

Note If you prefer not to unplug the Nissan TCU all OVMS functions appart from remote climate will function justfine alongside the Nissan TCU

1624 2016-2017 LEAF models (AZE0-2)

Remote climate control will only work when plugged in and actively charging on LEAF 2016-2017 models Thisis because in 2016 Nissan moved the TCU from the EV CAN bus to the CAR CAN bus

Set the model year as follows and if necessary configure 30 kWh model

config set xnl modelyear 2016

or

154 Chapter 16 Nissan Leafe-NV200

Open Vehicles

config set xnl modelyear 2017

Note in latest OVMS fimware version model year and battery size can be set via the web config interface

1625 2018+ models (ZE1)

2018+ 4062kWh LEAF is not yet supported Please get in touch if your interested in helping to add support Relevant2018 CANbus messages have already been decoded and documented see MyNissanLEAF thread

1626 Specific battery configs

For models with a 30 kWhr battery pack set the capacity manually with

config set xnl maxGids 356 config set xnl newCarAh 79

For models with a 40 kWhr battery pack set the capacity manually with

config set xnl maxGids 502 config set xnl newCarAh 115

For models with a 62 kWhr battery pack set the capacity manually with

config set xnl maxGids 775 config set xnl newCarAh 176

Note In latest OVMS firmware version model year and battery size can be set via the web config interface This iseasier and also the preferred method

Note 2 OVMS fully supports battery upgraded LEAFs just set the capacity according to what battery is currentlyinstalled

163 Range Calculation

The OVMS uses two configuration options to calculate remaining range whPerGid (default 80Whgid) and km-PerKWh (default 71kmkWh) The range calculation is based on the remaining gids reported by the LBC and atthe moment does not hold 5 in reserve like LeafSpy Feedback on this calculation is welcomed

164 Resources

bull Nissan LEAF support added by Tom Parker see his wiki for lots of documentation and resources Some info isoutdated eg climate control now turns off automatically

bull Nissan LEAF features are being added by Jaunius Kapkan see his github profile to track the progress

bull MyNissanLEAF thread for Nissan CANbus decoding discussion

bull Database files (DBC) for ZE0 and AZE0 Leaf can be found here Github LEAF Canbus database files

Assistance is appreciated as I havenrsquot had time to try to override the TCU using the OVMS or find an alternativesolution to prevent the TCU overriding the messages while still allowing the hands free microphone to work

163 Range Calculation 155

Open Vehicles

156 Chapter 16 Nissan Leafe-NV200

CHAPTER 17

OBDII Vehicles

Vehicle Type O2

Support for generic OBDII is provided by this module

157

Open Vehicles

171 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support Not widely tested but should be all that

support OBDII standard PIDs over CAN busVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display Yes (based on fuel level PID)Range Display NoGPS Location Yes (from modem module GPS)Speed Display Yes (from vehicle speed PID)Temperature Dis-play

Yes (from vehicle temperature PIDs)

BMS v+t Display NoTPMS Display NoCharge Status Dis-play

No

Charge Interrup-tion Alerts

No

Charge Control NoCabin Pre-heatcool Control

No

LockUnlockVehicle

No

Valet Mode Con-trol

No

Others VIN and RPMs should be available

158 Chapter 17 OBDII Vehicles

CHAPTER 18

Renault Twizy

Vehicle Type RT

159

Open Vehicles

181 Support Overview

Function Support StatusHardware No specific requirements (except for regen brake light

control see below)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right

or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any

compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or

any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display YesBMS v+t Display YesTPMS Display NoCharge Status Display YesCharge Interruption Alerts YesCharge Control Current limit stop SOCrange limitCabin Pre-heatcool Control NoLockUnlock Vehicle Mapped to dynamic speed lockValet Mode Control Mapped to odometer based speed lockOthers

bull Battery amp motor power amp energy monitoringbull Battery health amp capacitybull SEVCON monitoring amp tuning (Note tuning

only SC firmware lt= 07120002 ~072016)bull Kickdownbull Auto power adjustbull Regen brake lightbull Extended trip amp GPS logging

Note regarding the Twizy V3 works very similar to V2 All telemetry data tables and tuning profiles are fullycompatible and the commands are very similar Therefore the basic descriptions and background info from the V2manual are valid for V3 as well

bull V2 FAQ (english)

bull V2 FAQ (german)

bull V2 documents directory

bull V2 user manual (PDF)

182 Hints on V3 commands vs V2

bull V3 commands need to be in lower case

bull When accessing via USB terminal first issue enable (login)

bull V3 commands are similar to V2 commands just structured slightly different

160 Chapter 18 Renault Twizy

Open Vehicles

bull Try help and xrt Twizy commands are subcommands of xrt

bull TAB only works via USB SSH Shortcuts can be used generally eg mo t instead of module tasks

bull A usage info is shown if a command syntax is wrong or incomplete

183 Contents

1831 Configuration

The Twizy configuration is stored in the OVMS config parameter (section) xrt To list the current values issue

config list xrt

For reference the following table includes the equivalent OVMS V2 feature or parameter number amp bit value whereapplicable You may use the parameter amp feature editors on the App (values are mapped) the commands have beenmerged into the config command in V3

183 Contents 161

Open Vehicles

Config instancename

Examplevalue

V2FP

Description

autopower yes F158 Bool SEVCON automatic power level adjustment (Default yes)autoreset yes F152 Bool SEVCON reset on error (Default yes)aux_charger_port 0 ndash EGPIO port to control auxiliary charger (Default 0 = disabled)aux_fan_port 0 ndash EGPIO port to control auxiliary charger fan (Default 0 = disabled)canwrite yes F151 Bool CAN write enabled (Default no)cap_act_prc 822288 F13 Battery actual capacity level [] (Default 1000)cap_nom_ah 108 ndash Battery nominal capacity [Ah] (Default 1080)chargelevel 0 F7 Charge power level [1-7] (Default 0=unlimited)chargemode 0 F6 Charge mode 0=notify 1=stop at sufficient SOCrange (Default 0)console no F1516 -unused- (reserved for possible V3 SimpleConsole presence)dtc_autoreset no ndash Reset DTC statistics on every drivecharge start (Default no)gpslogint 5 (F8) Seconds between RT-GPS-Log entries while driving (Default 0 =

disabled)kd_compzero 120 F2 Kickdown pedal compensation (Default 120)kd_threshold 35 F1 Kickdown threshold (Default 35)kickdown yes F154 Bool SEVCON automatic kickdown (Default yes)lock_on 6 ndash Speed limit [kph] to engage lock mode at (Default undefined = off)maxrange 55 F12 Maximum ideal range at 20 degC [km] (Default 80)motor_rpm_rated 2050 ndash Powermap V3 control rated speed [RPM] (Default 0 = V2)mo-tor_trq_breakdown

210375 ndash Powermap V3 control breakdown torque [Nm] (Default 0 = V2)

profileNN XaZwt5ehZQ (P16-21)

Tuning profile NN [NN=01 99] base64 code

profileNNlabel PWR ndash button labelprofileNNtitle Power ndash titleprofile_buttons 0123 ndash Tuning drivemode button configurationprofile_cfgmode 2 ndash Tuning profile last loaded in config (pre-op) modeprofile_user 2 P15 Tuning profile last loaded in user (op) modesuffrange 0 F11 Sufficient range [km] (Default 0=disabled)suffsoc 80 F10 Sufficient SOC [] (Default 0=disabled)type ndash ndash Twizy custom SEVCONGearbox type [SC80GB45SC45GB80]

(Default - = auto detect)valet_on 123456 ndash Odometer limit [km] to engage valet mode at (Default undefined =

off)

1832 Custom Metrics

Metric name Example value Descriptioncocan1nd1emcycode SEVCON emergency codecocan1nd1emcytype SEVCON emergendy typecocan1nd1state Operational SEVCON state (preopop)xrtbusocmax 7052 Current tripcharge pack SOC maxxrtbusocmin 508 Current tripcharge pack SOC minxrtbutempmax 20degC Current tripcharge pack temp maxxrtbutempmin 181429degC Current tripcharge pack temp minxrtbuvoltmax 55V Current tripcharge pack volt maxxrtbuvoltmin 502V Current tripcharge pack volt min

Continued on next page

162 Chapter 18 Renault Twizy

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxrtbmsbalancing 248101314 Custom BMS cell balancing statusxrtbmserror 0 Custom BMS error statusxrtbmsstate1 4 Custom BMS main statexrtbmsstate2 1 Custom BMS auxiliary statexrtbmstemp 52degC Custom BMS internal temperaturexrtbmstype 1 Custom BMS type (0=VirtualBMS 1=eDriver BMS 7=Standard)xrtcfgapplied yes Tuning working set has been applied to SEVCONxrtcfgbase 2 Tuning base profile (preop mode params)xrtcfgprofile 144110111182 Tuning profile paramsxrtcfgtype Twizy80 Tuning vehicle typexrtcfgunsaved yes Tuning working set has unsaved changesxrtcfguser 2 Tuning userlive profile (op mode params)xrtcfgws 0 Tuning profile last loaded into working setxrticuract 0A SC monitor motor current levelxrtifrqoutput 0 SC monitor motor output frequencyxrtifrqslip 0 SC monitor motor slip frequencyxrtipwract 0kW SC monitor motor power levelxrtitrqact 0 SC monitor motor torque levelxrtitrqdemand 0 SC monitor motor torque demandxrtitrqlimit 0 SC monitor motor torque limitxrtivltact 0V SC monitor output voltage level (motor)xrtivltbat 0 SC monitor input voltage level (battery)xrtivltcap 0A SC monitor capacitor voltage levelxrtivltmod 0 SC monitor motor modulation factorxrtmversion 124 Sep 17 2019 OVMS Twizy component versionxrtpstatsaccdist 06267km Power stats accelerating distancexrtpstatsaccrecd 130133e-05kWh Power stats accelerating energy recoveredxrtpstatsaccspdavg 27kmhs Power stats accelerating speed averagexrtpstatsaccused 017692kWh Power stats accelerating energy usedxrtpstatscstdist 05331km Power stats coasting distancexrtpstatscstrecd 423289e-05kWh Power stats coasting energy recoveredxrtpstatscstspdavg 2618kmh Power stats coasting speed averagexrtpstatscstused 009703kWh Power stats coasting energy usedxrtpstatsdecdist 05436km Power stats decelerating distancexrtpstatsdecrecd 00140886kWh Power stats decelerating energy recoveredxrtpstatsdecspdavg 26kmhs Power stats decelerating speed averagexrtpstatsdecused 00379027kWh Power stats decelerating energy usedxrtpstatsldndist 02km Power stats downwards distancexrtpstatsldnhsum 3m Power stats downwards height sumxrtpstatsldnrecd 000300565kWh Power stats downwards energy recoveredxrtpstatsldnused 00356104kWh Power stats downwards energy usedxrtpstatslupdist 131km Power stats upwards distancexrtpstatsluphsum 66m Power stats upwards height sumxrtpstatsluprecd 0010866kWh Power stats upwards energy recoveredxrtpstatslupused 0263831kWh Power stats upwards energy usedxrtsbpwrdrv SC monitor virtual dyno drive power levelsxrtsbpwrrec SC monitor virtual dyno recup power levelsxrtsmtrqdrv SC monitor virtual dyno drive torque levelsxrtsmtrqrec SC monitor virtual dyno recup torque levels

Continued on next page

183 Contents 163

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxrtvbalert12v no Display service indicator 12V alertxrtvbalertbatt no Display service indicator Battery alertxrtvbalerttemp no Display service indicator Temperature alertxrtvbstatus 0 Internal BMS status (CAN frame 628)xrtvcstatus 0 Internal Charger status (CAN frame 627)xrtvistatus 0 Internal SEVCON status (CAN frame 629)xrtvelockedspeed 0 Speed limit [kph] set for Twizy lock modexrtvevaletodo 0 Odometer limit [km] set for Twizy valet mode

1833 Events

The Renault Twizy module emits these specific events additionally to the general OVMS events

Event Data Purposevehiclechargesubstatescheduledstop Charge stopped by user request (command)vehiclectrlcfgmode SEVCON in configuration mode (preop)vehiclectrlloggedin SEVCON session establishedvehiclectrlrunmode SEVCON in normal mode (op)vehicledrivemodechanged SEVCON tuning profile changedvehicledtcpresent ltdtc_descrgt OBD2 DTC (diagnostic trouble code) presentvehicledtcstored ltdtc_descrgt OBD2 DTC storedvehiclefaultcode ltcodegt SEVCON fault code receivedvehiclekickdownengaged Kickdown detected drive power changedvehiclekickdownreleased Kickdown mode end normal power restoredvehiclekickdownreleasing Kickdown mode about to end

1834 Custom Commands

Note This is currently just a brief overview to feed the search engine See each commandrsquos usage info and whereapplicable corresponding V2 manual entries on details

bull V3 commands need to be in lower case

bull When accessing via USB terminal first issue enable (login)

bull V3 commands are similar to V2 commands just structured slightly different

bull Try help and xrt Twizy commands are subcommands of xrt

bull TAB only works via USB SSH Shortcuts can be used generally eg mo t instead of module tasks

bull A usage info is shown if a command syntax is wrong or incomplete

OVMS xrt batt Battery monitorca Charge attributescfg SEVCON tuningdtc Show DTC report clear DTCmon SEVCON monitoringobd OBD2 toolspower Powerenergy info

164 Chapter 18 Renault Twizy

Open Vehicles

Battery Monitor

OVMS xrt batt data-cell Output cell recorddata-pack Output pack recordreset Reset alerts amp watchesstatus Status reporttdev Show temperature deviationstemp Show temperaturesvdev Show voltage deviationsvolt Show voltages

Note Also see standard BMS commands (bms )

Charge Attributes

OVMS xrt ca Usage xrt ca [R] | [ltrangegt] [ltsocgt] [Llt0-7gt] [S|N|H]

Note Also see standard charge control commands (charge )

SEVCON Tuning

OVMS xrt cfg brakelight Tune brakelight trigger levelsclearlogs Clear SEVCON diag logsdrive Tune drive power levelget Get tuning profile as base64 stringinfo Show tuning profileload Load stored tuning profileop Leave configuration mode (go operational)power Tune torque power amp current levelspre Enter configuration mode (pre-operational)querylogs Send SEVCON diag logs to serverramplimits Tune max pedal reactionramps Tune pedal reactionread Read registerrecup Tune recuperation power levelsreset Reset tuning profilesave Save current tuning profileset Set tuning profile from base64 stringshowlogs Display SEVCON diag logssmooth Tune pedal smoothingspeed Tune max amp warn speedtsmap Tune torquespeed mapswrite Read amp write registerwriteonly Write register

183 Contents 165

Open Vehicles

Show DTC Report Clear DTC

OVMS xrt dtc clear Clear stored DTC in carreset Reset OVMS DTC statisticsshow Show DTC report

SEVCON Monitoring

OVMS xrt mon reset Reset monitoringstart Start monitoringstop Stop monitoring

OBD2 Tools

OVMS xrt obd request Send OBD2 request output responseOVMS xrt obd request bms Send OBD2 request to BMSbroadcast Send OBD2 request as broadcastcharger Send OBD2 request to charger (BCB)cluster Send OBD2 request to cluster (display)device Send OBD2 request to a device

PowerEnergy Info

OVMS xrt power report Trip efficiency reportstats Generate RT-PWR-Stats entrytotals Power totals

1835 Notifications

The Renault Twizy module sends the custom or customized notifications described here additionally to the systemnotifications

See Notifications for general info on notifications

166 Chapter 18 Renault Twizy

Open Vehicles

Type Subtype Purpose Contentalert batterystatus Battery packcell alert status report (alerts amp watches)alert bmsstatus Battery management system alert (for custom BMS only)info chargestatussufficient Sufficient charge reached (SOCrange as configured)alert valetmodeodolimit Odometer limit reached speed reduction engagedalert vehicledtc OBD2 DTC (diagnostic trouble code) alertdata xrtbatterylog Battery packcell monitoring logdata xrtgpslog Extended GPS logdata xrtobdclusterdtc OBD2 DTC log for cluster (displayUCH)data xrtpowerdyno SEVCON live monitoring (virtual dyno) datadata xrtpowerlog Power statisticsinfo xrtpowertotals Current usage cycle power totalsdata xrttriplog Trip history loginfo xrttripreport Trip energy usage reportalert xrtsevconfault SEVCON fault condition detecteddata xrtsevconlog SEVCON faults amp events logsinfo xrtsevconprofilereset A tuning RESET has been performedinfo xrtsevconprofileswitch Tuning profile switch result

Trip history log

The trip history log can be used as a source for long term statistics on your trips and typical trip power usages as wellas your battery performance in different environmental conditions and degradation over time

Entries are created at the end of a trip and on each change in the charge state so you can also see where chargesstopped or how long they took and how high the temperatures got

bull Notification subtype xrttriplog

bull History record type RT-PWR-Log

bull Format CSV

bull Maximum archive time 365 days

bull Fieldscolumns

ndash odometer_km

ndash latitude

ndash longitude

ndash altitude

ndash chargestate

ndash parktime_min

ndash soc

ndash soc_min

ndash soc_max

ndash power_used_wh

ndash power_recd_wh

ndash power_distance

183 Contents 167

Open Vehicles

ndash range_estim_km

ndash range_ideal_km

ndash batt_volt

ndash batt_volt_min

ndash batt_volt_max

ndash batt_temp

ndash batt_temp_min

ndash batt_temp_max

ndash motor_temp

ndash pem_temp

ndash trip_length_km

ndash trip_soc_usage

ndash trip_avg_speed_kph

ndash trip_avg_accel_kps

ndash trip_avg_decel_kps

ndash charge_used_ah

ndash charge_recd_ah

ndash batt_capacity_prc

ndash chg_temp

Extended GPS log

The extended GPS log contains additional details about power and current levels the BMS power limits and theautomatic power level adjustments done by the OVMS You can use this to create detailed trip power charts and toverify your auto power adjust settings

The log frequency is once per minute while parkingcharging and controlled by config xrt gpslogint (web UITwizy rarr Features) while driving Logging only occurs if logged metrics have changed

bull Notification subtype xrtgpslog

bull History record type RT-GPS-Log

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash odometer_mi_10th

ndash latitude

ndash longitude

ndash altitude

ndash direction

ndash speed

168 Chapter 18 Renault Twizy

Open Vehicles

ndash gps_fix

ndash gps_stale_cnt

ndash gsm_signal

ndash current_power_w

ndash power_used_wh

ndash power_recd_wh

ndash power_distance

ndash min_power_w

ndash max_power_w

ndash car_status

ndash max_drive_pwr_w

ndash max_recup_pwr_w

ndash autodrive_level

ndash autorecup_level

ndash min_current_a

ndash max_current_a

Battery packcell monitoring log

The extended GPS log contains additional details about power and current levels the BMS power limits and theautomatic power level adjustments done by the OVMS You can use this to create detailed trip power charts and toverify your auto power adjust settings

The standard log frequency is once per minute logging only occurs if logged metrics have changed Additionalrecords are created on battery alert events Note an entry consists of a pack level record (RT-BAT-P) and up to 16(for LiFePO4 batteries) cell entries (RT-BAT-C)

bull Notification subtype xrtbatterylog

bull History record type RT-BAT-P (pack status)

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash packnr

ndash volt_alertstatus

ndash temp_alertstatus

ndash soc

ndash soc_min

ndash soc_max

ndash volt_act

ndash volt_min

183 Contents 169

Open Vehicles

ndash volt_max

ndash temp_act

ndash temp_min

ndash temp_max

ndash cell_volt_stddev_max

ndash cmod_temp_stddev_max

ndash max_drive_pwr

ndash max_recup_pwr

ndash bms_state1

ndash bms_state2

ndash bms_error

ndash bms_temp

bull Notification subtype xrtbatterylog

bull History record type RT-BAT-C (cell status)

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash cellnr

ndash volt_alertstatus

ndash temp_alertstatus

ndash volt_act

ndash volt_min

ndash volt_max

ndash volt_maxdev

ndash temp_act

ndash temp_min

ndash temp_max

ndash temp_maxdev

ndash balancing

ndash been_balancing

ndash balancetime

Power statistics

The power statistics are the base for the trip reports and can be used to analyze trip sections regarding speed andaltitude changes and their respective effects on power usage The log is also written when charging that data can beused to log changes in the charge current for example triggered externally by some solar charge controller

Log frequency is once per minute logging only occurs if metrics have changed

170 Chapter 18 Renault Twizy

Open Vehicles

bull Notification subtype xrtpowerlog

bull History record type RT-PWR-Stats

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash speed_const_dist

ndash speed_const_use

ndash speed_const_rec

ndash speed_const_cnt

ndash speed_const_sum

ndash speed_accel_dist

ndash speed_accel_use

ndash speed_accel_rec

ndash speed_accel_cnt

ndash speed_accel_sum

ndash speed_decel_dist

ndash speed_decel_use

ndash speed_decel_rec

ndash speed_decel_cnt

ndash speed_decel_sum

ndash level_up_dist

ndash level_up_hsum

ndash level_up_use

ndash level_up_rec

ndash level_down_dist

ndash level_down_hsum

ndash level_down_use

ndash level_down_rec

ndash charge_used

ndash charge_recd

OBD2 cluster DTC log

This server table stores DTC occurrences for one week This is mostly raw data and the DTCs are internal Renaultvalues that have not yet been decoded

See httpswwwtwizy-forumdeovms86362-liste-df-codes-dtc

bull Notification subtype xrtobdclusterdtc

183 Contents 171

Open Vehicles

bull History record type RT-OBD-ClusterDTC

bull Format CSV

bull Maximum archive time 7 days

bull Fieldscolumns

ndash EntryNr

ndash EcuName

ndash NumDTC

ndash Revision

ndash FailPresentCnt

ndash G1

ndash G2

ndash ServKey

ndash Customer

ndash Memorize

ndash Bt

ndash Ef

ndash Dc

ndash DNS

ndash Odometer

ndash Speed

ndash SOC

ndash BattV

ndash TimeCounter

ndash IgnitionCycle

SEVCON faults amp events

These logs are created on request only eg by the SEVCON logs tool in the Android App or by using the xrt cfgquerylogs command The command queries the SEVCON (inverter) alerts faults events and statistics (SEVCONneeds to be online) The results are then transmitted to the server using the following records

bull Notification subtype xrtsevconlog

bull History record type RT-ENG-LogKeyTime

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash KeyHour

ndash KeyMinSec

bull Notification subtype xrtsevconlog

172 Chapter 18 Renault Twizy

Open Vehicles

bull History record type RT-ENG-LogAlerts

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash Code

ndash Description

ndash TimeHour

ndash TimeMinSec

ndash Data1

ndash Data2

ndash Data3

bull Notification subtype xrtsevconlog

bull History record type RT-ENG-LogSystem

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash Code

ndash Description

ndash TimeHour

ndash TimeMinSec

ndash Data1

ndash Data2

ndash Data3

bull Notification subtype xrtsevconlog

bull History record type RT-ENG-LogCounts

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash Code

ndash Description

ndash LastTimeHour

ndash LastTimeMinSec

ndash FirstTimeHour

ndash FirstTimeMinSec

ndash Count

bull Notification subtype xrtsevconlog

183 Contents 173

Open Vehicles

bull History record type RT-ENG-LogMinMax

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns

ndash BatteryVoltageMin

ndash BatteryVoltageMax

ndash CapacitorVoltageMin

ndash CapacitorVoltageMax

ndash MotorCurrentMin

ndash MotorCurrentMax

ndash MotorSpeedMin

ndash MotorSpeedMax

ndash DeviceTempMin

ndash DeviceTempMax

SEVCON live monitoring

These records store the measurement results of the virtual dyno included in the SEVCON live monitor (Twizy rarrSEVCON Monitor) The virtual dyno records a torquepower profile from the actual car performance during drivingThe profile has four data sets

bull Maximum battery drive power over speed (metric xrtsbpwrdrv unit kW)

bull Maximum battery recuperation power over speed (metric xrtsbpwrrec unit kW)

bull Maximum motor drive torque over speed (metric xrtsmtrqdrv unit Nm)

bull Maximum motor recuperation torque over speed (metric xrtsmtrqrec unit Nm)

Power is measured at the battery so you can derive the efficiency Speed is truncated to integer the value arrays takeup to 120 entries (0 119 kph)

These datasets are visualized by the web UI using a chart and transmitted to the server on any monitoring ldquostoprdquo orldquoresetrdquo command in the following records

bull Notification subtype xrtpowerdyno

bull History record types RT-ENG-BatPwrDrv RT-ENG-BatPwrRec RT-ENG-MotTrqDrvRT-ENG-MotTrqRec

bull Format CSV

bull Maximum archive time 24 hours

bull Fieldscolumns max 120 values for speed levels beginning at 0 kph

1836 Twizy Regen Brake Light Hack

174 Chapter 18 Renault Twizy

Open Vehicles

Why

The Twizy recuperation levels are very low by default regenerative braking is so weak it doesnlsquot need to trigger thebrake light ndash so a regen braking indication has been omitted by Renault The Twizy can be tuned to one pedal drivingthough with high neutral braking power

The SEVCON normally can generate a regen braking signal itself That signal can be configured using the xrt cfgbrakelight tuning command Pin 11 on the SEVCON main connector will go to GND on activation The problemis that pin is not connected on the Twizy using it needs modification of the connector To my knowledge this hasnlsquotbeen done successfully up to now so we donlsquot even know if the Twizy SEVCON firmware includes that functionality

How does it work

The OVMS generates a secondary regen braking signal itself That signal is used to control a relay to provide powerto the brake light independant of the brake pedal

Integration is simple and does not require to change the existing connections

The Twizy UCHdisplay recognizes the regen brake light activation despite the foot brake being pushed and turns onthe SERV indicator Depending on your preferences you may see this as a problem or as an indicator for the regenbraking

Switching the 65A line does not avoid the SERV indicator (tested) Most probably the brake light is monitored by thecurrent flowing at the fuse box so the SERV indicator cannot be avoided without changing that system

Parts required

1 1x DA26 Sub-D 26HD Plug amp housing

bull Note housings for Sub-D 15 fit for 26HD

bull eg Assmann-WSW-A-HDS-26-LL-Z

183 Contents 175

Open Vehicles

bull Encitech-DPPK15-BK-K-D-SUB-Gehaeuse

2 1x 12V Universal Car Relay + Socket

bull eg Song-Chuan-896H-1CH-C1-12V-DC-Kfz-Relais

bull GoodSky-Relaissockel-1-St-GRL-CS3770

3 Car wire-tap connectors car crimp connectors 05 mm2 wires zipties shrink-on tube tools

Note if you already use the switched 12V output of the OVMS for something different you can use one of the freeEGPIO outputs That requires additionally routing an EGPIO line to the DA26 connector at the expansion slot (egusing a jumper) and using a relay module (relay shield) with separate power input instead of the standard car relay

Build

1 Solder ~ 40 cm two-core wire to the DA26 plug pins 8 (GND) and 18 (+12V switched) use shrink-on tubes toprotect the terminals mount the housing

2 Crimp 63mm sockets to the other ends of the wire isolate using shrink-on tube crimp 63mm plugs to the relaycoil (pins 85 + 86) isolate using shrink-on tube

176 Chapter 18 Renault Twizy

Open Vehicles

3 Extend the relay switch terminals by ~ 30 cm wires crimp on plugs for the tap connectors

4 Unmount the Twizy glovebox locate the red wire on the right above the parking brake

183 Contents 177

Open Vehicles

5 Crimp a tap connector onto the red wire and connect it to the relay (pin 30)

178 Chapter 18 Renault Twizy

Open Vehicles

6 Connect switched +12V likewise to pin 87 of the relay

bull +12V may be taken from the radio or 12V aux socket to simplify things

bull the dedicated brake light supply is fuse no 23 which is very hard to reach without dismounting the whole fuseholder

7 Place the relay in the free area on the upper left of the fuse holder (not below the door dampener that may crushthe relay) secure the relay using a ziptie

8 Pull the OVMS DIAG cable through the glovebox bottom hole and connect it to the relay inputs (pins 8586polarity doesnlsquot matter)

9 Do a test plug in the OVMS (Note the relay switches on during the first OVMS boot) switch on the Twizyissue commands

bull egpio output 1 1 should activate the brakelight

bull egpio output 1 0 should deactivate the brakelight

bull Note if youlsquore using another EGPIO port use the according port number (3-9) instead

10 Mount the glovebox and youlsquore done

Configuration

See OVMS web user interface menu Twizy rarr Brake Light

183 Contents 179

Open Vehicles

Set the port as necessary and the checkbox to enable the brakelight

For monitoring and fine tuning use the regenmon web plugin

httpsgithubcomopenvehiclesOpen-Vehicle-Monitoring-System-3blobmastervehicleOVMSV3componentsovms_webserverdevregenmonhtm

1837 Auxiliary Charge Fan

The builtin Elips 2000W chargerrsquos officially specified temperature operation range is -20+50 degC This is exceededby the Twizy easily even on moderate summer days The charger temperature can easily rise above 60 degC and this is

180 Chapter 18 Renault Twizy

Open Vehicles

possibly the main reason why Twizy chargers eventually die It also leads to the Twizy reducing the maximum chargepower available resulting in charges taking much longer than usual

A counter measure can be to add an additional fan to cool the charger and switch that fan on as necessary (seebelow) The fan can be controlled using one of the OVMS EGPIO output ports (see EGPIO) The easiest way is to usethe switched 12V supply available at the DA26 expansion plug without additional hardware The 12V port can delivera nominal output of 25W or 18A and up to 40W or 29A short term so can be used to power many auxiliary fansdirectly

To enable the auxiliary fan simply configure the EGPIO to be used in config parameter xrt aux_fan_port Forexample to use the switched 12V port = EGPIO port 1 do

OVMS config set xrt aux_fan_port 1

Set the port to 0 to disable the feature

Mode of operation

bull The OVMS continously monitors the charger temperature It turns on the fan when the charger temperaturerises above 45 degC (gt= 46 degC) and off when the temperature drops below 45 degC (lt= 44 degC)

bull After end of charge (Twizy system switched off) the OVMS does not get temperature updates so it keeps thefan running for another 5 minutes

The fan control works during charging and driving as during driving the charger also has to supply +12V by thebuiltin DCDC converter (heating up the charger) and a trip may start with an already hot charger

1838 Auxiliary Charger

The Elips 2000W (as the name says) does only charge with ~2 kW thus needing 3-35 hours to charge the originalTwizy battery Thatlsquos quite slow and gets worse when replacing the battery by a larger one

The Elips is running a special Renault firmware and also taking a crucial role in the Twizy system communication forexample to control the BMS So it cannot easily be replaced by a third party charger

But a third party charger can run in parallel to the Elips to boost the charge power This can be done best fromthe ldquorear endrdquo ie using the battery main connector as the power input (like the SEVCON does during regenerativebraking)

Some documented examples of additional chargers

bull httpswwwtwizy-forumdewerkstatt-twizy84935-twizy-schnelllader

bull httpswwwtwizy-forumdeprojekte-twizy83603-schnell-lader-extern

bull httpswwwtwizy-forumdetipps-und-tricks-twizy80814-twizy-schnellladen-die-wave-kann-kommen

The caveat to avoid damaging the battery additional charge power should not be supplied when the battery is nearlyfull So the additional charger needs to be switched off before the main charger finishes

The OVMS can automate switching the additional charger both on and off Any of the available EGPIO output ports(see EGPIO) can be used for this task If the charger has no digital power control input a convenient way is to use theswitched 12V supply available at the DA26 expansion plug without additional hardware The 12V port can deliver anominal output of 25W or 18A and up to 40W or 29A short term so can be used to power a standard automotiverelay directly

Configuration

Simply set the EGPIO to be used in config parameter xrt aux_charger_port For example to use the switched12V port = EGPIO port 1 do

183 Contents 181

Open Vehicles

OVMS config set xrt aux_charger_port 1

Set the port to 0 to disable the feature

Mode of operation

bull The port is switched ON when the Twizy charges is below 94 SOC is still within the CC phase (ie nottopping off balancing) and the charge current is not under user control

bull The port is switched OFF when the Twizy stops charging reaches 94 SOC or enters the topping off phase(whichever comes first) or when you set a custom charge current

Charge current control

If you set the charge current to level 7 (35 A) only the original charger will run but at full power You can set levels6 1 (30 5 A) to reduce the charge power only using the Elips charger Setting the current to level 0 (no chargethrottling) will allow maximum charge current from the Elips charger and additionally enable the second charger

182 Chapter 18 Renault Twizy

CHAPTER 19

Renault Zoe

Vehicle Type RZ

This vehicle type supports the Renault Zoe(PH1) and Kangoo(2011 - ~2019) The newer Zoe ph2 and Kangoo are notsupported yet

191 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display Yes (External Temp and Battery)BMS v+t Display YesTPMS Display Zoe Yes (pressure only)TPMS Display Kangoo NoCharge Status Display YesCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

After selecting the Renault ZoeKangoo vehicle module the corresponding settings have to be made in the web inter-face via the ldquoRenault ZoeKangoordquo menu under ldquoFeaturesrdquo

183

Open Vehicles

184 Chapter 19 Renault Zoe

CHAPTER 20

Smart ED Gen3

Vehicle Type SE

The Smart ED will be documented here

201 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display NoCharge Status Display YesCharge Interruption Alerts YesCharge Control Current limitCabin Pre-heatcool Control When charging and CAN-Bus ActiveLockUnlock Vehicle NoValet Mode Control NoOthers

185

Open Vehicles

202 Contents

2021 Custom Metrics

Metric name Example value DescriptionxsemybmsHWrev 12380 BMS hardware-revision year week patchlevelxsemybmsSWrev 12351 BMS soft-revision year week patchlevelxsemybmsadccvoltsmax 4171 maximum cell voltages in mV add offset +1500xsemybmsadccvoltsmean 4165 average cell voltage in mV no offsetxsemybmsadccvoltsmin 4145 minimum cell voltages in mV add offset +1500xsemybmsadcvoltsoffset 103 calculated offset between RAW cell voltages and ADCref about 90mVxsemybmsamps 65483A battery current in ampere (x32) reported by by BMSxsemybmsamps2 204634A battery current in ampere read by live data on CAN or from BMSxsemybmsbattvin WME4513901K661441 VIN stored in BMSxsemybmsdcfault 0 Flag to show DC-isolation faultxsemybmshv total voltage of HV system in Vxsemybmshvcontactcyclesleft 281991 counter related to ONOFF cyles of the carxsemybmshvcontactcyclesmax 300000 static seems to be maxiumum of contactor cyclesxsemybmsisolation 10239 Isolation in DC path resistance in kOhmxsemybmspower 794186kW power as product of voltage and amps in kWxsevbccapacity 184911853618536 Cell capacity [As]xsevbccapacitydevmax 451901901 Cell maximum capacity deviation observed [As]xsevbccapacitymax 184911853618536 Cell maximum capacity [As]xsevbccapacitymin 184911853618536 Cell minimum capacity [As]xsevbenergyusedreset 1634kWh Energy used Reset (Dashbord)xsevbenergyusedstart 169kWh Energy used Start (Dashbord)xsevbhvactive no HV Batterie Statusxsevbpcapacityasaverage 18625 cell capacity statistics from BMS measurement cyclexsevbpcapacityasmaximum 19193 cell capacity statistics from BMS measurement cyclexsevbpcapacityasminimum 18843 cell capacity statistics from BMS measurement cyclexsevbpcapacityavg 184459 Cell capacity - pack average [As]xsevbpcapacitycombinedquality 0515328 some sort of estimation factor constantly updatedxsevbpcapacitymax 18670 Cell capacity - strongest cell in pack [As]xsevbpcapacitymaxcell 9 Cell capacity - number of strongest cell in packxsevbpcapacitymin 18229 Cell capacity - weakest cell in pack [As]xsevbpcapacitymincell 59 Cell capacity - number of weakest cell in packxsevbpcapacityquality 0742092 some sort of estimation factor after measurement cyclexsevbpcapacitystddev 908 Cell capacity - current standard deviation [As]xsevbpcapacitystddevmax 908 Cell capacity - maximum standard deviation observed [As]xsevbphvlowcurrent 0Sec counter time of no current reset eg with PLC heater or drivingxsevbphvofftime 0Sec HighVoltage contactor off time in secondsxsevbplastmeasdays 13 days elapsed since last successful measurementxsevbpocvtimer 2676Sec counter time in seconds to reach OCV statexsevbpvoltagemaxcell 1 Cell volatage - number of strongest cell in packxsevbpvoltagemincell 5 Cell volatage - number of weakest cell in packxsevbrealsoc 978 real state of chargexsevbusawake no CAN-Bus Statusxsevcactive no Charging Statusxsevdisplaytime 738Min Dashbord Timexsevdisplaytripreset 27332km Dashbord Trip value at Reset

Continued on next page

186 Chapter 20 Smart ED Gen3

Open Vehicles

Table 1 ndash continued from previous pageMetric name Example value Descriptionxsevdisplaytripstart 175km Dashbord Trip value at Startxsevnlg6ampscablecode 0A Onboard Charger Ampere Cablexsevnlg6ampschargingpoint 0A Onboard Charger Ampere xsevnlg6ampssetpoint 41A Onboard Charger Ampere setpointxsevnlg6dccurrent 0A Onboard Charger LV current Amperexsevnlg6dchv 0V Onboard Charger HV Voltagexsevnlg6dclv 135V Onboard Charger LV Voltagexsevnlg6mainamps 000A Onboard Charger main Phasen Amperexsevnlg6mainvolts 000V Onboard Charger main Phasen Voltagexsevnlg6pnhw 4519820621 Onboard Charger Hardware Serial Noxsevnlg6present no Onboard Charger OBL or NLG6 presentxsevnlg6tempcoolingplate 0degC Onboard Charger coolingplate Temperaturexsevnlg6tempreported 0degC Onboard Charger reported Temperaturexsevnlg6tempsocket 0degC Onboard Charger socket Temperaturexsevnlg6temps Onboard Charger Temperaturesxsevposodometerstart 41940km Odo at last Ignition on For Trip calc Valuexsevdisplayaccel 89 Eco score on acceleration over last 6 hoursxsevdisplayconst 18 Eco score on constant driving over last 6 hoursxsevdisplaycoast 100 Eco score on coasting over last 6 hoursxsevdisplayecoscore 69 Eco score shown on dashboard over last 6 hours

2022 Custom Commands

xse trip

show last Trip value

xse recu up

xse recu down

set Rekuperation up or down Works only if Rekuperation is enabled in car

xse charge

set charge and leave Time

Example

xse charge 7 15 off

set Time at 715 clock with pre climate off

xse charge 9 55 on

set Time at 955 clock with pre climate on

2023 BMS Diagnose Tool

xse rptdata get a Battery Status Report

xse bmsdiag get Battery Diagnose Report

Original Tool ED BMSdiag

description DE

description EN

202 Contents 187

Open Vehicles

188 Chapter 20 Smart ED Gen3

CHAPTER 21

Smart EDEQ Gen4 (453)

Vehicle Type SQ

The Smart EDEQ Gen4 will be documented here

211 Support Overview

Function Support StatusHardware OVMS v3 (or later)Vehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location Yes (from modem module GPS)Speed Display YesTemperature Display Yes (External Temp and Battery)BMS v+t Display only Cell Volts atmTPMS Display NoCharge Status Display YesCharge Interruption Alerts NoCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers

189

Open Vehicles

190 Chapter 21 Smart EDEQ Gen4 (453)

CHAPTER 22

Tesla Model 3

Vehicle Type T3

At present support for the Tesla Model 3 in OVMS is experimental and under development This vehicle type shouldnot be used by anyone other than those actively involved in development of support for this vehicle

221 Support Overview

Function Support StatusHardware tbaVehicle Cable tbaGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna tbaSOC Display tbaRange Display tbaGPS Location tbaSpeed Display tbaTemperature Display tbaBMS v+t Display tbaTPMS Display tbaCharge Status Display tbaCharge Interruption Alerts tbaCharge Control tbaCabin Pre-heatcool Control tbaLockUnlock Vehicle tbaValet Mode Control tbaOthers tba

191

Open Vehicles

192 Chapter 22 Tesla Model 3

CHAPTER 23

Tesla Model S

Vehicle Type TS

At present support for the Tesla Model S in OVMS is experimental and under development This vehicle type shouldnot be used by anyone other than those actively involved in development of support for this vehicle

231 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support Not widely tested but should be

allVehicle Cable 9665972 OVMS Data Cable for Early TeslasGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna None not requiredSOC Display YesRange Display YesGPS Location Yes (from carrsquos built in GPS)Speed Display YesTemperature Display YesBMS v+t Display YesTPMS Display Not currently supportedCharge Status Display YesCharge Interruption Alerts YesCharge Control Not currently supportedCabin Pre-heatcool Con-trol

Not currently supported

LockUnlock Vehicle Not currently supportedValet Mode Control Not currently supportedOthers Adhesive velcro strips useful for vehicle attachment

193

Open Vehicles

232 TPMS Option

Reading and writing TPMS wheel sensor IDs fromto the Baolong TPMS ECU is supported by OVMS in Tesla ModelS cars using the Baolong system (vehicles produced up to around August 2014) You can easily tell if you have thisTesla Model S Baolong TPMS system as Tesla doesnrsquot support displaying tyre pressures in the instrument cluster Bycontrast the later Continental TPMS system does show the pressures in the instrument cluster

OVMS directly supports the Baolong TPMS in Tesla Model S cars without any extra hardware required You simplyneed the usual OVT1 cable

To read the current wheel sensor IDs from the Baolong TPMS ECU ensure that the car is ON (simplest is to wake thecar up and put in drive) and issue the lsquotpms readrsquo command in OVMS

Similarly to write wheel sensor IDs to the Baolong TPMS ECU ensure that the car is ON and issue the lsquotpms writersquocommand in OVMS

194 Chapter 23 Tesla Model S

CHAPTER 24

Tesla Roadster

Vehicle Type TR

The Tesla Roadster support in OVMS is perhaps the most mature in the project All versions (1x 2x and 3x) aresupported for both North American and other variants

241 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 1x 2x and 30 roadsters (all

markets)Vehicle Cable 9665972 OVMS Data Cable for Early TeslasGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna None not requiredSOC Display YesRange Display YesGPS Location Yes (from carrsquos built in GPS)Speed Display YesTemperature Display YesBMS v+t Display Not currently supportedTPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control YesCabin Pre-heatcool Con-trol

Not currently supported

LockUnlock Vehicle YesValet Mode Control YesOthers Adhesive velcro strips useful for vehicle attachment

195

Open Vehicles

242 Module Installation in the vehicle

The OVMS module is connected to your Roadster via the CAN bus diagnostic port connector which is located in thepassenger footwell It is made of plastic that is wrapped in grey foam as shown in the photo Typically the connectoris wedged into the front wall near the center console so it wonrsquot rattle Pull the connector out and note the orientationof the pins especially the void above the +12V and Ground pins

The OVMS Data Cable for Tesla Roadster can then be plugged in connecting the car to the OVMS module Makesure to tighten the screws holding the module-side DB9 connector

At this point check the car Tap on the VDS in the centre console and make sure it turns on Insert the key turn on thecar and make sure everything works as expected If you see any problems at all with the car disconnect the OVMSmodule and contact Open Vehicles support for assistance

WarningIf when you plug the OVMS into the car you see any interference to or strange behaviour of car systemsimmediately unplug the module and contact Open Vehicles for assistance Never leave a module connected in suchcircumstances

The OVMS Module is best secured to the front wall of the passenger footwell using adhesive velcro tape With themodule connected to the car diagnostics port connector experiment with various placements until you find a suitablespot For the velcro attachment to work yoursquoll want to choose a spot on the front wall thatrsquos flat for the entire size ofthe module (hint avoid the big round black plastic plug)

Mounting is straightforward

1 Ensure that both velcro strips are fixed together

2 Remove the adhesive backing from one side fasten it to the back of the OVMS module

3 Using a clean dry cloth clean the area of the car passenger footwell wall to which you are going to attach themodule

4 Remove the adhesive backing from the side of the velcro strip facing the car and then firmly push the OVMSmodule into place - holding it still for a few seconds to allow the adhesive to work

5 You can then remove and reinstall the OVMS module as desired via the velcro

196 Chapter 24 Tesla Roadster

Open Vehicles

243 Antenna Installation

You will find the performance of this antenna fantastic - and much better than even your cellphone but proper place-ment is essential Since it has a very long cable you can place the antenna just about wherever you want but pleaseensure it is high-up on the car and away from any metal objects that might interfere with the signal

Possible areas include the bottom of the windscreenwindshield on the passenger side the top of the windscreen onthe passenger side (hidden by the sun visor) behind the passenger on the side pillar in the rear window or under thedashboard (for the brave and experienced at dismantling Tesla Roadster dashboards)

The antenna is connected to the port marked GSM on the OVMS v3 module The GPS port is not used on the TeslaRoadster (as your car already has GPS installed and we can read that positioning information off the CAN bus directly)

2431 Antenna beside rear passenger headrest

The antenna cable is long enough to reach back to the area around the left side seat head This approach is generallyeasiest The module is placed in the left seat footwell near the diagnostic port connector From there the antennacable is routed through the base of the waterfall under the door sill and up the side of the door frame

The door sill is held in place by velcro and is easily removed You may have to loosen the waterfall (held in place byfour screws around the fuse box area) The antenna cable can then be placed on top of the metal of the chassis sillbetween the velcro strips and routed up through the existing plastic trunking At this point the door sill can then beput back in place

2432 Antenna on windshieldwindscreen

To route the antenna cable up to the front windshieldwindscreen you will need to remove the fuse-box cover (onescrew that needs to be turned 90 degrees) then two screws from the box below the fuse box (these screws should becompletely removed in order to be able to remove the box and access the compartment beneath) You do not need toadjust anything in the fuse box - you only need the cover removed to make it easier to route the cable

Start with the cable at the windscreenwindshield and route it down the side of the left side door front pillar Theplastic corner can be pulled back slightly and you can push the cable through into the open bottom compartmentPull the cable through there so that the antenna is where you want it and there is no loose cable outside the box Theantenna itself can be mounted to the windscreenwindshield by first cleaning the area with a clean dry cloth removingthe adhesive backing tape then firmly pushing the antenna against the glass and waiting a few seconds for the adhesiveto stick

Now for the tricky bit You need to get the cable through to the passenger footwell but it is tight It is much easier toget a guide wire up into the fuse box compartment than to get the antenna cable down into the passenger footwell Sowe recommend you use a small (12 inches 30 cm or so) piece of stiff wire to use as a guide and push it up from thearea marked by the green arrow on the bottom right of the picture below Once the guide wire is in the fuse box pushit down into the lower compartment you opened and wrap it around the antenna cable You can then pull the guidewire back down into the passenger footwell bringing the antenna cable with it

The antenna cable can then be screwed in to the OVMS module You can then tidy up any loose cable and screw-backthe lower compartment box (two screws) and fuse box cover (one screw 90 degrees to lock)

244 Configuration Options

The Tesla Roadster specific configuration options are in configuration parameter xtr

243 Antenna Installation 197

Open Vehicles

Instance Default Descriptiondigitalspeedo no Set to yes to enable digital speedometer (2x cars only)digitalspeedoreps 3 Number of CAN bus repeat transmissionscooldowntimelimit 60 Number of minutes after which cooldown is stoppedcooldowntemplimit 31 Temperature (in Celcius) after which cooldown is stoppedprotectlock yes Refuse to lock vehicle when switched on

245 Tesla Roadster Notes

1 In general the OVMS module in a Tesla Roadster acts exactly like the little VDS screen We should be able todo anything that screen can do but no more Here are some notes

2 The lockunlock and valet functions rely on a PIN code This is the same PIN code you enter into the vehicleusing the VDS screen when activating valet mode If you donrsquot know the PIN code either try the default 1234or contact Tesla for assistance

3 While OVMS can lockunlock the doors of all Tesla Roadster models cars outside North America are fitted withan immobiliser and neither OVMS nor the VDS will disarmarm that The OVMS lockunlock functionality onlyapplies to the doors not the alarm in vehicles sold outside North America

4 OVMS v3 can calculate an overall battery health metric This metric is calculated using our own algorithm andis in no way approved by Tesla Battery health is dependent on many factors and hard to bring down to just onesimple number

5 The Tesla Roadster requires the ignition key to be on and manual switches turned to coolheat the cabin It isnot technically possible to do this remotely via OVMS

The digital speedometer function replaces the AMPS display in the dashboard instrument cluster with the vehiclespeed It is only supported on v2x cars (not v15) This is an experimental feature and works 99 of the time butsometimes the car wins and displays AMPS for a split second A better solution is to use the HUD functionality ofOVMS v3 and install an external Heads Up Display in the car

246 TPMS Option

Reading and writing TPMS wheel sensor IDs fromto the Baolong TPMS ECU is supported in v2x Tesla Roadstersusing the optional OVMS K-Line Expansion Board You will need a v32 module (or v31 module labelled on boardas July 2018 or later with K-line pin connected) and an OVT1 vehicle cable (clearly labelled with ldquoOVT1rdquo on thecable)

The optional OVMS K-line Expansion Board should be configured with SW1 set to position 2 (LDO 5v) and S1 into OFF position (away from the ON label)

To read the current wheel sensor IDs from the Baolong TPMS ECU ensure that the ignition switch is ON (so instru-ment panel lights are on) and issue the lsquotpms readrsquo command in OVMS

Similarly to write wheel sensor IDs to the Baolong TPMS ECU ensure that the ignition switch is ON (so instrumentpanel lights are on) and issue the lsquotpms writersquo command in OVMS

Note that this functionality will not work with v15 Tesla Roadsters (that use a different TPMS ECU to the v2x cars)

198 Chapter 24 Tesla Roadster

Open Vehicles

247 Thanks

There are so many people to thank for Tesla Roadster support in OVMS WPetefish for sourcing the car connectorFuzzylogic for the original hardware and software design and demonstration of it working Scott451 for figuring outmany of the Roadster CAN bus messages Tom Saxton for v15 Roadster testing Michael Thwaite for pictures ofantenna installation Bennett Leeds for wordsmithing the manual Mark Webb-Johnson for CAN bus hacking andwriting the vehicle module support Sonny Chen for beta testing and tuning and many others for showing that thiskind of thing can work in the real world

247 Thanks 199

Open Vehicles

200 Chapter 24 Tesla Roadster

CHAPTER 25

Toyota RAV4 EV

Vehicle Type TYR4

At present support for the 2012-2014 Toyota RAV4 EV in OVMS is experimental and under development Thisvehicle type can be used by early adopters as long as you understand the limitations The current release only showsinformation from the Tesla CAN bus not the Toyota CAN bus and is read-only

201

Open Vehicles

251 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support All 2012-2014 RAV4 EV are identical

and no other years are supportedVehicle Cable A custom cable is required to connect at the left rear of the vehicle Tesla and Toyota CAN

buses are available at the Gateway ECUGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA)SOC Display Yes (Tesla BMS value)Range Display Not currently supportedGPS Location YesSpeed Display YesTemperature Dis-play

Yes

BMS v+t Display YesTPMS Display Not currently supportedCharge Status Dis-play

Yes

Charge InterruptionAlerts

Yes

Charge Control Not currently supportedCabin Pre-heatcool Control

Not currently supported

LockUnlock Vehi-cle

Not currently supported

Valet Mode Control Not currently supportedOthers

The Tesla CAN bus already had decodes available so those were implemented already The primary focus goingforward will be decoding the Toyota CAN bus to replicate SafetyConnect connected features like Remote Climatebefore the 3G shutdown ends that manufacturer provided functionality

The file xr4monhtm should be installed as a Page type Web Plugin to display detailed information about the carrsquosstatus

202 Chapter 25 Toyota RAV4 EV

CHAPTER 26

Tracking Vehicles

Vehicle Type XX

The track vehicle will be documented here

261 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support Not widely tested but should be allVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left) or any cable

proving powerGSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display NoRange Display NoGPS Location Yes (from modem module GPS)Speed Display Yes (from modem module GPS)Temperature Display NoBMS v+t Display NoTPMS Display NoCharge Status Display NoCharge InterruptionAlerts

No

Charge Control NoCabin Pre-heatcoolControl

No

LockUnlock Vehicle NoValet Mode Control NoOthers None

203

Open Vehicles

204 Chapter 26 Tracking Vehicles

CHAPTER 27

VW e-Up

Vehicle Type VWUP

This vehicle type supports the VW e-UP (2013- 2020-) Skoda Citigo E IV and the Seat MII electric (2020-) Con-nection can be made via the OBD2 port to the top left of the driving pedals andor the Comfort CAN bus eg belowthe passenger seat (T26 connector instead of the VW OCU there)

The main difference currently is that the OBD connection enables access to way more metrics (eg down to cellvoltages) while the Comfort CAN connection is necessary if write access is needed eg for remote climate controlThe Comfort CAN also provides data in more cases without turning on the car or charging as the bus wakes on manyevents (eg opening of doors) and can also be woken via OVMS

For the full experience making both connections is recommended

271 Using OBD2

Connection to OBD2 is done with the standard OVMS OBD2-cable just below the fuses left of the driving pedals

205

Open Vehicles

272 Using Comfort CAN

Connection to Comfort CAN can be done by removing the OCU below the passenger seat using a custom 26-pinadapter cable to the T26A plug (advantage the connections for the GSM amp GPS-antennas of the car can be used usinga Fakra-SMA adapter)

206 Chapter 27 VW e-Up

Open Vehicles

272 Using Comfort CAN 207

Open Vehicles

The passenger seat doesnrsquot need to be removed completely you can access the OCU connection from the back whentilting the unscrewed seat to the front To unscrew the seat yoursquoll need an XZN (triple-square german ldquoVielzahnrdquo)M10 bit Hint raise the seat to gain access to the rear screws

The T26a plug is secured by the white clamp open it fully to the left to unplug

273 Using both Connections

This document shows two options to use both connections

1 Variant 1 connects to the Comfort CAN using the OCU T26A connector

2 Variant 2 connects to the Comfort CAN by tapping the Comfort CAN cables

Both variants allow keeping the OCU in place If you intend to replace the OCU by the OVMS and reuse the OCUantennas for the OVMS variant 1 will probably be the better choice

2731 Variant 1

Connecting to the Comfort CAN using the OCU T26A connector

You need to establish a connection between the OBD2 and the OCU ports If installing the OVMS near the OBD2port you need to make a cable to connect to the T26A plug (or tap into the T26A cable there) If installing the OVMSreplacing the OCU you need to connect the OBD2 CAN bus from there

An adapter cable has to be made with the following connections

208 Chapter 27 VW e-Up

Open Vehicles

The cable used between the OBD plug and the DB9-F plug needs to be twisted to avoid transmission problems Agood cable to use here is a CAT-5 or CAT-6 double shielded network cable Be sure to not only connect CAN hi andCAN lo but also connect ground

T26 OBD DB9-F Signal26 4 3 Chassis Power GND 14 2 can1 L (OBD2 CAN Low) 6 7 can1 H (OBD2 CAN High) 4 can2 L (not used) 5 can2 H (not used)2 6 can3 L (Comfort-CAN Low)14 8 can3 H (Comfort-CAN High)1 9 +12V Vehicle Power

Important note the VW T26a pin numbering scheme does not follow the IT standard (zig zag) but instead has pins1-13 left to right on the top and 14-26 left to right on the bottom row See image above

2732 Variant 2

Connecting to the Comfort CAN by tapping the Comfort CAN cables

Description amp images by courtesy of GE user donaldduck8

This approach installs the OVMS near the OBD2 port and keeps the OCU in place Advantages

1 The OCU remains untouched and can be switched onoff as needed (fuse SD1)

2 No need to unmount the passenger seat

3 The OVMS can be disabledenabled any time simply via the OBD2 plug

The OVMS will be mounted on the driver side behind the footwell panel near the OBD2 port The Comfort CANsignal will be taken by tapping the cables behind the passengerrsquos footwell panel

The cable used needs to be twisted to avoid transmission problems A good cable to use here is a CAT-5 or CAT-6double shielded network cable A network cable has four pairs you will only need one pair here We recommendconnecting the shielding as well to avoid issues

273 Using both Connections 209

Open Vehicles

To connect to the OVMS you can use either a custom DB9 plug or add a DA26 connector You need to connect toCAN3

Comfort CAN OBD DB9-F DA26 Signal 4 3 8 Chassis Power GND 14 2 5 can1 L (OBD2 CAN Low) 6 7 15 can1 H (OBD2 CAN High) 12 4 7 can2 L (not used) 13 5 17 can2 H (not used)orangebrown 6 6 can3 L (Comfort-CAN Low)orangegreen 8 16 can3 H (Comfort-CAN High) 16 9 9 +12V Vehicle Power

Step 1 Remove the passenger footwell panel

Step 2 Tap into the Comfort CAN

Comfort CAN is on cables orangegreen (rarrCAN3-H) and orangebrown (rarrCAN3-L) Carefully remove a part of theisolation solder on your twisted pair cables then restore the isolation (eg by applying PlastiDip)

210 Chapter 27 VW e-Up

Open Vehicles

Step 3 Lay the cable towards the fuse box amp OBD2 port on the left

273 Using both Connections 211

Open Vehicles

Step 4 Use velcro tape to mount the OVMS on the side wall

Step 5 Stick the GPS antenna eg onto the air vent pipe To disable the OCU unplug fuse SD1

212 Chapter 27 VW e-Up

Open Vehicles

Step 6 Stick the GSM antenna eg on the lower panelrsquos rear side

Finally Refit all panels

273 Using both Connections 213

Open Vehicles

274 Basic Configuration

After selecting the VW e-Up vehicle module the corresponding settings have to be made in the web interface via theldquoVW e-Uprdquo menu under ldquoFeaturesrdquo

214 Chapter 27 VW e-Up

Open Vehicles

By default both connections are activated

For more details on the two connection types please see the corresponding projects

VW e-Up via Comfort CAN (T26A)

VW e-Up via OBD2

The initial code is shamelessly copied from the original projects for the Comfort CAN by Chris van der Meijden andfor the OBD2 port by SokoFromNZ

List of (possible) metrics via OBD2 httpswwwgoingelectricdewikiListe-der-OBD2-Codes

If OBD is selected a sample page with some charging metrics is shown in the web interface

274 Basic Configuration 215

Open Vehicles

216 Chapter 27 VW e-Up

Open Vehicles

Beware obviously these values have great uncertainties (in my car the DC output voltage of the charger is alwayslower than the voltage of the battery ) But eg the internal energy counters are very informative )

Additional custom web pages (code for the example above is below) can be defined as described here httpsdocsopenvehiclescomenlatestpluginREADMEhtmlhighlight=web20plugininstalling-web-plugins

274 Basic Configuration 217

Open Vehicles

275 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 2013-Vehicle Ca-ble

Comfort CAN T26A (OCU connector cable located under front passenger seat) to DB9 Data Cablefor OVMS using pin 6 and 8 for can3 _AND_ OBD-II to DB9 Data Cable for OVMS (1441200right or 1139300 left) for can1

GSMAntenna

T4AC - R205 with fakra_sma adapter cable or 1000500 Open Vehicles OVMS GSM Antenna (orany compatible antenna)

GPS An-tenna

T4AC - R50 with fakra_sma adapter cable or 1020200 Universal GPS Antenna (or any compatibleantenna)

SOC Dis-play

Yes

Range Dis-play

Yes

Cabin Pre-heatcoolControl

Yes

GPS Loca-tion

Yes (from modem module GPS)

Speed Dis-play

Yes

Tempera-ture Display

Yes (see list of metrics below)

BMS v+tDisplay

Yes

TPMS Dis-play

tba

Charge Sta-tus Display

Yes

ChargeInterruptionAlerts

Yes (per notification on the charging state)

ChargeControl

tba

LockUnlockVehicle

No

Valet ModeControl

No

Others See list of metrics below

276 Supported Standard Metrics

The second column specifies the bus from which the metrics are obtained Metrics via OBD are only updated when thevehicle is on (ignition started) or some in charging mode Metrics via T26 (Comfort CAN) can be updated on demandby waking the Comfort CAN from the OVMS module During charging the Comfort CAN automatically wakes every5 of SoC

218 Chapter 27 VW e-Up

Open Vehicles

Metric name bus Example value Descriptionvb12vvoltage direct 129 V Current voltage of the 12V batteryvbconsumption OBD 0Whkm Main battery momentary consumptionvbcurrent OBD 232 A Current current into (negative) or out of (positive) the main batteryvbenergyrecdtotal OBD 578323 kWh Energy recovered total (life time) of the main battery (charging and recuperation)vbenergyusedtotal OBD 540342 kWh Energy used total (life time) of the main batteryvbpower OBD 23234 kW Current power into (negative) or out of (positive) the main batteryvbrangeest T26 99km Estimated rangevbrangeideal T26 48km Ideal rangevbsoc OBD T26 882 Current usable State of Charge (SoC) of the main batteryvbtemp OBD 225 degC Current temperature of the main batteryvbvoltage OBD 3202 V Current voltage of the main batteryvc12vcurrent OBD 78A Output current of DCDC-convertervc12vpower OBD 0123kW Output power of DCDC-convertervc12vtemp OBD 345degC Temperature of DCDC-convertervc12vvoltage OBD 123V Output voltage of DCDC-convertervccharging T26 true Is vehicle charging (true = ldquoVehicle CHARGINGrdquo state veon=false if this is true)vcclimit fixed 1632A Maximum charger output currentvccurrent OBD 125A Momentary charger output currentvcefficiency OBD 913 Charging efficiency calculated by vbpower and vcpowervckwh OBD 26969kWh Energy sum for running chargevcmode T26 standard standard range performance storagevcpilot T26 no Pilot signal presentvcpower OBD 7345 kW Input power of chargervcstate T26 done charging topoff done prepare timerwait heating stoppedvcsubstate T26 scheduledstop scheduledstart onrequest timerwait powerwait stopped interruptedvctemp OBD 16degC Charger temperaturevctime T26 0Sec Duration of running chargevcvoltage OBD 0V Momentary charger supply voltagevdcp T26 yes yes = Charge port openvdfl T26 yes = Front left door openvdfr T26 yes = Front right door openvdhood T26 yes = Hoodfrunk openvdrl T26 yes = Rear left door openvdrr T26 yes = Rear right door openvdtrunk T26 yes = Trunk openveawake T26 no yes = Vehiclebus awake (switched on)vecabintemp T26 20degC Cabin temperaturevedrivetime T26 0Sec Seconds driving (turned on)veheadlights T26 yes = Headlights onvehvac T26 yes = HVAC activevelocked T26 yes = Vehicle lockedveon T26 true Is ignition on and drivable (true = ldquoVehicle ONrdquo false = ldquoVehicle OFFrdquo state)veparktime T26 49608Sec Seconds parking (turned off)veservrange OBD 12345km Distance to next scheduled maintenanceservice [km]veservtime OBD 1572590910Sec Time of next scheduled maintenanceservice [UTC]vetemp OBD T26 Ambient temperaturevitemp OBD Inverter temperaturevmtemp OBD 0degC Motor temperaturevpodometer OBD T26 2340 km Total distance traveledvpspeed T26 0kmh Vehicle speed

Continued on next page

276 Supported Standard Metrics 219

Open Vehicles

Table 1 ndash continued from previous pageMetric name bus Example value Descriptionvvin T26 VF1ACVYB012345678 Vehicle identification number

277 Custom Metrics

In addition to the standard metrics above the following custom metrics are read from the car or internally calculatedby OVMS using read values

Metricname

bus Examplevalue

Description

xvubcelldeltaOBD 0012 V Delta voltage between lowest and highest cell voltagexvubsocabs OBD 853 Current absolute State of Charge (SoC) of the main batteryxvucsocnormOBD 805 Current normalized State of Charge (SoC) of the main battery as reported by

charge management ECUxvucaci1 OBD 59 A AC current of AC charger phase 1xvucaci2 OBD 70 A AC current of AC charger phase 2 (only for model 2020+)xvucacp OBD 7223 kW Current charging power on AC side (calculated by ECUrsquos AC voltages and

AC currents)xvucacu1 OBD 223 V AC voltage of AC charger phase 1xvucacu2 OBD 233 V AC voltage of AC charger phase 2 (only for model 2020+)xvucdci1 OBD 12 A DC current of AC charger 1xvucdci2 OBD 12 A AC current of AC charger 2 (only for model 2020+)xvucdcp OBD 6500 kW Current charging power on DC side (calculated by ECUrsquos DC voltages and

DC currents)xvucdcu1 OBD 380 V DC voltage of AC charger 1xvucdcu2 OBD 375 V DC voltage of AC charger 2 (only for model 2020+)xvuceffcalc OBD 900 Charger efficiency calculated by AC and DC powerxvuceffecu OBD 923 Charger efficiency reported by the Charger ECUxvuclosscalc OBD 0733 kW Charger power loss calculated by AC and DC powerxvuclossecu OBD 0620 kW Charger power loss reported by the Charger ECUxvueservdaysOBD 78 days Time to next scheduled maintenanceservice [days]xvumsocabs OBD 853 Current absolute State of Charge (SoC) of the main battery as reported by

motor electronics ECUxvumsocnormOBD 805 Current normalized State of Charge (SoC) of the main battery as reported by

motor electronics ECU

278 Example Code for Web Plugin with some custom metrics

ltdiv class=panel panel-primarygtltdiv class=panel-headinggtCustom Metricsltdivgtltdiv class=panel-bodygt

lthrgt

ltdiv class=receivergtltdiv class=clearfixgtltdiv class=metric progress data-metric=vbsoc data-prec=1gtltdiv class=progress-bar value-low text-left role=progressbar

(continues on next page)

220 Chapter 27 VW e-Up

Open Vehicles

(continued from previous page)

aria-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoCltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=xvubsocabs data-prec=1gtltdiv class=progress-bar progress-bar-info value-low text-left role=progressbar

rarr˓aria-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoC (absolute)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbenergyusedtotal data-prec=2gtltspan class=labelgtTOTALSampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbsp

rarr˓ampnbspampnbspampnbspUsedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vbenergyrecdtotal data-prec=2gtltspan class=labelgtChargedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vpodometer data-prec=0gtltspan class=labelgtOdoltspangtltspan class=valuegtltspangtltspan class=unitgtkmltspangt

ltdivgtltdiv class=metric number data-metric=veservrange data-prec=0gtltspan class=labelgtSERVICEampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbspamp

rarr˓nbspampnbspampnbspampnbspRangeltspangtltspan class=valuegtltspangtltspan class=unitgtkmltspangt

ltdivgtltdiv class=metric number data-metric=xvueservdays data-prec=0gtltspan class=labelgtDaysltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

lth4gtBatterylth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=vbvoltage data-prec=1gtltdiv class=progress-bar value-low text-left role=progressbararia-valuenow=0 aria-valuemin=300 aria-valuemax=420 style=width0gtltdivgt

(continues on next page)

278 Example Code for Web Plugin with some custom metrics 221

Open Vehicles

(continued from previous page)

ltspan class=labelgtVoltageltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbcurrent data-prec=1gtltdiv class=progress-bar progress-bar-danger value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-200 aria-valuemax=200 style=width0gtltdivgtltspan class=labelgtCurrentltspangtltspan class=valuegtltspangtltspan class=unitgtAltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbpower data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-70 aria-valuemax=70 style=width0gtltdivgtltspan class=labelgtPowerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgtltdivgt

ltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbtemp data-prec=1gtltspan class=labelgtTempltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangtltdivgtltdiv class=metric number data-metric=xvubcelldelta data-prec=3gtltspan class=labelgtCell deltaltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangtltdivgt

ltdivgt

lth4gtTemperatureslth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=vetemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtAmbientltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vecabintemp data-prec=1gt

(continues on next page)

222 Chapter 27 VW e-Up

Open Vehicles

(continued from previous page)

ltdiv class=progress-bar progress-bar-warning value-low text-left role=rarr˓progressbar

aria-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtCabinltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbtemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtBatteryltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vctemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtChargerltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vc12vtemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtDCDC-Converterltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vitemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtInverterltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgtltdivgtltdiv class=metric progress data-metric=vmtemp data-prec=1gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbar(continues on next page)

278 Example Code for Web Plugin with some custom metrics 223

Open Vehicles

(continued from previous page)

aria-valuenow=0 aria-valuemin=-10 aria-valuemax=40 style=width0gtltdivgtltspan class=labelgtMotorltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdivgt

ltdivgtltdivgt

ltdivgtltdivgt

ltdivgt

279 Custom Data Logs

2791 SOC Monitoring Log

The SOC monitoring log provides detailed data about the correlations and connections between the various SOCsvoltage level amp energycoulomb chargedischarge amounts

You need to enable this log explicitly by configuring a storage time via config param xvu logsocmonstoretime (in days) Set to 0empty to disable the log Already stored log entries will be kept on the serveruntil expiry or manual deletion

Log entries are created on SOC changes while charging and every 10 seconds while driving

bull Notification subtype xvulogsocmon

bull History record type XVU-LOG-SOCMon

bull Format CSV

bull Archive time config xvu logsocmonstoretime (days 0=off)

bull Fieldscolumns

ndash temp ndash battery temperature [degC]

ndash charging ndash 01

ndash soc_abs_bms ndash absolute SOC from BMS (ECU 8C PID 028C) []

ndash soc_abs_eng ndash absolute SOC from engine (ECU 01 PID F45B) []

ndash soc_norm_cmg ndash normalized user SOC from charge manager (ECU BD PID 1DD0) []

ndash soc_norm_eng ndash normalized user SOC from engine (ECU 01 PID 1164) []

ndash soc_norm ndash previously selected soc_norm_eng while driving now always soc_norm_cmg []

ndash voltage ndash momentary total battery voltage [V]

ndash current ndash momentary battery current negative = charging [A]

ndash soh ndash state of health sourced as configured []

ndash cac ndash battery capacity sourced as configured [Ah]

ndash energy_used ndash total car energy discharge counter [kWh]

ndash energy_recd ndash total car energy charge counter [kWh]

224 Chapter 27 VW e-Up

Open Vehicles

ndash coulomb_used ndash total car coulomb discharge counter [Ah]

ndash coulomb_recd ndash total car coulomb charge counter [Ah]

ndash pack_vavg ndash average cell voltage [V]

ndash pack_vmin ndash minimum cell voltage [V]

ndash pack_vmax ndash maximum cell voltage [V]

ndash pack_vstddev ndash cell voltage standard deviation [V]

ndash pack_vgrad ndash cell voltage series quality (gradient)

ndash energy_range ndash remaining usable energy from MDF range estimation (ECU 17 PID 22E4) [kWh]

279 Custom Data Logs 225

Open Vehicles

226 Chapter 27 VW e-Up

CHAPTER 28

VW e-Up via OBD2

Vehicle Type VWUPOBD

This vehicle type supports the VW e-UP (new model from year 2020 onwards) Untested (so far) but probably workingThe older models of the e-Up as well as Skoda Citigo E IV and Seat MII electric

Connection is via the standard OBD-II port (above the drivers left foot)

All communication with the car is read-only For changing values (ie climate control) see the T26A connection tothe Comfort CAN bus

281 Support Overview

Function Support StatusHardware No specific requirementsVehicle Cable OBD-II to DB9 Data Cable for OVMS (1441200 right or 1139300 left)GSM Antenna 1000500 Open Vehicles OVMS GSM Antenna (or any compatible antenna)GPS Antenna 1020200 Universal GPS Antenna (SMA Connector) (or any compatible antenna)SOC Display YesRange Display YesGPS Location YesSpeed Display YesTemperature Display YesBMS v+t Display Yes (including cell details)TPMS Display YesCharge Status Display YesCharge Interruption Alerts YesCharge Control NoCabin Pre-heatcool Control NoLockUnlock Vehicle NoValet Mode Control NoOthers See list of metrics below

227

Open Vehicles

282 Vehicle States

Warning For proper state detection the 12V calibration is crucial Calibrate using the OVMS Web UI Configrarr Vehicle rarr 12V Monitor

Three vehicle states are supported and detected automatically

Vehicle ON The car is on It is drivable

Vehicle CHARGING The car is charging The carrsquos Charger ECU is responsive and reports charging activity

Vehicle OFF The car is off It hasnrsquot drawn (or charged) any current into the main battery for a period of time andthe 12V battery voltage is smaller than 129V

283 Supported Standard Metrics

Metrics updated in state ldquoVehicle ONrdquo or ldquoVehicle CHARGINGrdquo

Metric name Examplevalue

Description

veon yes Is ignition on and drivable (true = ldquoVehicle ONrdquo false = ldquoVehicle OFFrdquostate)

vccharging yes Is vehicle charging (true = ldquoVehicle CHARGINGrdquo state veon=false if thisis true)

vclimitsoc 100 Sufficient SOC timer mode SOC destination or user CTP configuration (seebelow)

vcmode range ldquorangerdquo = charging to 100 SOC else ldquostandardrdquovctimermode no Yes = currentnext charge under timer controlvcstate done charging stopped donevcsubstate scheduledstop scheduledstop scheduledstart onrequest timerwait stopped interruptedvb12vvoltage1 129 V Current voltage of the 12V batteryvbvoltage 3202 V Current voltage of the main batteryvbcurrent 232 A Current current into (negative) or out of (positive) the main batteryvbpower 23234 kW Current power into (negative) or out of (positive) the main batteryvbenergyusedtotal 540342 kWh Energy used total (life time) of the main batteryvbenergyrecdtotal 578323 kWh Energy recovered total (life time) of the main battery (charging and recu-

peration)vbtemp 225 degC Current temperature of the main batteryvpodometer 2340 km Total distance traveled

Metrics updated only in state ldquoVehicle ONrdquo

Metric name Example value Descriptionvbsoc2 882 Current usable State of Charge (SoC) of the main batteryvedrivemode 2 1=STD 2=ECO 3=ECO+vegear 1 1=forward 0=neutral -1=reverse (2020 model only)

Metrics updated only in state ldquoVehicle CHARGINGrdquo1 Also updated in state ldquoVehicle OFFrdquo2 Restriction by the ECU Supplied when the ignition is on during charging Use xvubsoc as an alternative when charging with ignition off

228 Chapter 28 VW e-Up via OBD2

Open Vehicles

Metric name Example value Descriptionvcpower 7345 kW Input power of chargervcefficiency 913 Charging efficiency calculated by vbpower and vcpower

284 Custom Metrics

In addition to the standard metrics above the following custom metrics are read from the car or internally calculatedby OVMS using read values

State metrics

Metric name Example value Descriptionxvuehvchgmode 0 High voltage charge mode 0=off 1=Type2 4=CCSxvuelvautochg 1 Auxiliary battery (12V) auto charge mode (01)xvuelvpwrstate 0 Low voltage (12V) power state (0=off 4=12V 8=HVAC 15=on)

Timed charge metrics

Metric name Example value Descriptionxvuclimitsocmax 80 Charge schedule maximum SOCxvuclimitsocmin 20 Charge schedule minimum SOCxvuctimermodedef yes Charge timer defined amp default

xvuctimermodedef tells if a charge schedule has been configured and enabled If so the car uses timedcharging by default (the charge mode button will be lit) vctimermode tells if the charge timer is or will actuallybe used for the current or next charge ie reflects the mode selected by pushing the button

With timed charging the car first charges to the minimum SOC as soon as possible (when connected) If the maximumSOC configured for the schedule hasnrsquot been reached by then it will then wait for the timer to signal the second phaseto charge up to the maximum SOC The ldquosufficient SOCrdquo vclimitsoc will be the maximum SOC if less than100 If the timer is disabled or set to charge up to 100 the sufficient SOC is set to the user configured charge timeprediction SOC limit (config xvu ctpsoclimit)

Charging above vclimitsoc is classified as the ldquotopping offrdquo charge phase When crossing that SOC thresholdan intermediate charge status notification is sent

Note xvuclimitsocmin will show the configured minimum SOC also if no schedule is currently enabledxvuclimitsocmax shows the maximum for the currentnext schedule to apply If no schedule is enabled itwill be zero

Metrics updated in state ldquoVehicle ONrdquo or ldquoVehicle CHARGINGrdquo

Metric name Example value Descriptionxvubcelldelta 0012 V Delta voltage between lowest and highest cell voltagexvubsoc 853 Current absolute State of Charge (SoC) of the main battery

Metrics updated only in state ldquoVehicle CHARGINGrdquo

284 Custom Metrics 229

Open Vehicles

Metric name Examplevalue

Description

xvuceffecu3 923 Charger efficiency reported by the Charger ECUxvuclossecu3 0620 kW Charger power loss reported by the Charger ECUxvucacp 7223 kW Current charging power on AC side (calculated by ECUrsquos AC voltages and AC

currents)xvucdcp 6500 kW Current charging power on DC side (calculated by ECUrsquos DC voltages and DC

currents)xvuceffcalc 900 Charger efficiency calculated by AC and DC powerxvuclosscalc 0733 kW Charger power loss calculated by AC and DC powerxvucccsu4 3315V CCS charger supplied voltage [V]xvucccsi4 622A CCS Charger supplied current [A]xvucccsp4 206193kW CCS Charger supplied power [kW]

285 Battery Capacity amp SOH

e-Up Model Total capacity Usable capacityGen 1 (2016) 187 kWh 50 Ah 164 kWh 439 Ah (877)Gen 2 (2020) 368 kWh 120 Ah 323 kWh 1053 Ah (877)

There are currently two ways to get an estimation of the remaining capacity of the e-Up

1 By deriving a usable energy capacity from the MFD range estimation

2 By deriving a total coulomb capacity from the coulombs charged

You can configure which of the estimations you want to use as the standard SOH from the ldquoFeaturesrdquo web page or bysetting the config parameter xvu batsohsource to either charge (default) or range

Note Consider the capacity estimations as experimental preliminary We need field data to optimize thereadings If yoursquod like to help us see below

The MFD range estimation seems to include some psychological factors with an SOC below 30 so we onlyprovide this and the derived capacity in two custom metrics The capacity derivation is only calculated with SOC gt=30 (initial value needs SOC gt= 70) but if so is available immediately after switching the car on This can serve asa quick first estimation relate it to the usable capacity of your model

The range based SOH is taken at itrsquos maximum peaks observed and copied if higher than the previously observedvalue or added smoothed if lower So to take the next reading directly set metric xvubsohrange to 0 beforeswitching on the car

The charge coulomb based estimation provides a better estimation but will need a little more time to settle Usablemeasurements need charges of at least 30 SOC the more the better Estimations are only calculated if a charge hasexceeded 30 SOC and results are smoothed over multiple charges to provide stable readings

bull To get a rough capacity estimation charge at least 30 normalized SOC difference

3 Only supplied by ECU when the car ignition is on during charging4 These are not measurements by the car but provided as is by the charger and typically deviate from the battery metrics According to IEC

61851 CCS currents may be off by +- 3 and voltages by +- 5 The power figures displayed by some chargers also typically wonrsquot match thesevalues possibly because the charger displays the power drawn from the grid (including losses)

230 Chapter 28 VW e-Up via OBD2

Open Vehicles

bull To get a good capacity estimation do at least three charges with each covering 60 or more normalized SOCdifference

Charging by CCS (DC) apparently yields higher results especially on the energy estimations We donrsquot know yet thereason or if we need to compensate this

Note the SOH (state of health) is currently coupled directly and solely to the calculated amp-hour capacity CAC

To log your capacity data on a connected V2 server do

OVMS config set xvu logchargecapstoretime 30

30 is the number of days to keep the data set to 0 to disable The counters will be stored in tableXVU-LOG-ChargeCap with one entry every 24 absolute SOC difference Resulting CACSOH updates willbe logged in table XVU-LOG-ChargeCapSOH You can also extract the data from your module log file by filteringlines matching ChargeCap

2851 Capacity and SOH metrics

Metric name Example value Descriptionxvubsohcharge 9923 SOH based on charge energy sumxvubsohrange 9889 SOH based on MFD range estimationxvubcapahabs 12271Ah Total coulomb capacity estimationxvubcapahnorm 11363Ah Usable coulomb capacity estimationxvubcapkwhabs 391kWh Total energy capacity estimationxvubcapkwhnorm 3621kWh Usable energy capacity estimationxvubcapkwhrange 328947kWh Usable energy capacity estimation from MFD rangexvubenergyrange 185kWh Current energy used by MFD range estimation

2852 Provide Data to the Developers

To help us with optimizing the capacity estimations first of all enable file logging if not already enabled Then enableextended polling and logging before a charge by

OVMS config set xvu dc_interval 30OVMS log level verbose v-vweup

After the charge disable the extended polling and logging

OVMS config set xvu dc_interval 0OVMS log level info v-vweup

Then download all log files written during the charge (archived and current) zip them and mail the zip to MichaelBalzer ltdexterdexters-webdegt The log data will only be used for technical analysis and deleted afterwards

Note if you forgot enabling the local log but still have chargecap logs on the server these can help as well

Thanks

286 Configuration Variables

The main configuration variables can be set through the web configuration page

286 Configuration Variables 231

Open Vehicles

bull VW e-Up rarr Features

Some configuration variables are kept ldquounder the hoodrdquo as these will normally not need to be changed except forsome special use cases or for development debugging

Configuration variables can be listed using command config list xvu and changed using command configset xvu ltvariablegt ltvaluegt

Configuration variable Default value Descriptionbatsohsource charge SOH source ndash see abovebmsautoreset no Reset BMS statistics on use phase transitionscanwrite no Allow CAN write accesscell_interval_awk 60 BMS cell query interval in awake state [s]cell_interval_chg 60 BMS cell query interval in charge state [s]cell_interval_drv 15 BMS cell query interval in drive state [s]con_obd yes Enable OBDII connectioncon_t26 yes Enable T26 connectionctpmaxpower 0 Charge time prediction fallback power limit [kW] (0=none)ctpsoclimit 80 Charge time prediction fallback SOC limit []dc_interval 0 Development additional DC charge PID query interval [s] (0=off)logchargecapcpstep 24 Charge capacity checkpoint interval [110]logchargecapminvalid 272 Charge capacity min SOC hub for SOH change [110]logchargecapstoretime 0 Charge capacity server log archive time [days] (0=off)modelyear 2012 Vehicle model yearnotifychargestartdelay 24 Charge start notification delay [s]5

287 Shell Commands

bull xvu polling ltstatus|pause|continuegt ndash control OBD2 polling

The OBD2 polling is normally continuously active as long as the vehicle module is loaded To free the CANbus from this load during an extended OBD2 diagnostics or modification (coding adaptation) session you cantemporarily pause the polling using this command

There is no time limit for a pause keep in mind you need to explicitly continue the polling when yoursquore doneDuring a polling pause no vehicle state changes can be detected

288 Custom Status Page for Web UI

Note This plugin is obsolete use the standard page VW e-Up rarr Charging Metrics instead We keep the sourcehere as a base for user customization

The easiest way to display custom metrics is using the Web Plugins feature of OVMS (see Installing Web Plugins)

This page plugin content shows the metrics in a compact form which can be displayed on a phone in landscape modeon the dashboard of the car Best approach is to connect the phone directly to the OVMS AP-WiFi and access the webUI via the static IP (19216841) of OVMS

5 Charge start needs some time to ramp up the charge current which implies charge speed amp time estimations If you want the start notificationas fast as possible reduce the value

232 Chapter 28 VW e-Up via OBD2

Open Vehicles

ltdiv class=panel panel-primarygtltdiv class=panel-headinggtVW eUpltdivgtltdiv class=panel-bodygt

lthrgt

ltdiv class=receivergtltdiv class=clearfixgtltdiv class=metric progress data-metric=vbsoc data-prec=2gtltdiv class=progress-bar value-low text-left role=progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoCltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=xvubsoc data-prec=2gtltdiv class=progress-bar progress-bar-info value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gtltdivgtltspan class=labelgtSoC (absolute)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

(continues on next page)

288 Custom Status Page for Web UI 233

Open Vehicles

(continued from previous page)

ltdivgtltdivgt

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbenergyusedtotal data-prec=3gtltspan class=labelgtTOTALSampnbspampnbspampnbspampnbspampnbspampnbspampnbspampnbspamp

rarr˓nbspampnbspampnbspampnbspUsedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vbenergyrecdtotal data-prec=3gtltspan class=labelgtChargedltspangtltspan class=valuegtltspangtltspan class=unitgtkWhltspangt

ltdivgtltdiv class=metric number data-metric=vpodometer data-prec=0gtltspan class=labelgtDistanceltspangtltspan class=valuegtltspangtltspan class=unitgtkmltspangt

ltdivgtltdivgt

lth4gtBatterylth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=vbvoltage data-prec=1gt

ltdiv class=progress-bar value-low text-left role=progressbararia-valuenow=0 aria-valuemin=300 aria-valuemax=350 style=width0gtltdivgtltspan class=labelgtVoltageltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbcurrent data-prec=1gtltdiv class=progress-bar progress-bar-danger value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-200 aria-valuemax=200 style=width0gtltdivgtltspan class=labelgtCurrentltspangtltspan class=valuegtltspangtltspan class=unitgtAltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=vbpower data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=-70 aria-valuemax=70 style=width0gtltdivgtltspan class=labelgtPowerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgt

(continues on next page)

234 Chapter 28 VW e-Up via OBD2

Open Vehicles

(continued from previous page)

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vbtemp data-prec=1gtltspan class=labelgtTempltspangtltspan class=valuegtltspangtltspan class=unitgtdegCltspangt

ltdivgtltdiv class=metric number data-metric=xvubcelldelta data-prec=3gtltspan class=labelgtCell deltaltspangtltspan class=valuegtltspangtltspan class=unitgtVltspangt

ltdivgtltdivgt

lth4gtChargerlth4gt

ltdiv class=clearfixgtltdiv class=metric progress data-metric=xvucacp data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=8 style=width0gtltdivgtltspan class=labelgtAC Powerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgt

ltdivgtltdiv class=metric progress data-metric=xvucdcp data-prec=3gtltdiv class=progress-bar progress-bar-warning value-low text-left role=

rarr˓progressbararia-valuenow=0 aria-valuemin=0 aria-valuemax=8 style=width0gtltdivgtltspan class=labelgtDC Powerltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgtltdivgt

ltdivgtltdivgtltdiv class=clearfixgtltdiv class=metric number data-metric=vcefficiency data-prec=1gt

ltspan class=labelgtEfficiency (total)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdiv class=metric number data-metric=xvuceffcalc data-prec=1gtltspan class=labelgtEfficiency (charger)ltspangtltspan class=valuegtltspangtltspan class=unitgtltspangt

ltdivgtltdiv class=metric number data-metric=xvuclosscalc data-prec=3gtltspan class=labelgtLoss (charger)ltspangtltspan class=valuegtltspangtltspan class=unitgtkWltspangt

ltdivgt(continues on next page)

288 Custom Status Page for Web UI 235

Open Vehicles

(continued from previous page)

ltdivgtltdivgtltdivgt

ltdivgt

236 Chapter 28 VW e-Up via OBD2

CHAPTER 29

VW e-Up via Comfort CAN (T26A)

Vehicle Type integrated in VWUP

This part was the initial code for the OVMS VWUP vehicle module Development started in January 2020 by Chrisvan der Meijden

It supports the VW e-UP (2013- 2020-) Skoda Citigo E IV and the Seat MII electric (2020-) directly connected tothe comfort can bus through the lsquoT26Arsquo socket

237

Open Vehicles

291 Support Overview

Function Support StatusHardware Any OVMS v3 (or later) module Vehicle support 2020- (2013- VW e-Up as well)Vehicle Cable Comfort CAN T26A (OCU connector cable located under front passenger seat) to DB9 Data

Cable for OVMS using pin 6 and 8 for can3GSM Antenna T4AC - R205 with fakra_sma adapter cable or 1000500 Open Vehicles OVMS GSM Antenna

(or any compatible antenna)GPS Antenna T4AC - R50 with fakra_sma adapter cable or 1020200 Universal GPS Antenna (or any com-

patible antenna)SOC Display YesRange Display YesCabin Pre-heatcool Control

Yes

GPS Location Yes (from modem module GPS)Speed Display YesTemperature Dis-play

Yes (outdoor cabin)

BMS v+t Display NoTPMS Display NoCharge Status Dis-play

Yes

Charge Interrup-tion Alerts

Yes (per notification on the charging state)

Charge Control tbaLockUnlockVehicle

No

Valet Mode Con-trol

No

Others Odometer trip VIN status of lock plug lights doors trunk and bonnet

292 Pinout OCU T26A - OVMS DB9 adapter

For the T26A approach we directly tap into the comfort can bus via the original OCU cable

The OCU connector is located under the passenger seat

238 Chapter 29 VW e-Up via Comfort CAN (T26A)

Open Vehicles

Advantage is the direct write access to the comfort can bus

Disadvantage is that we wonrsquot be able to access all control units of the car

OCU DB9-F Signal26 3 Chassis Power GND 2 can1 L (Can Low not used) 7 can1 H (Can High not used) 4 can2 L (Can Low not used) 5 can2 H (Can High not used)2 6 can3 L (Comfort-can Low)14 8 can3 H (Comfort-can High)1 9 +12V Vehicle Power

For confectioning the T26A adapter cable you can use a standard 26 pin ribbon cable (2x13 pins 254mm grid dimen-sion) and a DB9 female D-Sub connector You will need to grind down the rim of the socket of the ribbon cable

To make a GSMGPS adapter cable to connect to the original VW fakra socket you can use a double fakra maleconnector with two SMA male connectors attached

292 Pinout OCU T26A - OVMS DB9 adapter 239

Open Vehicles

293 User notes

bull Remove the passenger seat (on right hand drive cars the driverrsquos seat)

bull Open the carpet lid

bull Disconnect the T26A cable and the fakra cable from the OCU (online communication unit)

bull Remove the OCU

bull Connect the confectioned T26A adapter DB9 cable attached to the OVMS to the VW T26A connector of thecar

bull Connect your GMSGPS fakra adapter to the VW fakra cable

bull Fit OVMS in the compartment

bull Close the carpet lid

bull Reinstall the passenger seat

bull Configure OVMS as described in the OVMS user manual

bull Configure lsquoModel yearrsquo lsquoCan write accessrsquo and lsquoConnection typersquo under VW e-Up -gt Features

bull lsquoModel yearrsquo and lsquoCan write accessrsquo can also be set from within the app (FEATURES 20 and 15)

bull Register and connect OVMS to a server (as guided within the OVMS setup)

bull Turn the ignition in the car on and off to receive initial values (also needed after updates)

bull Install the OVMS app on your smartphone or tablet and configure it to connect to the server

240 Chapter 29 VW e-Up via Comfort CAN (T26A)

Open Vehicles

bull Enjoy -)

294 Climate control

Climate control works as long as write access to the comfort can has been enabled in the app or in the OVMSwebinterface (VW e-Up -gt Features)

To turn on or off the AC from within the Android app just press the ldquoACrdquo button Within the iOS app press ldquoHomelink1rdquo for AC on and ldquoHomelink 2rdquo for AC off

Once the AC is turned on by the app there will be a delay of about 17 seconds untill the AC actually starts in the carFurther 10 seconds all communication from the app to the car is blocked

The communication from the app to the car is also blocked for 10 seconds after the ldquoAC offrdquo command from the appto the car There is no delay between the ldquoAC offrdquo signal of the app and the actually turning off in the car

In rare cases lsquoAC offrsquo does not respond There will be a delay of 40 seconds before you can try again

The cabin target temperature can be set from the OVMS webinterface (VW e-Up (Komfort CAN) -gt Climate control)or via the app under FEATURES 21

294 Climate control 241

Open Vehicles

295 IDs on Comfort CAN Bus

ID Conversion Unit Function61A d72 State of Charge (relative)320 (d4ltlt8+d3-1)190 kmh Speed65F 3 Msg d5-7d1-7d1-7 String VIN number571 5+(05d0) Volt 12 Volt battery voltage65D d3ampfltlt12|d2ltlt8|d1 km Odometer3E3 (d2-100)2 degC Cabin temperature527 (d52)-50 degC Outdoor temperature531 d0 00 Headlights off52D d0 +255 if d1 41 km Calculated range381 d0 02 Status doors locked470 d1 12482010 Integer Doors trunk hood opened or closed3E1 d4 Integer Blower speed(57667D98BBDEFA)575 d0 00 to 0F Integer Key position575 d3 00 or 10 windshield heater (off or on)569 b07 ldquoACrdquo-LED69C d110+10 degC temperature setpoint for remote AC (only in message D2 ltd1gt 00 1E 1E

0A 00 00)61C d2 lt 07 bool Charging detection43D d1 01 or 11 TX Working or sleeping in the ring5A7 d1 16 TX OCU AC blocking signal5A9 all 00 TX OCU heartbeat69E multiple msg d0 C1 d6

xxdegC TX AC on off signals TX set cabin temperature for 69C

242 Chapter 29 VW e-Up via Comfort CAN (T26A)

Open Vehicles

296 Development notes

Under this vehicle component part we use the original T26A approach which can write to the comfort can and is ableto manage the climate control of the car

You will normally use the OVMS binaries provided ie here

The VWUP T26A component part with working climate control is publicly available within the OVMS binary version3215 lsquoedgersquo and upwards (lsquomainrsquo lsquoeaprsquo and lsquoedgersquo) The Android app version has to be 3171 or higher to haveaccess to the climate control functions for this vehicle component

If you want to compile the binary yourself you will need to read the OVMS development documentation on how to setup the tool chain check out the repository and the submodules and copy the file

sdkconfigdefaulthw31

from the OVMSV3support folder to the OVMSV3 folder and rename it to

sdkconfig

297 Vehicle log files

To be able to implement the VWUP vehicle component for OVMS the CAN logging of the VW e-UP provided bylsquosharkcowrsquo was of tremendous help

The implementation of this vehicle component could not have been done without these great files

They can be found here

httpsgithubcomsharkcowVW-e-UP-OBD-CAN-logs

296 Development notes 243

Open Vehicles

244 Chapter 29 VW e-Up via Comfort CAN (T26A)

CHAPTER 30

Command Line Interpreter

The command line interpreter or command parser presented by the OVMS async serial console is constructed as a treeof command word tokens Enter a single question mark followed by RETURN to get the root command list like this

OVMS Run a scriptbms BMS frameworkboot BOOT frameworkcan CAN framework

A root command may be followed by one of a list of additional tokens called subcommands which in turn may befollowed by further subcommands down multiple levels forming a tree The command and subcommand tokens maybe followed by parameters Use question mark at any level in the command sequence to get the list of subcommandsapplicable at that point If the next item to be entered is a parameter rather than a subcommand then a usage mes-sage will be displayed to indicate the required or optional parameters The usage message will also be shown if thecommand as entered is not valid The usage message is described in further detail below

Command tokens can be abbreviated so long as enough characters are entered to uniquely identify the command Op-tionally pressing TAB at that point will auto-complete the token If the abbreviated form is not sufficient to be unique(in particular if no characters have been entered yet) then TAB will show a concise list of the possible subcommandsand retype the portion of the command line already entered so it can be completed Pressing TAB is legal at any pointin the command if there is nothing more that can be completed automatically then there will just be no response tothe TAB

301 OvmsCommand API

Each command word token in the tree is represented by an OvmsCommand object TheOvmsCommandRegisterCommand() function is used to create and add a command or subcommand to-ken object into the tree returning an OvmsCommand pointer to the new object New commands are added to theroot of the tree using the global MyCommandAppRegisterCommand() Subcommands are added as childrenof a command by calling RegisterCommand() using the OvmsCommand pointer to the parent object thusbuilding the tree For example

245

Open Vehicles

OvmsCommand cmd_wifi = MyCommandAppRegisterCommand(wifiWIFI framework wifi_rarr˓status)cmd_wifi-gtRegisterCommand(statusShow wifi statuswifi_status)cmd_wifi-gtRegisterCommand(reconnectReconnect wifi clientwifi_reconnect)

The RegisterCommand() function takes the following arguments

bull const char name ndash the command token

bull const char title ndash one-line description for the command list

bull void (execute)() ndash does the work of the command

bull const char usage ndash parameter description for ldquoUsagerdquo message

bull int min ndash minimum number of parameters allowed

bull int max ndash maximum number of parameters allowed

bull bool secure ndash true for commands permitted only after enable

bull int (validate)() ndash validates parameters as explained later

The RegisterCommand() function tolerates duplicate registrations of the same name at the same node of the treeby assuming that the other arguments are also the same and returning the existing object This allows mulitple modulesthat can be configured independently to share the same top-level command For example the obdii command is sharedby the vehicle and obd2ecu modules

Modules that can be dynamically loaded and unloaded must remove their commands from the tree usingUnregisterCommand(const char name) before unloading

Itrsquos important to note that many of the arguments to RegisterCommand() can and should be defaulted The defaultvalues are as follows

execute = NULLusage = min = 0max = 0secure = truevalidate = NULL

For example for secure non-terminal commands (those with child subcommands) such as the top-level frameworkcommands like bms in the list of root commands shown earlier the model should simply be

RegisterCommand(name Title)

For secure terminal subcommands (those with no children) that donrsquot require any additional parameters the modelshould be

RegisterCommand(name Title execute)

This model also applies if the command has children but the command itself wants to execute a default operation if nosubcommand is specified It is incorrect to specify min = 0 max = 1 to indicate an optional subcommand that isindicated by the presence of the execute function along with a non-empty array of child subcommands

Any command with required or optional parameters should provide a ldquousagerdquo string hinting about the parameters inaddition to specifying the minimum and maximum number of parameters allowed

RegisterCommand(name Title execute usage min max)

246 Chapter 30 Command Line Interpreter

Open Vehicles

The usage argument only needs to describe the parameters that follow this (sub)command because the full usagemessage is dynamically generated The message begins with the text ldquoUsage rdquo followed by the names of the ancestorsof this subcommand back to the root of the tree plus the name of this subcommand itself That is the message startswith all the tokens entered to this point The message continues with a description of subcommands andor parametersthat may be entered next as specified by the usage string

Note The usage message is not resricted to a single line the usage string can include additional lines of explana-tory text separated by n (newline) characters to help convey the meaning of the paramters and the purpose of thecommand

The usage string syntax conventions for specifying alternative and optional parameters are similar to those of usagemessages in Unix-like systems The string can also include special codes to direct the dynamic generation of themessage

bull $C expands to the list of children commands as child1|child2|child3

bull [$C] expands to list optional children as [child1|child2|child3]

bull $G$ expands to the usage string of the first child this would typically used after $C so the usage message showsthe list of children and then the parameters or next-level subcommands that can follow the children This isuseful when the usage string is the same for all or most of the children as in this example

Usage power adc|can1|can2|can3|egpio|esp32|sdcard|simcom|spi|wifirarr˓deepsleep|devel|off|on|sleep|status

bull $Gfoo$ expands to the usage of the child named ldquofoordquo this variant would be used when not all the childrenhave the same usage but it would still be helpful to show the usage of one thatrsquos not first

bull $L lists a full usage message for each of the children on separate lines This provides more help than justshowing the list of children but at the expense of longer output

For subcommands that take parameters the usage string contains explicit text to list the parameters

bull Parameter names or descriptions are enclosed in angle brackets to distinguish the them from command tokensfor example ltmetricgt ltvaluegt Since the angle brackets demarcate each parameter spaces may be in-cluded in the description

bull Parameters that are optional are further enclosed in square brackets like ltidgt ltnamegt [ltvaluegt]

bull When there are alternative forms or meanings for a parameter the alternatives are separated by vertical bar asin lttask names or idsgt||= which indicates that the parameter can be either of the characters or =instead of a list of task names or ids A variant form encloses the alternatives in curly braces as in ltparamgtltinstancegt |

bull One or more additional lines of explanatory text can be included like this

ltidgtnUse ID from connection list 0 to close all

For non-terminal commands (those with children subcommands) the usage argument can be omitted because thedefault value of is interpreted as $C For commands that have children subcommands that are optional (because anexecute function is included) the default usage argument is interpreted as [$C]

3011 Execute Function

The execute function performs whatever work is required for the command Its signature is as follows

301 OvmsCommand API 247

Open Vehicles

void (execute)(int verbosity OvmsWriter writer OvmsCommand cmd int argc constrarr˓char const argv)

bull int verbosity ndash tells how much output is appropriate (eg shell vs SMS)

bull OvmsWriter writer ndash object to which output is delivered eg console

bull OvmsCommand cmd ndash the command that held the execute function pointer

bull int argc ndash how many parameters are being supplied to the function

bull const char const argv ndash the parameter list

Any output appropriate for the command is accomplished through puts() or printf() calls on the writerobject The cmd pointer may allow sharing one execute function among multiple related command objects andprovides access to members of the command object such as GetName()

The argc count will be constrained to the min and max values specified for the cmd object so if the minimum andmaximum are the same then the execute function does not need to check However if parameters are expected thentheir values must be validated

3012 Validate Function

Most commands do not need to specify a validate function It supports extensions of the original command parserdesign for two use cases

1 For commands that store the possible values of a parameter in a NameMapltTgt or CNameMapltTgt thevalidate function enables TAB auto-completion when entering that parameter

2 The original design only allowed parameters to be collected by the terminal subcommand That forced anunnatural word order for some commands The validate function enables non-terminal subcommands totake one or more parameters followed by multiple levels of children subcommands The parameters may bestrings looked up in a NameMapltTgt or CNameMapltTgt or they could be something else like a number that canbe validated by value The validate function must indicate success for parsing to continue to the childrensubcommands The return value is the number of parameters validated if successful or -1 if not

The signature of the validate function is as follows

int (validate)(OvmsWriter writer OvmsCommand cmd int argc const char constrarr˓argv bool complete)

bull OvmsWriter writer ndash object to which output is delivered eg console

bull OvmsCommand cmd ndash the command that held the validate function pointer

bull int argc ndash how many parameters are being supplied to the function

bull const char const argv ndash the parameter list

bull bool complete ndash true for TAB completion of the last parameter (case 1) false when validating intermediateparameters before calling execute on the terminal descendant command (case 2)

The writer and cmd arguments are the same as for the execute function The argc count is never more than maxand if complete is false never less than min However when complete is true to request TAB auto-completionand max is greater than 1 argc will be at least 1 but may be less than min because it indicates how many parametershave been entered so far The TAB auto-completion is performed on the last parameter entered after validating anypreceding parameters If min and max are both 1 then it is not necessary to check argc

If the acceptable values of a parameter are stored in a NameMapltTgt or CNameMapltTgt those maps implement aValidate() function that will perform the validation needed for the validate function covering both the true

248 Chapter 30 Command Line Interpreter

Open Vehicles

and false cases of complete Those maps also implement a FindUniquePrefix() function that may be used tovalidate preceding parameters for commands that take multiple parameters

The config_validate() function for the config command in mainovms_configcpp is an example imple-mentation of use case 1 for a command taking three parameters with TAB auto-completion on the first two

int config_validate(OvmsWriter writer OvmsCommand cmd int argc const charrarr˓const argv bool complete)if (MyConfigismounted())return -1

argv[0] is the ltparamgtif (argc == 1)return MyConfigm_mapValidate(writer argc argv[0] complete)

argv[1] is the ltinstancegtif (argc == 2)OvmsConfigParam const p = MyConfigm_mapFindUniquePrefix(argv[0])if (p) ltparamgt was not valid so cant check ltinstancegtreturn -1

return (p)-gtm_mapValidate(writer argc argv[1] complete)

argv[2] is the value which we cant validatereturn -1

The location command in componentsovms_locationsrcovms_locationcpp is an example of usecase 2 as it includes an intermediate parameter and also utilizes the $L form of the usage string

OVMS location action enter Usage location action enter ltlocationgt acc ltprofilegtUsage location action enter ltlocationgt homelink 1|2|3Usage location action enter ltlocationgt notify lttextgt

The following excerpt shows the implementation of the location_validate() function and a subset of theRegisterCommand() calls to build the command subtree This example shows how simple the validation codecan be ndash sometimes just one line to call Validate() In this case the code does need to check argc because thefunction is shared by multiple subcommand objects taking 1 or 2 parameters

int location_validate(OvmsWriter writer OvmsCommand cmd int argc const charrarr˓const argv bool complete)if (argc == 1)return MyLocationsm_locationsValidate(writer argc argv[0] complete)

return -1

OvmsCommand cmd_location = MyCommandAppRegisterCommand(locationLOCATIONrarr˓framework)OvmsCommand cmd_action = cmd_location-gtRegisterCommand(actionSet an action for

rarr˓a location)OvmsCommand cmd_enter = cmd_action-gtRegisterCommand(enterSet an action upon

rarr˓entering a location NULL ltlocationgt $L 1 1 true location_validate)OvmsCommand enter_homelink = cmd_enter-gtRegisterCommand(homelinkTransmit

rarr˓Homelink signal)enter_homelink-gtRegisterCommand(1Homelink 1 signallocation_homelink 0 0

rarr˓true)enter_homelink-gtRegisterCommand(2Homelink 2 signallocation_homelink 0 0

rarr˓true) (continues on next page)

301 OvmsCommand API 249

Open Vehicles

(continued from previous page)

enter_homelink-gtRegisterCommand(3Homelink 3 signallocation_homelink 0 0rarr˓true)cmd_enter-gtRegisterCommand(accACC profilelocation_accltprofilegt 1 1

rarr˓true)cmd_enter-gtRegisterCommand(notifyText notificationlocation_notifylttextgt 1

rarr˓ INT_MAX true)

250 Chapter 30 Command Line Interpreter

CHAPTER 31

CAN Bus Data Logging

OVMS can be used as CAN bus datalogging tool

311 Physical Connections

OVMS hardware V3 supports up to three CAN bus connections The connections to OVMS are as follows

DB9-F Signal----- ------

2 CAN1-L7 CAN1-H

4 CAN2-L5 CAN2-H

6 CAN3-L8 CAN3-H

Note the board schematics refer to CAN012 These correspond to CAN123 here in the documentation and sourcecode The first is handled by ESP32 io lines directly and CAN23 are handled by MCP2515 ICs via SPI from theESP

CAN1 is the fastest bus use this one if possible The CAN logging tool is able to log all buses at the same time to thesame file or stream

Vehicle CAN bus(s) are usually accesable via the vehiclersquos OBD2 port Most modern cars have multiple CAN bussesThe OBD2 lsquostandardrsquo CAN will be available on OBD2 pin 6 CAN-H and pin 14 CAN-L However modern vehicles(especially EVrsquos) often have other CAN buses available on non-standard OBD2 pins

A voltmeter (ideally oscilloscope) can be used to determine which OBD2 pins contain CAN data

bull Can high pins should normally be between 25 and 35 volts (to ground) - maybe 27 to 33 volts if there istraffic

bull Can low pins should normally be between 15 and 25 volts (to ground) - maybe 17 to 23 volts if there is traffic

251

Open Vehicles

Pre-fabricated OBD2 gt DB9-F for several specific vehicles can be purchased via OpenVehicles

312 Enable OVMS CAN bus

Once physical connections has been made and OVMS is up and running connect to OVMS shell via web browser SSH or serial

If a specific vehicle module is loaded the CAN bus will already be enabled in OVMS To check which CAN buses areenabled use

OVMS can list

If no vehicle module is selected the CAN bus must be started eg

OVMS can can1 start listen 500000

This will enable CAN1 in listen mode (read only) at 500k baud active can be used instead of listen to enableread-write mode To stop a CAN1 bus

OVMS can can1 stop

OVMS supports the following CAN bauds rates 100000 125000 250000 500000 1000000

313 Logging to SD card

It is possible to view CAN data directly in OVMS monitor shell however since modern cars have very busy CANbuses there is often too much data which swamps the monitor or exceeds the logging queue resulting in droppedmessages Logging to SD card is the better option

If using a good quality SD card with a current OVMS V3 module (ie PCB revision 32 20190523 or later) increasethe SD card speed for best performance with

config set sdcard maxfreqkhz 20000

Start logging all CAN messages using CRTD log file format with

ovms can log start vfs crtd sdcancrtd

or log specific CAN packets by applying a filter eg 0x55b the Nissan LEAF SoC CAN message

ovms can log start vfs crtd sdcancrtd 55b

Other CAN log file formats are supported eg crtd gvret-a gvret-b lawricel pcap raw

Check CAN logging satus with

ovms can log status

To Stop CAN logging

ovms can log stop

Note the can logging must be stopped before the file can be viewed

To View the CAN log

ovms vfs head sdcancrtd

tail and cat commands can also be used However be careful the log file can quickly become very large cat mayoverwhelm the shell

The log file can also be viewed in a browser with httpltovms-ipaddressgtsdcancrtd

252 Chapter 31 CAN Bus Data Logging

Open Vehicles

The logfiles can then be imported into a tool like SavvyCan for analysis

314 Network Streaming

CAN data can be streamed directly to SavvyCan (or other compatible application) using the OVMS tcpserver CANlogging feature over a local network Start tcpserver CAN logging with

OVMS can log start tcpserver discard gvret-b 23

This will start a tcpserver on port 23 (as required by SavvyCan) using the GVRET format supported by SavvyCAN

Once OVMS CAN logging tcpserver is running open up SavvyCan and select

Connection gt Add New Device Connection gt Network Connection

then enter the OVMS WiFi local network IP address (no port number required) CAN packets should now appearstreaming into SavvyCan

Note CAN tcpserver network streaming is a beta feture currently in edge firmware and may be buggy

315 Optimizing the Performance

On can log stop the system will output some statistics Check especially the dropped frame count Framedrops can occur because the system was busy with other tasks like handling network traffic There are two options tooptimize this

a) Reduce background activities ie stop all services not needed for the logging If possible do the loggingwithout an active vehicle module (eg set the ldquoemptyrdquo vehicle via vehicle module NONE)

b) Raise the log queue size The default queue size has a capacity of 100 frames To eg allow 200 frames doconfig set can logqueuesize 200

314 Network Streaming 253

Open Vehicles

254 Chapter 31 CAN Bus Data Logging

CHAPTER 32

CRTD CAN Log Format

321 Introduction

The CRTD CAN Log format is a textual log file format designed to store information on CAN bus frames and eventsIt was introduced as a human readable file format capable of supporting data dumps from multiple CAN buses

Files or network data streams in CRTD format contain only textual data in UTF-8 with each record being on anindividual line terminated by a single linefeed (ascii 10) character or CRLF (ascii 13 ascii 10)

Each line is made up from the following fields separated by single spaces (ASCII 32)

bull Timestamp Julian timestamp seconds and millisecondsmicroseconds separated by a decimal point

bull Record Type Mnenomic to denote the record type

bull Record Data The remaining data is dependant on the record type

Here are some examples

1542473901020305 1R11 1542473901020305 2T11 1542473901020305 R11 1542473901021 1R11

322 History

bull 10 Initial version supporting CXX R11 R29 T11 and T29 messages only

bull 20 Add optional bus ID prefix to record types

bull 30 Add support for comment commands and clarify documentation inconsistencies

255

Open Vehicles

323 Specification

CRTD files are UTF-8 text files using LF or CR+LF line termination to separate each record

ltcrtd-filegt = ltcrtd-recordgt [CR] LF

The records are formatted as follows

ltcrtd-recordgt = lttimestampgt ltspacegt ltcrtd-typegt lttimestampgt = ltjuliansecondsgt [ ltmillisecondsgt| ltmicrosecondsgt ] ltjuliansecondsgt = ltdigtigt ltdigitgt ltmillisecondsgt = ltdigitgt ltdigitgt ltdigitgtltmicrosecondsgt = ltdigitgt ltdigitgt ltdigitgt ltdigitgt ltdigitgt ltdigitgt ltdigitgt = [ 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |8 | 9 ] lthexdigitgt = [ ltdigitgt

A | B | C | D | E | F | a | b | c | d | e | f ]

ltspacegt = ASCII character 32 decimal (0x20 hex)

ltcrtd-typegt = [ ltcrtd-commentgt | ltcrtd-transmitgt | ltcrtd-receivegt ]

ltcrtd-commentgt = CXX ltspacegt lttextual-commentgt

ltcrtd-receivegt = R11 ltspacegt ltrxtx-datagt

ltbusgtR11 ltspacegt ltrxtx-datagtR29 ltspacegt ltrxtx-datagtltbusgtR29 ltspacegt ltrxtx-datagt

ltcrtd-transmitgt = T11 ltspacegt ltrxtx-datagt

ltbusgtT11 ltspacegt ltrxtx-datagtT29 ltspacegt ltrxtx-datagtltbusgtT29 ltspacegt ltrxtx-datagt

ltbusgt = ltdigitgt ltdigitgt

ltrxtx-datagt = ltcan-idgt ltspacegt ltcan-bytegt ltcan-idgt = lthexdigitgt lthexdigitgt ] ltcan-bytegt =lthexdigitgt [ lthexdigitgt ]

324 Timestamps

Timestamps can be provided in either millisecond or microsecond precision It is recommended that they be based onthe julian seconds in UTC but there is no specific requirement for that It is suggested that a comment may optionallybe placed at the start of the file to describe the timezone The timestamps should however increase monotonically inthe file (ie time flows forward with subsequent records)

If the timestamp contains 3 digits after the decimal point it should be consider millisecond precision and handledappropriately Similarly if the timestamp contains 6 digits after the decimal point it should be considered microsecondprecision

325 Case Independence

CAN IDs and data bytes are in case-independent hex and may or may not be padded with leading zeros CRTDprocessors should be as flexible as possible in their handling of this

256 Chapter 32 CRTD CAN Log Format

Open Vehicles

326 CAN Bus Designation

Record types may optionally be prefixed by the CAN bus number (1 n) If no bus number is provided 1 shouldbe assumed

327 Data bytes

The number of data bytes is limited by the CAN specification to a maximum of 8 bytes Similarly the range ofacceptable CAN IDs is limited by the 11bit 29bit encoding in the CAN protocol specification

328 Record Types

Each record can be one of a comment receive or transmit data Other record types should be discarded to allow newrecord types to be introduced without breaking existing processors

3281 Comment Records

Comment records start with the letter lsquoCrsquo and the record type has two characters following to denote the sub-typeThe rest of the record is to be considered a comment (or data for the command)

The following comment record types are defined

bull CXX General textual comment

bull CER An indication of a (usually recoverable) error

bull CST Periodical statistics

bull CEV An indication of an event

bull CVR Version of CRTD protocol adhered to (with version number as text comment)

and the following command record types are defined

bull CBC A command to configure a CAN bus

bull CDP A command to pause the transmission of messages

bull CDR A command to resume the transmission of messages

bull CFC A command to clear all filters for this connection

bull CFA A command to add a filter for this connection

Here are some examples

169971289 CXX Info Typecrtd Pathsdcan3crtd Filter30-ffffffffrarr˓VehicleTSHK19292299819 CEV vehiclealert this is a textual vehicle alert198923283738 CST intr=0 rxpkt=0 txpkt=0 errflags=0 rxerr=0 txerr=0 rxovr=0 txovr=0rarr˓txdelay=0 wdgreset=02783384726 CER intr=0 rxpkt=0 txpkt=0 errflags=0 rxerr=0 txerr=0 rxovr=0 txovr=0rarr˓txdelay=0 wdgreset=0

326 CAN Bus Designation 257

Open Vehicles

3282 Command Record CBC - Configure a CAN bus

The CBC command is used to configure a CAN bus It should be prefixed with the bus ID in the usual way or defaultto bus 1 if not defined

The command should have the following space separated parameters

bull mode either L for listen or A for active

bull speed the baud rate of the CAN bus

3283 Command Record CDP - Pause transmission

The CDP command is used to pause transmission of messages for this connection Upon receiving this commandthe device producing CRTD logs should henceforth discard those logs and not transmit them to this connection untilresumed

3284 Command Record CDR - Resume transmission

The CDR command is used to resume transmission of messages for this connection It clears the condition previouslyset by the CDP command

3285 Command Record CFC - Clear filters

The CFC command is used to clear the message filters for this connection

By default connections receive all messages for all CAN buses and that is indicated by the filter list being initiallyempty This command resets the filters to this default condition

Note that external to the per-message filters CAN data sources may also have incoming filters that apply to all incom-ing data (regardless of the logging destination) These incoming filters are not affected by this

3286 Command Record CFA - Add a filter

The CFA command is used to add a filter to the list of message filters for this connection If one or more filters aredefined only messages matching those filters will be forwarded

The command should have the filter passed as a single parameter

bull filter the filter to add

Filters are formatted as

Filter = ltbusgt | ltidgt[-ltidgt] | ltbusgtltidgt[-ltidgt]

For example

bull 22a0-37f for bus 2 IDs 0x2a0 - 0x37f

bull 10-37f for bus 1 IDs 0x000 - 0x37f

bull 3 for bus 3 all messages

bull 100-200 for bus 1 IDs 0x100 - 0x200

258 Chapter 32 CRTD CAN Log Format

Open Vehicles

3287 Received Frame Record

Received frame records describe a frame received from the CAN bus and start with the letter lsquoRrsquo Two types aredefined

bull R11 A standard 11bit ID CAN frame

bull R29 An extended 29bit ID CAN frame

The record type is followed by the frame ID (in hexadecimal) and then up to 8 bytes of CAN frame data

Here are some examples

1542473901020305 1R11 213 00 00 00 00 c0 01 00 001542473901020970 2R11 318 92 0b 13 10 11 3a 00 001542473901021259 2R11 308 00 ff f6 a6 06 03 80 001542473901021560 2R11 408 001542473901030341 1R11 358 18 08 20 00 00 00 00 201542473901034872 2R11 418 801542473901035514 1R11 408 101542473901036694 3R11 41C 101542473901040289 R11 428 00 301542473901042516 2R11 168 e0 7f 70 00 ff ff ff1542473901042809 2R11 27E c0 c0 c0 c0 00 00 00 001542473901043073 1R11 248 29 29 0f bc 01 10 00

3288 Transmitted Frame Record

Transmitted frame records describe a frame transmitted onto the CAN bus and start with the letter lsquoTrsquo Two types aredefined

bull T11 A standard 11bit ID CAN frame

bull T29 An extended 29bit ID CAN frame

The record type is followed by the frame ID (in hexadecimal) and then up to 8 bytes of CAN frame data

Here are some examples

1542473901020305 1T11 213 00 00 00 00 c0 01 00 001542473901020970 2T11 318 92 0b 13 10 11 3a 00 001542473901021259 2T11 308 00 ff f6 a6 06 03 80 001542473901021560 2T11 408 001542473901030341 1T11 358 18 08 20 00 00 00 00 201542473901034872 2T11 418 801542473901035514 1T11 408 101542473901036694 3T11 41C 101542473901040289 T11 428 00 301542473901042516 2T11 168 e0 7f 70 00 ff ff ff1542473901042809 2T11 27E c0 c0 c0 c0 00 00 00 001542473901043073 1T11 248 29 29 0f bc 01 10 00

329 Conclusions

The CRTD format is intended to be very simple to process either by automated code or humans manually It can beloaded into text editors for manipulation (search replace etc) and easily processed by command line tools such aslsquocutrsquo lsquogreprsquo lsquoawkrsquo etc

329 Conclusions 259

Open Vehicles

260 Chapter 32 CRTD CAN Log Format

CHAPTER 33

Web Framework amp Plugins

331 TLDR Examples

The following examples include their documentation in the HTML page and source Read the source and install themas plugins (see below) to see how they work

3311 Metric Displays

OVMS V3 is based on metrics Metrics can be single numerical or textual values or complex values like sets and arraysThe web framework keeps all metrics in a global object which can be read simply by eg metrics[vbsoc]

Metrics updates (as well as other updates) are sent to all DOM elements having the receiver class To hook intothese updates simply add an event listener for msgmetrics

Listening to the event is not necessary though if all you need is some metrics display This is covered by the metricwidget class family as shown here

261

Open Vehicles

Single Values amp Charts

The following example covers

bull Text (String) displays

bull Number displays

bull Progress bars (horizontal light weight bar charts)

bull Gauges

bull Charts

Gauges amp charts use the HighCharts library which is included in the web server The other widgets are simple standardBootstrap widgets extended by an automatic metrics value update mechanism

Highcharts is a highly versatile charting system For inspiration have a look at

bull httpswwwhighchartscomdemo

bull httpswwwhighchartscomdocs

Wersquore using styled mode so some options donrsquot apply but everything can be styled by standard CSS

Install the example as a web page plugin

metricshtm (hint right click save as)

262 Chapter 33 Web Framework amp Plugins

Open Vehicles

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltdiv class=panel panel-primarygt6 ltdiv class=panel-headinggtMetrics Displays TestDemoltdivgt7 ltdiv class=panel-bodygt8

9 ltpgtOVMS V3 is based on metrics Metrics can be single numerical or textual valuesrarr˓or complex values

10 like sets and arrays The web framework keeps all metrics in a global objectrarr˓which can be read

11 simply by eg ltcodegtmetrics[vbsoc]ltcodegtltpgt12

13 ltpgtMetrics updates (as well as other updates) are sent to all DOM elements havingrarr˓the

14 ltcodegtreceiverltcodegt class To hook into these updates simply add an eventrarr˓listener for

15 ltcodegtmsgmetricsltcodegt Listening to the event is not necessary if all yourarr˓need is some metrics

16 display This is covered by the ltcodegtmetricltcodegt class family as shown hererarr˓ltpgt

17

18 ltpgt19 ltbutton type=button class=btn btn-default action-gendatagtGenerate random

rarr˓dataltbuttongt20 ltbutton type=button class=btn btn-default action-showsrcgtShow page sourcelt

rarr˓buttongt21 ltpgt22

23 lthrgt24

25 ltdiv class=receivergt26

27 lth4gtBasic usagelth4gt28

29 ltpgtAll elements of class ltcodegtmetricltcodegt in a ltcodegtreceiverltcodegt arerarr˓checked for the

30 ltcodegtdata-metricltcodegt attribute If no specific metric class is given therarr˓metric value

31 is simply set as the element text ltspan class=metric data-metric=mnetrarr˓providergtltspangt

32 is your current network providerltpgt33

34 lth4gtText ampamp Numberlth4gt35

36 ltpgtltcodegtnumberltcodegt ampamp ltcodegttextltcodegt displays get the metric valuerarr˓set in their child of

37 class ltcodegtvalueltcodegt They may additionally have labels and units ltcodegtrarr˓data-precltcodegt can

38 be used on ltcodegtnumberltcodegt to set the precision ltcodegtdata-scaleltcodegtrarr˓to scale the raw

39 values by a factor They have fixed min widths and float by default so yourarr˓can simply put

40 multiple displays into the same containerltpgt41

42 ltdiv class=clearfixgt

(continues on next page)

331 TLDR Examples 263

Open Vehicles

(continued from previous page)

43 ltdiv class=metric number data-metric=vethrottle data-prec=0gt44 ltspan class=labelgtThrottleltspangt45 ltspan class=valuegtltspangt46 ltspan class=unitgtltspangt47 ltdivgt48 ltdiv class=metric number data-metric=vb12vvoltageref data-prec=1gt49 ltspan class=valuegtltspangt50 ltspan class=unitgtVltsubgtrefltsubgtltspangt51 ltdivgt52 ltdiv class=metric text data-metric=mnetprovidergt53 ltspan class=labelgtNetworkltspangt54 ltspan class=valuegtltspangt55 ltdivgt56 ltdivgt57

58 lth4gtProgress Barlth4gt59

60 ltpgtBootstrap ltcodegtprogressltcodegt bars can be used as lightweight graphicalrarr˓indicators

61 Labels and units are available also ltcodegtdata-precltcodegt and ltcodegtdata-rarr˓scaleltcodegt

62 Again all you need is a bit of markupltpgt63

64 ltdiv class=clearfixgt65 ltdiv class=metric progress data-metric=vethrottle data-prec=0gt66 ltdiv class=progress-bar progress-bar-success value-low text-left role=

rarr˓progressbar67 aria-valuenow=0 aria-valuemin=0 aria-valuemax=100 style=width0gt68 ltdivgt69 ltspan class=labelgtThrottleltspangt70 ltspan class=valuegtltspangt71 ltspan class=unitgtltspangt72 ltdivgt73 ltdivgt74 ltdivgt75 ltdiv class=metric progress data-metric=vb12vvoltageref data-prec=1gt76 ltdiv class=progress-bar progress-bar-info value-low text-left role=

rarr˓progressbar77 aria-valuenow=0 aria-valuemin=5 aria-valuemax=15 style=width0gt78 ltdivgt79 ltspan class=labelgt12V refltspangt80 ltspan class=valuegtltspangt81 ltspan class=unitgtVltspangt82 ltdivgt83 ltdivgt84 ltdivgt85 ltdivgt86

87 lth4gtGauges ampamp Chartslth4gt88

89 ltpgtThe OVMS web framework has builtin support for the highly versatile ltbgtrarr˓Highcharts libraryltbgt

90 with loads of chart types and options ltcodegtchartltcodegt metric examplesltpgt91

92 ltdiv class=rowgt93 ltdiv class=col-sm-6gt94 ltdiv class=metric chart data-metric=vethrottle style=height220pxgt

(continues on next page)

264 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

95 ltdiv class=chart-box gaugechart id=throttle-gaugegt96 ltdivgt97 ltdivgt98 ltdiv class=col-sm-6gt99 ltdiv class=metric chart data-metric=vbcvoltagevbcvoltagemin

rarr˓style=height220pxgt100 ltdiv class=chart-box barchart id=cell-voltagesgt101 ltdivgt102 ltdivgt103 ltdivgt104

105 ltpgtltbutton type=button class=btn btn-default action-gendatagtGenerate randomrarr˓dataltbuttongtltpgt

106

107 ltpgtFor charts a little bit of scripting is necessary108 The scripts for these charts contain the chart configuration part of which

rarr˓is the update109 function you need to define The update function translates metrics data into

rarr˓chart data110 This is trivial for single values like the throttle the cell voltage chart

rarr˓is an example111 on basic array processingltpgt112

113 ltpgtAlso while charts ltemgtcanltemgt be defined with few options youll ltemgtloverarr˓ltemgt to explore

114 all the features and fine tuning options provided by Highcharts Forrarr˓inspiration

115 have a look at the lta target=_blank href=httpswwwhighchartscomdemogtrarr˓Highcharts demosltagt

116 and the lta target=_blank href=httpswwwhighchartscomdocsgtHighchartsrarr˓documentationltagt

117 Were using lta target=_blank href=httpswwwhighchartscomdocschart-rarr˓design-and-stylestyle-by-cssgt

118 styled modeltagt so some options dont apply but everything can be styled byrarr˓standard CSSltpgt

119

120 ltdivgt121

122 ltdivgt123 ltdivgt124

125 ltscriptgt126 (function()127

128 Get page source before chart rendering 129 var pagesrc = $(main)html()130

131 Init throttle gauge 132 $(throttle-gauge)chart(133 chart 134 type gauge135 spacing [0 0 0 0]136 margin [0 0 0 0]137 animation duration 500 easing easeOutExpo 138 139 title text Throttle verticalAlign middle y 75 140 credits enabled false

(continues on next page)

331 TLDR Examples 265

Open Vehicles

(continued from previous page)

141 tooltip enabled false 142 plotOptions 143 gauge dataLabels enabled false overshoot 1 144 145 pane [146 startAngle -125 endAngle 125 size 100 center [50 60]147 ]148 yAxis [149 title text 150 className throttle151 reversed false152 min 0 max 100153 plotBands [154 from 0 to 60 className green-band 155 from 60 to 80 className yellow-band 156 from 80 to 100 className red-band 157 ]158 minorTickInterval auto minorTickLength 5 minorTickPosition inside159 tickPixelInterval 40 tickPosition inside tickLength 13160 labels step 2 distance -28 x 0 y 5 zIndex 2 161 ]162 series [163 name Throttle data [0]164 className throttle165 animation duration 0 166 pivot radius 10 167 dial radius 88 topWidth 1 baseLength 20 baseWidth 10

rarr˓rearLength 20 168 ]169 Update method 170 onUpdate function(update) 171 Create gauge data set from metric172 var data = [ metrics[vethrottle] ]173 Update chart174 thisseries[0]setData(data)175 176 )177

178 Init cell voltages chart 179 $(cell-voltages)chart(180 chart 181 type column182 animation duration 500 easing easeOutExpo 183 184 title text Cell Voltages 185 credits enabled false 186 tooltip 187 enabled true188 shared true189 headerFormat Cell pointkeyltbrgt190 pointFormat seriesname ltbgtpointyltbgtltbrgt191 valueSuffix V192 193 legend enabled true 194 xAxis 195 categories []196

(continues on next page)

266 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

197 yAxis [198 title text null 199 labels format value2fV 200 tickAmount 4 startOnTick false endOnTick false201 floor 33 ceiling 42202 minorTickInterval auto203 ]204 series [205 name Current data []206 className cell-voltage207 animation duration 0 208 209 name Minimum data []210 className cell-voltage-min211 animation duration 0 212 ]213 Update method 214 onUpdate function(update) 215 Note the update parameter contains the actual update set216 You can use this to reduce chart updates to the actual changes217 For this demo we just use the global metrics object218 var219 m_vlt = metrics[vbcvoltage] || []220 m_min = metrics[vbcvoltagemin] || []221 Create categories (cell numbers) amp rounded values222 var cat = [] val0 = [] val1 = []223 for (var i = 0 i lt m_vltlength i++) 224 catpush(i+1)225 val0push(Number((m_vlt[i]||0)toFixed(3)))226 val1push(Number((m_min[i]||0)toFixed(3)))227 228 Update chart229 thisxAxis[0]setCategories(cat)230 thisseries[0]setData(val0)231 thisseries[1]setData(val1)232 233 )234

235 Test metrics generator 236 $(action-gendata)on(click function() 237 var td = 238 td[mnetprovider] = [hologramVodafoneTelekom][Mathfloor(Math

rarr˓random()3)]239 td[vethrottle] = Mathrandom() 100240 td[vb12vvoltageref] = 10 + Mathrandom() 4241 var m_vlt = [] m_min = []242 for (var i = 1 i lt= 16 i++) 243 m_vltpush(36 + Mathrandom() 05)244 m_minpush(34 + Mathrandom() 02)245 246 td[vbcvoltage] = m_vlt247 td[vbcvoltagemin] = m_min248 $(receiver)trigger(msgmetrics $extend(metrics td))249 )250

251 Display page source 252 $(action-showsrc)on(click function()

(continues on next page)

331 TLDR Examples 267

Open Vehicles

(continued from previous page)

253 $(ltdivgt)dialog(254 title Source Code255 body ltpre style=font-size85 heightcalc(100vh - 230px)gt256 + encode_html(pagesrc) + ltpregt257 size lg258 )259 )260

261 )()262 ltscriptgt

Vector Tables

Some metrics for example the battery cell voltages or the TPMS tyre health data may contain vectors of arbitrarysize Besides rendering into charts these can also be displayed by their textual values in form of a table

The following example shows a live view of the battery cell voltages along with their recorded minimum maximummaximum deviation and current warningalert state Alert states 0-2 are translated into icons

The metric table widget uses the DataTables library which is included in the web server The DataTables Javascriptlibrary offers a wide range of options to create tabular views into datasets

Install the example as a web page plugin

metrics-tablehtm (hint right click save as)

1 lt--2 Web UI page plugin DataTables metrics widget demonstration3 --gt4

5 ltstylegt6 td i

(continues on next page)

268 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

7 font-style normal8 font-size 1409 line-height 90

10 font-weight bold11 12 td iwarning color orange 13 td idanger color red 14 ltstylegt15

16

17 ltdiv class=panel panel-primary panel-single receiver id=my-receivergt18 ltdiv class=panel-headinggtMetrics Table Widget Exampleltdivgt19 ltdiv class=panel-bodygt20

21 ltpgtThe following table shows a live view of the battery cell voltages along withrarr˓their recorded

22 minimum maximum maximum deviation and current warningalert stateltpgt23 ltpgtTry resizing the window or using a mobile phone to see how the table adapts to

rarr˓the screen24 width The table will also keep the selected sorting over data updatesltpgt25 ltpgtHint if you dont have live battery cell data click the generator button to

rarr˓create26 some random values The random data is only generated in your browser not on

rarr˓the moduleltpgt27

28 ltdiv class=metric table29 data-metric=vbcvoltagevbcvoltageminvbcvoltagemaxvbcvoltage

rarr˓devmaxvbcvoltagealertgt30 lttable class=table table-striped table-bordered table-hover id=v-table gt31 ltdivgt32

33 ltpgtSee lta target=_blank href=httpsdatatablesnetmanualgtDataTables manualrarr˓ltagt for all

34 options and API methods availableltpgt35

36 ltdivgt37 ltdiv class=panel-footergt38 ltpgtltbutton type=button class=btn btn-default action-gendatagtGenerate random

rarr˓dataltbuttongtltpgt39 ltdivgt40 ltdivgt41

42

43 ltscriptgt44 (function()45

46 Utilities47 var alertMap = 48 0 49 1 lti class=warninggtltigt50 2 lti class=dangergtltigt51 52

53 function fmtCode(value map) 54 return (map[value] == undefined) map[value] null55 56 function fmtNumber(value prec)

(continues on next page)

331 TLDR Examples 269

Open Vehicles

(continued from previous page)

57 return (value == undefined) Number(value)toFixed(prec) null58 59

60 Init table61 $(v-table)table(62 responsive true63 paging true64 searching false65 info false66 autoWidth false67 columns [68 title className dt-body-center width 6

rarr˓responsivePriority 1 69 title Voltage className dt-body-right width 22

rarr˓responsivePriority 3 70 title Minimum className dt-body-right width 22

rarr˓responsivePriority 4 71 title Maximum className dt-body-right width 22

rarr˓responsivePriority 5 72 title MaxDev className dt-body-right width 22

rarr˓responsivePriority 2 73 title Alert className dt-body-center width 6

rarr˓responsivePriority 1 74 ]75 rowId 076 onUpdate function(update) 77 Get vector metrics to display78 var v = [79 metrics[vbcvoltage] || []80 metrics[vbcvoltagemin] || []81 metrics[vbcvoltagemax] || []82 metrics[vbcvoltagedevmax] || []83 metrics[vbcvoltagealert] || []84 ]85 var lcnt = 086 vmap(el =gt lcnt = Mathmax(lcnt ellength))87 Transpose vectors to columns88 var l d = []89 for (l = 0 l lt lcnt l++) 90 dpush([91 l+192 fmtNumber(v[0][l] 2)93 fmtNumber(v[1][l] 2)94 fmtNumber(v[2][l] 2)95 fmtNumber(v[3][l] 3)96 fmtCode(v[4][l] alertMap)97 ])98 99 Display new data

100 thisclear()rowsadd(d)draw()101 102 )103

104

105 Test data generator106 $(action-gendata)on(click function() 107 var td =

(continues on next page)

270 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

108 var m_vlt = [] m_min = [] m_max = [] m_devmax = [] m_alert = []109 for (var i = 1 i lt= 16 i++) 110 m_vltpush(36 + Mathrandom() 05)111 m_minpush(34 + Mathrandom() 02)112 m_maxpush(38 + Mathrandom() 02)113 m_devmaxpush(-02 + Mathrandom() 04)114 m_alertpush(Mathfloor(Mathrandom() 3))115 116 td[vbcvoltage] = m_vlt117 td[vbcvoltagemin] = m_min118 td[vbcvoltagemax] = m_max119 td[vbcvoltagedevmax] = m_devmax120 td[vbcvoltagealert] = m_alert121 $(receiver)trigger(msgmetrics $extend(metrics td))122 )123

124 )()125 ltscriptgt

3312 Command Buttons amp Monitors

commandshtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltstylegt6 h3 7 margin-top 40px8 margin-bottom 20px9

10 ltstylegt11

12 ltdiv class=panel panel-primarygt13 ltdiv class=panel-headinggtCommands ampamp Monitorsltdivgt14 ltdiv class=panel-bodygt15

16 ltpgtCommand execution is only allowed for an authorized session The command API will17 output Unauthorized and a Login button as necessary The login state is also18 available in the global variable ltcodegtloggedinltcodegt To send the user to the19 login page and return to the current page after login call ltcodegtlogin()ltcodegt

rarr˓ltpgt20

21 ltpgt22 ltbutton type=button class=btn btn-default action-login onclick=login()gtLogin

rarr˓ltbuttongt23 ltbutton type=button class=btn btn-default action-logout onclick=logout()gt

rarr˓Logoutltbuttongt24 ltpgt25

26 ltscriptgt27 $(action-login)prop(disabled loggedin)28 $(action-logout)prop(disabled loggedin)29 ltscriptgt

(continues on next page)

331 TLDR Examples 271

Open Vehicles

(continued from previous page)

30

31

32 lth3gtCommand Execution on Loadlth3gt33

34 ltpgtTo execute a command automatically on page load simply add the ltcodegtmonitorltrarr˓codegt class

35 to an output element set ltcodegtdata-updcmdltcodegt to the command to be executedrarr˓and

36 ltcodegtdata-updcntltcodegt to 1ltpgt37

38 ltpre class=monitor data-updcmd=boot status data-updcnt=1gtFetching bootrarr˓statusltpregt

39

40 ltpgtOutput elements typically are ltcodegtsampltcodegt or ltcodegtpreltcodegt as commands41 normally output formatted plain text but any element can be used ltcodegtsamplt

rarr˓codegt42 by default compresses white space and has no visible area while ltcodegtpreltcodegt43 is visible and preserves all spacingltpgt44

45 ltpgtltcodegtupdcntltcodegt will count down to zero and stop or run indefinitely ifrarr˓started

46 below zero The execution interval can be given in ltcodegtdata-updintltcodegt (inrarr˓seconds)

47 You can set the data attributes any time using jQuery all monitors are checkedrarr˓and

48 updated by the framework once per secondltpgt49

50

51 lth3gtCommand Execution on Eventslth3gt52

53 ltpgtTo automatically trigger a monitor update on OVMS events additionally set the54 ltcodegtdata-eventsltcodegt attribute to a regular expression matching the event(s)

rarr˓of55 interest This example monitor lists the active network channels and automatically56 updates on all server connection eventsltpgt57

58 ltpgtltpre class=monitor59 data-events=server(connect|open|close|stop)60 data-updcmd=network list61 data-updcnt=1gtltpregtltpgt62

63 ltpgt64 Try65 lta class=btn btn-default onclick=windowopen( _blank width=400

rarr˓height=500)gtOpen new windowltagt66 lta class=btn btn-default href= data-cmd=server v2 stopgtStop V2 serverltagt67 lta class=btn btn-default href= data-cmd=server v2 startgtStart V2 serverltagt68 lta class=btn btn-default href= data-cmd=event raise serverfakeopengtSend

rarr˓fake eventltagt69 ltpgt70

71

72 lth3gtCommand Buttonslth3gt73

74 ltpgtA bootstrap button has the base class ltcodegtbtnltcodegt Add the command torarr˓execute

75 as attribute ltcodegtdata-cmdltcodegt and optionally the output element as(continues on next page)

272 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

76 ltcodegtdata-targetltcodegt and youre doneltpgt77

78 ltdiv class=rowgt79

80 ltdiv class=col-sm-6gt81 ltbutton type=button class=btn btn-default data-target=out1 data-cmd=

rarr˓wifi statusgt82 Wifi Status rarr ltcodegtampltsampampgtltcodegt83 ltbuttongt84 ltsamp id=out1 gt85 ltdivgt86

87 ltdiv class=col-sm-6gt88 ltbutton type=button class=btn btn-default data-target=out2 data-cmd=

rarr˓wifi statusgt89 Wifi Status rarr ltcodegtampltpreampgtltcodegt90 ltbuttongt91 ltpre id=out2 gt92 ltdivgt93

94 ltdivgt95

96 ltpgtAdd class ltcodegtsamp-inlineltcodegt or wrap in a ltcodegtullist-inlineltcodegt torarr˓place

97 the output element on the same line with the button Prefix the target with a +rarr˓to

98 append to itltpgt99

100 ltpgt101 External 12V power102 ltbutton type=button class=btn btn-info data-target=+out3 data-cmd=power

rarr˓ext12v ongtonltbuttongt103 ltbutton type=button class=btn btn-info data-target=+out3 data-cmd=power

rarr˓ext12v offgtoffltbuttongt104 ltsamp class=samp-inline id=out3 gt105 ltpgt106

107

108 lth3gtCombining Buttons ampamp Monitorslth3gt109

110 ltpgtBy combination of a button and a monitor you can let the button start a repeated111 execution of a command set ltcodegtdata-watchcntltcodegt on the button to the

rarr˓number of112 repetitions (default 0) and ltcodegtdata-watchintltcodegt to the interval in seconds113 (default 2)ltpgt114

115 ltpgt116 ltbutton type=button class=btn btn-default data-target=out4117 data-cmd=power cellular on data-watchcnt=-1 data-watchint=3gt118 Power on cellular modem ampamp get status updates every 3 seconds119 ltbuttongt120 ltpre class=monitor id=out4 data-updcmd=cellular status gt121 ltpgt122

123 ltpgtNote to stop a monitor set ltcodegtdata-updcntltcodegt to 0124 ltbutton type=button class=btn btn-default onclick=$(out4)data(updcnt

rarr˓0)gt(continues on next page)

331 TLDR Examples 273

Open Vehicles

(continued from previous page)

125 Stop updates126 ltbuttongtltpgt127

128

129 lth3gtExecute Javascriptlth3gt130

131 ltpgtTo execute Javascript code directly (ie without calling ltcodegtscript evalltrarr˓codegt)

132 simply exchange the ltcodegtdata-cmd data-updcmdltcodegt attribute by133 ltcodegtdata-js data-updjsltcodegt Exampleltpgt134

135 ltpgt136 ltbutton type=button class=btn btn-default data-target=out5137 data-js=JSONprint(OvmsConfigGetValues(vehicle))gt138 Show vehicle config139 ltbuttongt140 ltpre id=out5 gt141 ltpgt142

143 ltdivgt144 ltdivgt145

146

147 ltscriptgt148 (function()149 Show page source 150 var pagesrc = $(main)html()151 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +152 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)153 $(action-showsrc)on(click function() 154 $(ltdivgt)dialog(155 title Source Code156 body ltpre style=font-size85 heightcalc(100vh - 230px)gt157 + encode_html(pagesrc) + ltpregt158 size lg159 )160 )161 )()162 ltscriptgt

3313 Notifications

notificationshtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web file path eg sddevnotificationshtm5 - open in framework by eg httptest1localdevnotificationshtm6 --gt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtNotification TestDemoltdivgt

10 ltdiv class=panel-bodygt

(continues on next page)

274 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

11 lth4gtReceiverlth4gt12 lt--13 You can use data-subscriptions to preconfigure subscriptions14 Note types info error and alert get sent to all receivers15 --gt16 ltpre id=log class=receiver data-subscriptions=notifystreammyappgtIm

rarr˓preconfigured to receive notifystreammyappltpregt17 ltdivgt18 ltdiv class=panel-footergt19 ltdivgt20 ltlabel for=topicsgtTest commandltlabelgt21 ltinput type=text class=form-control font-monospace id=cmd value=notify

rarr˓raise text stream myappinput my first streamgt22 ltpgtJSON example ltcode class=autoselectgtnotify raise text stream myappinput

rarr˓myJSON streampi3141fib[1235813]ltcodegtltpgt23 ltbutton type=button class=btn btn-default id=action-execgtExecuteltbuttongt24 ltsamp id=cmdres gt25 ltdivgt26 ltdivgt27 ltlabel for=topicsgtTopic subscription (separate topics by space)ltlabelgt28 ltinput type=text class=form-control font-monospace id=topics value=

rarr˓notifystreammyappgt29 ltbutton type=button class=btn btn-default id=action-subgtSubltbuttongt30 ltbutton type=button class=btn btn-default id=action-unsubgtUnsubltbuttongt31 ltbutton type=button class=btn btn-default id=action-unsuballgtUnsub alllt

rarr˓buttongt32 ltdivgt33 ltdivgt34 ltdivgt35

36 ltscriptgt37

38 Receiver event handling39 $(log)on(msgnotify function(ev msg) 40 You normally should filter by typesubtype here eg41 if (subtypestartsWith(myapp)) 42 msg has type subtype and value43 Dump the msg into the receiver to show the structure44 $(this)text(JSONstringify(msg null 2))45

46 A convenient way to transport complex data is JSON47 To decode a JSON string use JSONparse()48 Note JSONparse() needs strict JSON syntax ie quoted names49 var payload50 try 51 payload = JSONparse(msgvalue)52 if (payload) 53 $(this)append(ltdivgtFound JSON payloadltdivgt)54 append($(ltdiv gt)text(JSONstringify(payload null 2))html())55 consolelog(payload)56 57 catch(e) 58 no JSON59 consolelog(e)60 61 )62

(continues on next page)

331 TLDR Examples 275

Open Vehicles

(continued from previous page)

63 Topic subscription can be done on page load using the data-subscriptions attribute64 andor on demand using the subscribe amp unsubscribe calls65 $(action-sub)on(click function(ev) 66 var topics = $(topics)val()67 $(log)subscribe(topics)text(added + topics)68 )69 The receiver remembers the subscriptions and does an auto unsubscribe on unload70 You can also unsubscribe topics dynamically Your data producer can check for71 active subscriptions using the MyNotifyHasReader() method72 $(action-unsub)on(click function(ev) 73 var topics = $(topics)val()74 $(log)unsubscribe(topics)text(removed + topics)75 )76 $(action-unsuball)on(click function(ev) 77 $(log)unsubscribe()text(removed all subscriptions)78 )79

80 Command handler81 $(action-exec)on(click function(ev) 82 var cmd = $(cmd)val()83 if (cmd) loadcmd(cmd cmdres)84 )85 $(cmd)on(keydown function(ev) 86 if (evwhich == 13) $(action-exec)trigger(click)87 )88

89 ltscriptgt

3314 Hook Plugins

hookshtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 --gt4

5 ltdiv class=panel panel-primarygt6 ltdiv class=panel-headinggtPage Hook Pluginsltdivgt7 ltdiv class=panel-bodygt8

9 ltpgtPlugins can provide pages on their own or extend existing pages To extend anrarr˓existing

10 page the page needs to support this by offering hook pointsltpgt11

12 ltpgtYou are not limited to the hook points for page modifications To insert yourrarr˓extensions

13 at arbitrary placesltpgt14 ltulgt15 ltligtinsert your extensions dynamically or with ltcodegtdisplaynoneltcodegtltligt16 ltligtregister a onetime handler for the ltcodegtloadltcodegt event on ltcodegtmainlt

rarr˓codegtltligt17 ltligtmove your extensions into place and show them from the event handlerltligt18 ltulgt19

20 ltpgtand yes youre also not limited to adding stuffltpgt(continues on next page)

276 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

21

22 lth3gtExamplelth3gt23

24 ltpgtThe following hook plugin adds a custom menu and some color to ltcodegthomeltcodegtrarr˓ltpgt

25

26 ltpre id=plugindisplay style=font-size85gtltpregt27

28 lth3gtAvailable Hookslth3gt29

30 ltpgtas of January 2019 This is work in progress if you miss a hook somewhererarr˓contact usltpgt

31

32 lttable class=table table-condensed font-monospacegt33 lttrgtltth colspan=2gtFrameworkltthgtlttrgt34 lttrgtlttdgt lttdgtlttdgthtmlpre headpost bodypost

rarr˓ lttdgtlttrgt35 lttrgtlttdgthome lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt36 lttrgtlttdgtdashboard lttdgtlttdgtbodypre

rarr˓ lttdgtlttrgt37 lttrgtlttdgtstatus lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt38 lttrgtlttdgtshell lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt39 lttrgtltth colspan=2gtRenault Twizyltthgtlttrgt40 lttrgtlttdgtxrtdrivemode lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt41 lttrgtlttdgtxrtscmon lttdgtlttdgtbodypre bodypost

rarr˓ lttdgtlttrgt42 lttablegt43

44 ltdivgt45 ltdivgt46

47 ltscriptgt48 (function()49 var pluginsrc = $(pluginsrc)html()50 $(plugindisplay)html(encode_html(pluginsrcsubstr(1)))51 )()52 ltscriptgt53

54 ltdiv id=pluginsrc style=displaynonegt55 lt--56 Hook plugin for homebodypre57 - custom coloring of menu titles58 - add custom menu Test Demo after Main59 --gt60

61 ltstylegt62 menu legend 63 color brown64 65 ltstylegt66

67 ltfieldset class=menu id=fieldset-menu-demo1 style=displaynonegt68 ltlegendgtTest Demoltlegendgt

(continues on next page)

331 TLDR Examples 277

Open Vehicles

(continued from previous page)

69 ltul class=list-inlinegt70 ltligtlta class=btn btn-default href=usrdemometrics target=maingtMetrics lt

rarr˓agtltligt71 ltligtlta class=btn btn-info href=logslog target=_blankgtOpen Log File ltagtlt

rarr˓ligt72 ltulgt73 ltfieldsetgt74

75 ltscriptgt76 $(main)one(load function(ev) 77 $(fieldset-menu-demo1)insertAfter(fieldset-menu-main)show()78 )79 ltscriptgt80 ltdivgt

3315 Solid Gauges

solidgaugehtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltstylegt6 solidgauge highcharts-yaxis-grid highcharts-grid-line7 solidgauge highcharts-yaxis-grid highcharts-minor-grid-line 8 display none9

10 solidgauge highcharts-pane 11 fill eee12 fill-opacity 113 stroke aaa14 stroke-width 2px15 16 night solidgauge highcharts-pane 17 fill b1b1b118 stroke b1b1b119 20 solidgauge highcharts-point 21 transition fill 500ms stroke 500ms see stops styles note 22 23 throttle-gauge highcharts-color-0 24 fill eee initial colors = pane for smooth fade in 25 stroke aaa26 fill-opacity 0827 stroke-width 3px28 stroke-opacity 0529 30 rpm-gauge highcharts-color-0 31 fill 55e32 stroke none33 34 ltstylegt35

36 ltdiv class=panel panel-primarygt

(continues on next page)

278 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

37 ltdiv class=panel-headinggtSolid Gaugeltdivgt38 ltdiv class=panel-bodygt39

40 ltdiv class=receivergt41

42 ltdiv class=rowgt43 ltdiv class=col-sm-6gt44 ltdiv class=metric chart data-metric=vethrottle style=height220pxgt45 ltdiv class=chart-box solidgauge id=throttle-gaugegt46 ltdivgt47 ltpgt48 Note stops dont work by default in styled mode This example includes a

rarr˓simple redraw49 event callback that applies styles from the stops To get a smooth color

rarr˓transition50 the CSS transition time needs to be equal to the chart animation time51 ltpgt52 ltdivgt53 ltdiv class=col-sm-6gt54 ltdiv class=metric chart data-metric=vmrpm style=height220pxgt55 ltdiv class=chart-box solidgauge gaugechart id=rpm-gaugegt56 ltdivgt57 ltpgt58 Note the ltcodegtgaugechartltcodegt CSS class pulls in the default styling

rarr˓for the bands59 labels and ticks here You can also copy those CSS rules from ltcodegtovms

rarr˓cssltcodegt60 and do your own styling61 ltpgt62 ltdivgt63 ltdivgt64

65 ltpgtltbutton type=button class=btn btn-default action-gendatagtGenerate randomrarr˓dataltbuttongtltpgt

66

67 ltdivgt68

69 ltdivgt70 ltdivgt71

72 ltscriptgt73 (function()74

75 Show page source 76 var pagesrc = $(main)html()77 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +78 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)79 $(action-showsrc)on(click function() 80 $(ltdivgt)dialog(81 title Source Code82 body ltpre style=font-size85 heightcalc(100vh - 230px)gt83 + encode_html(pagesrc) + ltpregt84 size lg85 )86 )87

(continues on next page)

331 TLDR Examples 279

Open Vehicles

(continued from previous page)

88 Init throttle gauge 89 $(throttle-gauge)chart(90 chart 91 type solidgauge92 spacing [0 0 0 0]93 margin [0 0 0 0]94 animation duration 500 easing easeOutExpo 95 events 96 Apply stops styles on redraw97 redraw function(ev) 98 var y = thisseries[0]yData[0] $pt = $(thisrenderTo)find(highcharts-

rarr˓point)99 $map(thisyAxis[0]stops function(stop) if (y gt= stop[0]) $pt

rarr˓css(stop[1]) )100 101 102 103 title text Throttle verticalAlign middle y 75 104 credits enabled false 105 tooltip enabled false 106 plotOptions 107 solidgauge dataLabels enabled false overshoot 1 108 109 pane [110 startAngle -90 endAngle 90 size 140 center [50 85]111 background innerRadius 60 outerRadius 100 shape arc 112 ]113 yAxis [114 title text 115 className throttle116 reversed false117 min 0 max 100118 stops [119 [0 fill afa stroke 4f4 ]120 [50 fill ffa stroke ff4 ]121 [80 fill faa stroke f44 ]122 ]123 tickPixelInterval 40 tickPosition inside tickLength 13124 labels step 2 distance 10 x 0 y 0 zIndex 2 125 ]126 series [127 name Throttle data [40]128 className throttle129 animation duration 0 130 ]131 Update method 132 onUpdate function(update) 133 Create gauge data set from metric134 var data = [ metrics[vethrottle] ]135 Update chart136 thisseries[0]setData(data)137 138 )139

140 Init rpm gauge 141 $(rpm-gauge)chart(142 chart

(continues on next page)

280 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

143 type solidgauge144 spacing [0 0 0 0]145 margin [0 0 0 0]146 animation duration 500 easing easeOutExpo 147 148 title text RPM verticalAlign middle y 75 149 credits enabled false 150 tooltip enabled false 151 plotOptions 152 solidgauge dataLabels enabled false overshoot 1 153 154 pane [155 startAngle -90 endAngle 90 size 140 center [50 85]156 background innerRadius 70 outerRadius 100 shape arc 157 ]158 yAxis [159 title text rpm 160 className rpm161 reversed false162 min 0 max 11000163 plotBands [164 from 0 to 7000 className green-band 165 from 7000 to 9000 className yellow-band 166 from 9000 to 11000 className red-band 167 ]168 minorTickInterval auto minorTickLength 5 minorTickPosition inside169 tickPixelInterval 40 tickPosition inside tickLength 10170 labels step 2 distance 10 x 0 y 0 zIndex 2 171 ]172 series [173 name RPM data [4500]174 className rpm175 animation duration 0 176 innerRadius 72177 radius 92178 ]179 Update method 180 onUpdate function(update) 181 Create gauge data set from metric182 var data = [ metrics[vmrpm] ]183 Update chart184 thisseries[0]setData(data)185 186 )187

188 Test metrics generator 189 $(action-gendata)on(click function() 190 var td = 191 td[vethrottle] = Mathrandom() 100192 td[vmrpm] = Mathrandom() 11000193 $(receiver)trigger(msgmetrics $extend(metrics td))194 )195

196 )()197 ltscriptgt

331 TLDR Examples 281

Open Vehicles

3316 Command Streaming

loadcmdhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltdiv class=panel panel-primarygt6 ltdiv class=panel-headinggtAsynchronous Command Streamingltdivgt7 ltdiv class=panel-bodygt8

9 lth3gtSynopsislth3gt10

11 ltp class=leadgtltcodegt[jqxhr=] loadcmd(command [target] [filter] [timeout])ltrarr˓codegtltpgt

12

13 ltpgtThe ltcodegtloadcmd()ltcodegt function executes a shell command or evaluatesrarr˓javascript

14 code with asynchronous streaming of the output into a target element or onto ararr˓functionltpgt

15

16

17 lth3gtBasic Usagelth3gt18

19 ltpgtAs this is the underlying function for command buttons basic usage20 is very similar but fully scriptableltpgt21

22 ltpgt23 ltbutton type=button class=btn btn-default onclick=loadcmd(boot status

rarr˓out1)gt24 Show boot status25 ltbuttongt26 ltpgt27 ltpre id=out1 gt28

29 ltpgtAs with command buttons you can append the output by prefixing the target30 selector with + You can omit the output by passing null as the target If

rarr˓target31 is a DOM element loadcmd automatically sets the ltcodegtloadingltcodegt class on

rarr˓the32 target while the command is processedltpgt33

34 ltpgtThe target elements min-height is automatically fixed to the current height35 of the target before the output is set This avoids page layout jumps when36 reusing a target for commandsltpgt37

38 ltpgtIf the target is scrollable and the content exceeds the visible area the39 element is automatically scrolled to show the new content unless the user has40 done a manual scrolling on the elementltpgt41

42 ltpgtIf the command output stops for ltcodegttimeoutltcodegt seconds the request is43 aborted and a timeout error is shown Default timeout is 20 seconds for standard44 commands 300 seconds for known long running commandsltpgt45

46

47 lth3gtEvaluate Javascript Codelth3gt48

(continues on next page)

282 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

49 ltpgtTo execute Javascript either pass an object instead of the ltcodegtcommandltrarr˓codegt string

50 containing the command as property command and a second property type with51 value js or simply use the wrapper call ltcodegtloadjs()ltcodegt Exampleltpgt52

53 ltpgt54 ltbutton type=button class=btn btn-default55 onclick=loadjs(print(OvmsVehicleType()) out1js)gt56 Show vehicle type57 ltbuttongt58 ltpgt59 ltpre id=out1js gt60

61 ltpgtJavascript evaluation is not limited to a single command or line Hint torarr˓avoid

62 encoding complex JS code in the onclick attribute store the code in some hidden63 DOM element and read it via ltcodegt$()text()ltcodegtltpgt64

65

66 lth3gtOutput Encoding ampamp Binary Streamslth3gt67

68 ltpgtTo allow binary data to be sent by a command and to enable processing of the69 result by Javascript on the browser without character encoding issues the

rarr˓command70 API supports output binary modeltpgt71

72 ltpgtPrimary application for this is exchanging CBOR encoded objects between the73 module and the web frontend To fully support this the OVMS web frontent

rarr˓includes74 the CBOR library by Patrick Gansterer Example useltpgt75

76 ltpregt77 loadjs( command auxbatmondump(CBOR) output binary )done((data) =gt 78 history = CBORdecode(data)79 )80 ltpregt81

82 ltpgtSee the AuxBatMon and PwrMon OVMS plugins for full examplesltpgt83

84 ltpgtltcodegtoutputltcodegt modes supported by the command API areltpgt85

86 ltulgt87 ltligtltcodegttextltcodegt rarr Content-Type textplain charset=utf-8ltligt88 ltligtltcodegtjsonltcodegt rarr Content-Type applicationjson charset=utf-8ltligt89 ltligtltcodegtbinaryltcodegt rarr Content-Type applicationoctet-stream charset=x-

rarr˓user-definedltligt90 ltligtdefaultother rarr Content-Type applicationoctet-stream charset=utf-8ltligt91 ltulgt92

93

94 lth3gtjqXHR Objectlth3gt95

96 ltpgtltcodegtloadcmd()ltcodegt returns the jqXHR (XMLHttpRequest) object in charge for97 the asynchronous execution of the request This can be used to track the results98 of the execution check for errors or to abort the commandltpgt99

100 ltpgt(continues on next page)

331 TLDR Examples 283

Open Vehicles

(continued from previous page)

101 ltbutton type=button class=btn btn-default id=startcggtStart chargenltrarr˓buttongt

102 ltbutton type=button class=btn btn-default id=abortcg disabledgtAbortrarr˓chargenltbuttongt

103 ltpgt104 ltpre id=out2 style=max-height200px overflowauto gt105

106 ltpgtThe jQuery XHR object is also a thenable so actions to be performed after107 the command execution can simply be chained to the object Exampleltpgt108

109 ltpgtltbutton type=button class=btn btn-default id=showstatgtShow statltbuttongtrarr˓ltpgt

110

111 ltpgtSee lta target=_blank href=httpapijquerycomjQueryajaxjqXHRgtjQuery112 documentationltagt for full details and optionsltpgt113

114

115 lth3gtFilter Process Outputlth3gt116

117 ltpgtSupply a filter function to hook into the asynchronous output stream Userarr˓filters

118 to filter (ahem) preprocess reformat the command output scan the streamrarr˓for some

119 info youd like to know as soon as possible or completely take over the output120 processingltpgt121

122 ltpgtThe filter function is called when a new chunk of output has arrived or when123 a stream error has occurred The function gets a message object containing124 the ltcodegtrequestltcodegt object and either a ltcodegttextltcodegt for normal

rarr˓outputs125 or an ltcodegterrorltcodegt which is a preformatted error output you can use or126 ignoreltpgt127

128 ltpgtIf the filter function returns a string that will be added to the outputrarr˓target

129 If it returns ltcodegtnullltcodegt the target will remain untouchedltpgt130

131 ltpgtHint if you just want to scan the text for some info you can pass on therarr˓message

132 after your scan to the default ltcodegtstandardTextFilter()ltcodegtltpgt133

134 ltpgtExample lets reformat a ltcodegtcan statusltcodegt dump into a nice Bootstraprarr˓tableltpgt

135

136 ltpgtltbutton type=button class=btn btn-default id=canstatusgtCAN1 statusltrarr˓buttongtltpgt

137

138 lttable class=table table-condensed table-border table-striped table-hover id=rarr˓canoutgt

139 lttheadgt140 lttrgtltth class=col-xs-6gtKeyltthgtltth class=col-xs-6gtValueltthgtlttrgt141 lttheadgt142 lttbodygt143 lttablegt144

145 ltdivgt146 ltdivgt

(continues on next page)

284 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

147

148 ltscriptgt149 (function()150

151 Show page source 152 var pagesrc = $(main)html()153 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +154 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)155 $(action-showsrc)on(click function() 156 $(ltdivgt)dialog(157 title Source Code158 body ltpre style=font-size85 heightcalc(100vh - 230px)gt159 + encode_html(pagesrc) + ltpregt160 size lg161 )162 )163

164 Example jqXHRabort() 165 var xhr166 $(startcg)on(click function() 167 xhr = loadcmd(test chargen 20 600 out2)168 $(abortcg)prop(disabled false)169 )170 $(abortcg)on(click function() 171 xhrabort()172 )173

174 Example jqXHRthen() 175 $(showstat)on(click function() 176 loadcmd(stat)then(function(output) 177 confirmdialog(STAT result ltsampgt + output + ltsampgt [Close])178 )179 )180

181 Example filter output processor 182 $(canstatus)on(click function() 183 var $table = $(canout gt tbody)184 var buf = 185 $tableempty()186 loadcmd(can can1 status function(msg) 187 if (msgerror) 188 Render error into table row189 $(lttr class=dangergtlttd colspan=2gt + msgerror + lttdgtlttrgt)appendTo(

rarr˓$table)190 191 else if (msgtext) 192 As this is a stream the text chunks received need not be single or

rarr˓complete lines193 Were interested in lines here so we buffer the chunks and split the

rarr˓buffer at n194 buf += msgtext195 var lines = bufsplit(n)196 if (lineslength gt 1) 197 buf = lines[lineslength-1]198 for (var i = 0 i lt lineslength-1 i++) 199 Skip empty lines

(continues on next page)

331 TLDR Examples 285

Open Vehicles

(continued from previous page)

200 if (lines[i] == ) continue201 Split line into columns202 var col = lines[i]split( +)203 Create table row amp append to table add some color on error counters204 if (col[0]match([Ee]rr))205 $(lttr class=warninggtltthgt + col[0] + ltthgtlttdgt + col[1] + lttdgtlt

rarr˓trgt)appendTo($table)206 else207 $(lttrgtltthgt + col[0] + ltthgtlttdgt + col[1] + lttdgtlttrgt)appendTo(

rarr˓$table)208 209 210 211 Filter has handled everything212 return null213 )214 )215

216 )()217 ltscriptgt

3317 File API

The file API enables web clients to read and write files at arbitrary VFS locations

bull API URL apifile

bull Methods

ndash GET ndash read file

ndash POST ndash write file

bull Parameters

ndash path ndash the full path to the file

ndash content ndash the new file content on POST

bull Output

ndash HTTP status 200 (OK) or 400 (Error)

ndash HTTP body file content on GET or error message

On writing missing directories along the path will be created automatically

Usage Example

The API can be accessed easily in the web frontend with the jQuery AJAX methods

Write object JSON encoded into filevar json = JSONstringify(object)$post(apifile path sdmystorefile1 content json )

done(function() confirmdialog(Saved ltpgtFile has been savedltpgt [OK] 2)

)fail(function(jqXHR)

(continues on next page)

286 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

confirmdialog(Save failed jqXHRresponseText [OK]))

Read JSON encoded object from file$get(apifile path sdmystorefile1 )

done(function(responseText) var object = JSONparse(responseText) process object

)fail(function(jqXHR) confirmdialog(Load failed jqXHRresponseText [OK])

)

External Access

From external clients the API can be used by either registering a session cookie or by supplying the apikey param-eter (as explained in the general authorization overview)

Read example

curl http19216841apifileapikey=passwordamppath=sdmystorefile1

Write example

curl http19216841apifile -d apikey=password -d path=sdmystorefile1 --data-urlencode contentlocalfile

3318 Longtouch Buttons

btn-longtouchhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web dir eg scp testpagehtm test1localsddev5 - open in framework by eg httptest1localdevtestpagehtm6 --gt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtLongtouch Buttonsltdivgt

10 ltdiv class=panel-bodygt11

12 ltpgtNote open this test page with a mobile touch screen device or simulate13 a mobile device using the web debugger of your browserltpgt14

15 ltpgtThe buttons below should work normally on a non-touch deviceltpgt16

17 ltpgtOn a touch screen device touching the buttons starts a countdown18 of 15 seconds showing an overlay with a progress bar and giving vibration19 signals (on devices supporting this) The button action is triggered only20 after the countdown has finished while holding the touchltpgt21

22 ltpgtThis feature is meant to a) secure certain buttons against unintentionalrarr˓activation

(continues on next page)

331 TLDR Examples 287

Open Vehicles

(continued from previous page)

23 and to b) allow secure usage of these buttons while driving ie when the mobilerarr˓phone

24 tablet is mounted to a car holderltpgt25

26 ltpgtStandard candidates for this are buttons triggering deep modifications ie27 changing the car tuning or drive modeltpgt28

29 ltpgtTo activate the feature on a button simply add the class ltcodegtbtn-longtouchltrarr˓codegt to the button

30 To activate it on a group of buttons add the class to the container of therarr˓buttonsltpgt

31

32 ltpgtThe progress overlay shows the button title if set (HTML supported) else therarr˓button textltpgt

33

34 ltform action=gt35 ltdiv class=btn-group btn-group-justified btn-longtouchgt36 ltdiv class=btn-group btn-group-lggt37 ltbutton type=submit name=load value=0 id=prof-0 class=btn btn-

rarr˓defaultgtltstronggtSTDltstronggtltbuttongt38 ltdivgt39 ltdiv class=btn-group btn-group-lggt40 ltbutton type=submit name=load value=1 id=prof-1 class=btn btn-

rarr˓default title=Power ModegtltstronggtPWRltstronggtltbuttongt41 ltdivgt42 ltdiv class=btn-group btn-group-lggt43 ltbutton type=submit name=load value=2 id=prof-2 class=btn btn-

rarr˓successgtltstronggtECOltstronggtltbuttongt44 ltdivgt45 ltdiv class=btn-group btn-group-lggt46 ltbutton type=submit name=load value=3 id=prof-3 class=btn btn-

rarr˓default title=Winter ModegtltstronggtICEltstronggtltbuttongt47 ltdivgt48 ltdivgt49 ltformgt50

51 ltdivgt52 ltdivgt

3319 Basic Dialogs

dialogtesthtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web dir eg scp testpagehtm test1localsddev5 - open in framework by eg httptest1localdevtestpagehtm6 --gt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtDialog TestDemoltdivgt

10 ltdiv class=panel-bodygt11 lth4gtCore Widgetlth4gt12 ltbutton class=btn btn-default id=action-loadgtDialog 1ltbuttongt

(continues on next page)

288 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

13 ltbutton class=btn btn-default id=action-savegtDialog 2ltbuttongt14 ltbutton class=btn btn-default id=action-bothgtBoth togetherltbuttongt15 ltbutton class=btn btn-default id=action-dyngtDynamic customltbuttongt16 lthr gt17 lth4gtUtility Wrapperslth4gt18 ltbutton class=btn btn-default id=action-infogtAlertltbuttongt19 ltbutton class=btn btn-default id=action-confirmgtConfirmltbuttongt20 ltbutton class=btn btn-default id=action-choicegtChoiceltbuttongt21 ltbutton class=btn btn-default id=action-promptgtPromptltbuttongt22 ltbutton class=btn btn-default id=action-passwordgtPasswordltbuttongt23 lthr gt24 lth4gtLoglth4gt25 ltpre id=log gt26 ltdivgt27 ltdivgt28

29 ltdiv id=dialog1 gt30 ltdiv id=dialog2 gt31 ltdiv id=dialog3 gt32

33 ltscriptgt34

35 rarr˓=======================================================================================

36 Dialog core widget37 options 38 title 39 body 40 show false true = open directly on init41 remote false42 backdrop true background overlay43 keyboard true ESC = close44 transition fade 45 size sm lg46 contentClass added to modal-content47 onShown null function(input)48 onHidden null function(input)49 onShow null function(input)50 onHide null function(input)51 onUpdate null function(input)52 buttons [] see example53 timeout 0 in seconds54 input null predefinedshared input object to use55 56

57 Note use static dialogs (attached to the document) for speed and to store reusable58 input eg for a promptdialog59

60 The default dialog will contain just a Close button61 $(dialog1)dialog(62 title Please note63 body ltpgtThis is just a testltpgt64 )65 $(dialog2)dialog(66 title Alert67 body ltpgtDanger Will Robinson dangerltpgt68 contentClass alert-danger note looks strange just an example -- dont use

(continues on next page)

331 TLDR Examples 289

Open Vehicles

(continued from previous page)

69 )70

71 You can simply open preconfigured dialogs like this72 $(action-load)on(click function()73 $(dialog1)dialog(show)74 )75 $(action-save)on(click function()76 $(dialog2)dialog(show)77 )78

79 or you can reconfigure dialogs on the fly like this80 Note the new configuration is stored in the dialog81 $(action-both)on(click function()82 $(dialog1)dialog(show body ltpgtThis is now another testltpgt )83 This example also opens a second dialog on top of the first84 $(dialog2)dialog(show body ltpgtThis is a second layer dialogltpgt )85 )86

87 Use dynamic dialogs for single shot purposes88 $(action-dyn)on(click function()89 $(log)text()90 $(ltdiv gt)dialog(91 title Dynamic92 body ltpgtdialog with custom buttonsltpgt93 buttons [94 Buttons default to auto hiding the dialog95 label Nope 96 You can get the button clicked in the onHidden callback or you can97 add specific action callbacks to each button98 label Maybe btnClass warning autoHide false action

rarr˓function(input) 99 input is the data container of the widget with only predefined

100 member being button = the button clicked (or null)101 You can use this container for custom extensions102 inputclicked_maybe = true103 $(this)find(modal-body)append(ltpgtYoure now a maybe personltpgt)104 105 autoHide callbacks are called on the hidden event so a fade out106 is guaranteed to be finished in the callback107 label Done btnClass primary action function(input) 108 $(log)text(JSONstringify(input null 2))109 110 ]111 )112 )113

114

115 rarr˓=======================================================================================

116 Dialog utility wrappers117 confirmdialog(title body buttons [callback] timeout)118 promptdialog(type title body buttons callback)119 Both can be used plugin style or standalone for dynamic dialogs120

121 Dynamic alert() style dialog with 5 seconds timeout122 $(action-info)on(click function()123 confirmdialog(Sorry Im afraid I cant do that Dave [OK] 5)

(continues on next page)

290 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

124 Note you can also add a callback here to know when the dialog is dismissed125 )126

127 Dynamic confirm() style dialog128 $(action-confirm)on(click function()129 $(log)text()130 confirmdialog(Load file Discard unsaved changes [No Yes]

rarr˓function(confirmed)131 if (confirmed)132 $(log)text(Loading now)133 else134 $(log)text(Load aborted)135 )136 )137

138 The callback argument is the index of the button clicked (or null) so139 simple choice dialogs can be done like this140 $(action-choice)on(click function()141 $(log)text()142 confirmdialog(Select Please select the slot to use [1 2 3 4]

rarr˓function(button)143 if (button = null)144 $(log)text(Using slot + (button+1))145 else146 $(log)text(Abort)147 )148 )149

150 Static prompt() style text input dialog (with dialog3 keeping the dialog)151 $(action-prompt)on(click function()152 $(log)text()153 $(dialog3)promptdialog(text Save data Please enter file name [Cancel

rarr˓ Save] function(button input)154 if (button ampamp input)155 $(log)text(Saving to file + input)156 else157 $(log)text(Save aborted)158 )159 )160

161 All single field HTML5 input types can be used162 $(action-password)on(click function()163 $(log)text()164 promptdialog(password Authentication Please enter PIN [Cancel Continue

rarr˓] function(button input)165 if (button ampamp input)166 $(log)text(PIN entered + input)167 else168 $(log)text(Auth aborted)169 )170 )171

172 ltscriptgt

331 TLDR Examples 291

Open Vehicles

33110 File Dialogs

filedialoghtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web file path eg sddevfiledialoghtm5 - open in framework by eg httptest1localdevfiledialoghtm6 --gt7

8 ltdiv class=filedialog id=fileselectgt9

10 ltdiv class=panel panel-primarygt11 ltdiv class=panel-headinggtFileDialog Testltdivgt12 ltdiv class=panel-bodygt13

14 lth2gtDynamic APIlth2gt15

16 ltpgt17 ltbutton class=btn btn-default id=action-loadgtLoadltbuttongt18 ltbutton class=btn btn-default id=action-savegtSaveltbuttongt19 ltpgt20 ltpre id=loggt21

22 lth2gtData APIlth2gt23

24 ltdiv class=input-groupgt25 ltinput type=text class=form-control font-monospace placeholder=Enter file

rarr˓name26 name=filename id=input-filename value= autocapitalize=none

rarr˓autocorrect=off27 autocomplete=section-demo spellcheck=falsegt28 ltdiv class=input-group-btngt29 lt-- use data-toggle=filedialog data-target amp data-input on the button --gt30 ltbutton type=button class=btn btn-default data-toggle=filedialog data-

rarr˓target=fd-api data-input=input-filenamegtSelectltbuttongt31 ltdivgt32 ltdivgt33

34 lt-- This is the file dialog triggered by the button --gt35 ltdiv class=filedialog id=fd-api data-options=36 title This is a data API dialog37 path sdfoo38 quicknav [sd sdfoo sdbar]39 gt40 lt-- thats it no JS code necessary41 Note JSON syntax needs to be strict here see JS console for errors42 --gt43

44 ltdivgt45 ltdivgt46

47 ltscriptgt48

49 rarr˓=======================================================================================

50 FileDialog is a Dialog with an embedded FileBrowser

(continues on next page)

292 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

51 52 The input object combines the dialog button and the file browser data53 54 Options55 title Select file -- dialog title56 submit Select -- label of submit button57 select f -- f = only files selectable (default) d

rarr˓ = only directories58 onSubmit null -- callback function(input)59 onCancel null -- callback function(input)60 61 inherited from FileBrowser62 path 63 quicknav [sd store]64 filter null65 sortBy null66 sortDir 167 68 inherited from Dialog69 backdrop true70 keyboard true71 transition fade72 size lg73 onUpdate null74 75

76 Init dialog77 $(fileselect)filedialog(78 path storescripts79 quicknav [storescripts storeevents storeobd2ecu]80 )81

82 $(action-load)on(click function()83 $(log)empty()84 $(fileselect)filedialog(show 85 title Load Script86 submit Load87 onSubmit function(input) 88 This is called when the user doubleclicks an entry or presses Enter in a

rarr˓directory89 Note you need to check if inputfile is valid (empty = directory selected)90 if (inputfile)91 $(log)text(Loading + inputpath + n)92 else93 $(log)text(Directory selection + inputpath + n)94 95 onCancel function(input) 96 This is called when the user cancels or closes the dialog97 $(log)text(Load cancelledn)98 99 )

100 )101

102 $(action-save)on(click function()103 $(log)empty()104 $(fileselect)filedialog(show 105 title Save Script

(continues on next page)

331 TLDR Examples 293

Open Vehicles

(continued from previous page)

106 submit Save107 onSubmit function(input) 108 if (inputfile)109 $(log)text(Saving + inputpath + n)110 else111 $(log)text(Directory selection + inputpath + n)112 113 onCancel function(input) 114 $(log)text(Save cancelledn)115 116 )117 )118

119 ltscriptgt

33111 File Browser Widget

filebrowserhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page3 - enable web server file access4 - upload to web file path eg sddevfilebrowserhtm5 - open in framework by eg httptest1localdevfilebrowserhtm6 --gt7

8 ltstylegt9 Note set height or min-height on the filebrowser tbody

10 Default height by class filebrowser is 310px (each file row has a height of 31pxrarr˓with the default font size)

11 myfilebrowser tbody 12 height 35vh13 14 ltstylegt15

16 ltdiv class=panel panel-primarygt17 ltdiv class=panel-headinggtFileBrowser TestDemoltdivgt18 ltdiv class=panel-bodygt19

20 ltdiv class=filebrowser id=myfilebrowser gt21

22 lthrgt23 ltpre id=loggt24 ltbutton type=button class=btn btn-default id=action-setpathgtSet path to sd

rarr˓logslogltbuttongt25 ltbutton type=button class=btn btn-default id=action-stoploadgtStop loading

rarr˓dirltbuttongt26 ltbutton type=button class=btn btn-default id=action-filterongtFilter ziplt

rarr˓buttongt27 ltbutton type=button class=btn btn-default id=action-filteroffgtFilter offlt

rarr˓buttongt28 ltbutton type=button class=btn btn-default id=action-sortoffgtSort offlt

rarr˓buttongt29 ltpgtNote the test widget is configured to stopinhibit loading on selection of a

rarr˓txt file or a directory matching DCIMltpgt(continues on next page)

294 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

30 ltdivgt31 ltdivgt32

33 ltscriptgt34

35 rarr˓=======================================================================================

36 FileBrowser Widget37 38 Testdemo of init with all options39 Note you can init a filebrowser without any options40 Defaults are path amp quicknav as shown below no sorting no callbacks41 42 The input object passed to all callbacks contains these fields43 - path -- the full path (dir + + file)44 - file -- the file part of the currently selected path45 - dir -- the directory part of the currently selected path46 - noload -- set to true to inhibit directory loading (see onPathChange)47 48 Note path file amp dir are unvalidated user input49 50 Note on sorting disabling initial sorting improves user interaction while loading

rarr˓the51 directory ie to select filesdirs while the loader is running This may52 be an option especially for large directories The user can still sort manually53 54 Methods55 - getInput() -- retrieve input object56 - setPath(newpath reload) -- add trailing slash to enter dir wo file

rarr˓selection57 - sortList(by dir) -- sort file list58 - loadDir() -- trigger directory reload59 - stopLoad() -- abort directory loading60 - newDir() -- open create directory sub dialog61 62

63 $(myfilebrowser)filebrowser(64 path sd65 quicknav [sd store]66 filter null see Filter examples below67 sortBy name or size or date or null (disable)68 sortDir 1 or -1 for reverse69 onUpdate function(input) 70 This is called after any widget configuration update use for custom

rarr˓extensions71 $(log)append(onUpdate + JSONstringify(input) + n)72 73 onPathChange function(input) 74 Called whenever the path changes75 $(log)append(onPathChange + JSONstringify(input) + n)76 To inhibit loading the directory for the new path set inputnoload to true77 if (inputdirindexOf(DCIM) gt= 0 || inputfileindexOf(txt) gt= 0) 78 $(log)append(inhibiting directory loadingn)79 inputnoload = true80 81 82 onAction function(input)

(continues on next page)

331 TLDR Examples 295

Open Vehicles

(continued from previous page)

83 This is called when the user doubleclicks an entry or presses Enter in ararr˓directory

84 $(log)append(onAction + JSONstringify(input) + n)85 86 )87

88 $(action-setpath)on(click function(ev) 89 $(myfilebrowser)filebrowser(setPath sdlogslog true)90 )91 $(action-stopload)on(click function(ev) 92 $(myfilebrowser)filebrowser(stopLoad)93 )94 $(action-sortoff)on(click function(ev) 95 $(myfilebrowser)filebrowser(sortList )96 )97

98 Filter example99 $(action-filteron)on(click function(ev)

100 $(myfilebrowser)filebrowser(101 The list filter may be given as a string (regular expression applied to file

rarr˓name)102 filter zip$103 A string filter always lists directories104

105 For advanced usage you may alternatively specify a filter callback like this106 filter function(f) return fisdir || fnamematch(zip$) 107 The function is called per list entry object with108 - isdir true = is sub directory109 - name the name part (file or directory dir with trailing )110 - path the full path of this entry111 - size formatted size (68k)112 - date formatted date (23-Nov-2018 1742)113 - bytes size in bytes -1 for directories114 - isodate ISO style date YYYY-mm-dd HHMM115 - class can be used to add a custom row class116 Return true to allow the entry to be added to the list117

118 Note list filters do not restrict the allowed path input To do so119 register onPathChange or onAction and check the input in your callback120 See FileDialog widget select option handling for an example121 )122 )123 $(action-filteroff)on(click function(ev) 124 $(myfilebrowser)filebrowser(125 filter null126 )127 )128

129 ltscriptgt

33112 Slider Widget

input-sliderhtm (hint right click save as)

296 Chapter 33 Web Framework amp Plugins

Open Vehicles

1 ltstylegt2 Align multiple slider inputs by suitably fixing their value width 3 form-inline form-controlslider-value 4 width 80px5 6 ltstylegt7

8 ltdiv class=panel panel-primarygt9 ltdiv class=panel-headinggtSlider Widgetltdivgt

10 ltdiv class=panel-bodygt11

12 lth3gtStandard Numerical Inputslth3gt13

14 ltpgtThe number input is just the bootstrap defaultltpgt15

16 ltinput class=form-control type=number id=input-num1 name=num1 value=80rarr˓min=0 max=100 step=1gt

17 ltbrgt18

19 ltpgtThe range input has some styling optimization for touch devicesltpgt20

21 ltinput class=form-control type=range id=input-rng1 name=rng1 value=80rarr˓min=0 max=100 step=1gt

22 ltbrgt23

24 lth3gtSlider Widgetlth3gt25

26 ltpgt27 In many cases youd like to give especially the touchscreen user a combination

rarr˓of these input28 elements and as sliding may be too imprecise you also need large buttons for

rarr˓single step changes29 Thats what the slider widget does It also adds the option of a checkbox and a

rarr˓default value to30 reflect if the user control shall be applied31 ltpgt32

33 ltdiv class=rowgt34 ltdiv class=col-md-9gt35

36 ltpgtSliders can easily be created from minimal markup using the ltcodegtslider()rarr˓ltcodegt plugin

37 with configuration given by data attributes andor dynamic optionsltpgt38

39 ltdiv class=form-control slider id=sld1 data-min=-5 data-max=50 data-rarr˓step=05

40 data-default=40 data-unit= data-disabled=false data-checked=truerarr˓data-value=10 gt

41 ltbrgt42

43 ltdiv class=form-control slider id=sld2 gt44 ltbrgt45

46 ltpgtand slider state limits and value can be controlled using the samerarr˓methodltbrgt

47 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(rarr˓value42 )gt

(continues on next page)

331 TLDR Examples 297

Open Vehicles

(continued from previous page)

48 Set sld1 value to 4249 ltbuttongt50 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(

rarr˓checkedtrue )gt51 Check sld152 ltbuttongt53 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(

rarr˓disabledtrue )gt54 Disable sld155 ltbuttongt56 ltbutton type=button class=btn btn-default onclick=$(sld1)slider(

rarr˓disabledfalse )gt57 Enable sld158 ltbuttongt59 ltpgt60 ltbrgt61

62 ltpgtIf you need even more control you can create the slider markup yourselfrarr˓as wellltpgt

63

64 ltdiv class=form-control slider id=sld3 data-default=50 data-reset=falserarr˓

65 data-value=80 data-min=-10 data-max=100 data-step=1gt66 ltdiv class=slider-control form-inlinegt67 ltinput class=slider-enable type=checkbox checkedgt68 ltinput class=form-control slider-value type=number id=input-sld3

rarr˓name=sld3gt69 ltspan class=slider-unitgtltspangt70 ltinput class=btn btn-default slider-down type=button value=gt71 ltinput class=btn btn-default slider-set type=button value=Lo data-

rarr˓set=25gt72 ltinput class=btn btn-default slider-set type=button value=Hi data-

rarr˓set=75gt73 ltinput class=btn btn-default slider-up type=button value=gt74 ltdivgt75 ltinput class=slider-input type=rangegt76 ltdivgt77 ltbrgt78

79 ltdivgt80 ltdiv class=col-md-3gt81

82 ltpgtltugtEvents ampamp valuesltugtltpgt83 ltpre id=show-sldevgtltpregt84

85 ltdivgt86 ltdivgt87

88 ltbrgt89

90 ltpgt91 Checkbox buttons and unit are optional You can reduce the widget to just a

rarr˓number or92 just a range input the input then needs to have the ltcodegtslider-inputltcodegt

rarr˓class93 ltpgt94

(continues on next page)

298 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

95 ltpgt96 The checkbox element defines the default value to be set on unchecking in97 ltcodegtdata-defaultltcodegt By default the checkbox will restore the previous

rarr˓user98 value when re-checked to disable this set ltcodegtdata-resetltcodegt to true99 To reset the value to the default from a script call the ltcodegtslider()ltcodegt

100 method with ltcodegtvalue nullltcodegt (this resets both the actual and the stored101 user value)102 ltpgt103

104 ltpgt105 Values and checkbox status need to be consistent on init or be set by your

rarr˓script106 To hook into value changes attach event handlers to events ltcodegtinputltcodegt107 andor ltcodegtchangeltcodegt as usual Read the ltcodegtcheckedltcodegt property to

rarr˓get the108 checkbox state109 ltpgt110

111 ltdivgt112 ltdivgt113

114 ltscriptgt115 (function()116

117 Show page source 118 var pagesrc = $(main)html()119 $(panel-heading)prepend(ltbutton type=button class=btn btn-sm btn-info

rarr˓action-showsrc +120 style=floatright positionrelative top-5pxgtShow page sourceltbuttongt)121 $(action-showsrc)on(click function() 122 $(ltdivgt)dialog(123 title Source Code124 body ltpre style=font-size85 heightcalc(100vh - 230px)gt125 + encode_html(pagesrc) + ltpregt126 size lg127 )128 )129

130 Init sliders 131 $(slider)slider()132 $(sld2)slider( min-10 max10 step01 default25 unitkW

rarr˓checkedfalse value-38 )133

134 Show slider events amp values 135 var sldev = 136 $(input-sld1 input-sld2 input-sld3)on(input change function(ev) 137 sldev[thisname] = $extend(sldev[thisname] checked thischecked )138 Note thisvalue is unvalidated here for a direct entry but the validation is

rarr˓simple139 sldev[thisname][evtype] = Mathmax(thismin Mathmin(thismax 1thisvalue))140 $(show-sldev)text(JSONstringify(sldev null 2))141 )142

143 )()144 ltscriptgt

331 TLDR Examples 299

Open Vehicles

33113 Regen Brake Monitor

This plugin defines a page including an acceleration level gauge chart number metrics for the acceleration speed andbattery power and two large indicators for the regen brake light and the brake pedal state

Itrsquos useful to fine tune the regen brake settings as you can monitor the actual deceleration levels while driving andcheck the smoothing level

Install add the source as a page plugin eg devregenmon

regenmonhtm (hint right click save as)

1 lt--2 TestDevelopmentDocumentation page install as plugin to test3 --gt4

5 ltstylegt6 indicator gt label 7 font-size 1508 line-height 2009 margin 10px

10 padding 10px11 display block12 border-radius 50px13 14 metricnumber label 15 min-width 8em16

(continues on next page)

300 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

17 metricnumber 18 display block19 float none20 text-align center21 22 ltstylegt23

24 ltdiv class=panel panel-primarygt25 ltdiv class=panel-headinggtRegen Brake Monitorltdivgt26 ltdiv class=panel-bodygt27

28 ltdiv class=receiver id=regenmon-receivergt29

30 ltdiv class=rowgt31 ltdiv class=col-sm-6gt32 ltdiv class=metric chart data-metric=vpacceleration style=height300px

rarr˓gt33 ltdiv class=chart-box gaugechart id=accel-gaugegt34 ltdivgt35 ltdiv class=metric number data-metric=vpacceleration data-prec=2gt36 ltspan class=labelgtAccelerationltspangt37 ltspan class=valuegtltspangt38 ltspan class=unitgtms2ltspangt39 ltdivgt40 ltdiv class=metric number data-metric=vpspeed data-prec=1gt41 ltspan class=labelgtSpeedltspangt42 ltspan class=valuegtltspangt43 ltspan class=unitgtkphltspangt44 ltdivgt45 ltdiv class=metric number data-metric=vbpower data-prec=1gt46 ltspan class=labelgtBattery powerltspangt47 ltspan class=valuegtltspangt48 ltspan class=unitgtkWltspangt49 ltdivgt50 ltbr class=clearfixgt51 ltdivgt52 ltdiv class=col-sm-6gt53 ltdiv class=indicator data-metric=veregenbrakegt54 ltspan class=label label-defaultgtREGENltspangt55 ltdivgt56 ltdiv class=indicator data-metric=vefootbrakegt57 ltspan class=label label-defaultgtFOOTltspangt58 ltdivgt59 ltdivgt60 ltdivgt61

62 ltdivgt63

64 ltdivgt65 ltdivgt66

67 ltscriptgt68 (function()69

70 Init acceleration gauge 71 $(accel-gauge)chart(72 chart

(continues on next page)

331 TLDR Examples 301

Open Vehicles

(continued from previous page)

73 type gauge74 spacing [0 0 0 0]75 margin [0 0 0 0]76 animation duration 250 easing easeOutExpo 77 78 title text Acceleration verticalAlign middle y 75 79 credits enabled false 80 tooltip enabled false 81 plotOptions 82 gauge dataLabels enabled false overshoot 5 83 84 pane [85 startAngle -120 endAngle 120 size 100 center [50 60]86 ]87 yAxis [88 title text ms2 89 className accel90 reversed false91 min -2 max 292 minorTickInterval 01 minorTickLength 5 minorTickPosition inside93 tickInterval 05 tickPosition inside tickLength 1394 labels step 1 distance -28 x 0 y 5 zIndex 2 95 ]96 series [97 name Acceleration data [0]98 className accel99 animation duration 0

100 pivot radius 10 101 dial radius 88 topWidth 1 baseLength 20 baseWidth 10

rarr˓rearLength 20 102 ]103 Update method 104 onUpdate function(update) 105 Create gauge data set from metric106 var data = [ metrics[vpacceleration] ]107 Update chart108 thisseries[0]setData(data)109 110 )111

112 Init indicators 113 $(regenmon-receiver)on(msgmetrics function(e update) 114 $(this)find(indicator)each(function() 115 var $el = $(this) metric = $eldata(metric) val = update[metric]116 if (val == null)117 return118 else if (val = 0)119 $elchildren()removeClass(label-default)addClass(label-danger)120 else if (val == 0)121 $elchildren()removeClass(label-danger)addClass(label-default)122 )123 )124

125 )()126 ltscriptgt

302 Chapter 33 Web Framework amp Plugins

Open Vehicles

33114 Dashboard

A refined and configurable version of this plugin has been added to the standard OVMS web UI and gets automaticallyconfigured by the vehicle modules with their respective vehicle parameters

Itrsquos a good example of the Highcharts gauge chart options and shows how to combine multiple gauge charts into asingle container (div gaugeset1) and how to style the charts using CSS

It also includes a simple test data generator so can be tested without actual vehicle data

To add a new vehicle parameter set for the standard dashboard simply override the GetDashboardConfig()method in your vehicle class Have a look at the existing overrides (for example Twizy Kia Soul Smart ED )

Install not necessary for the standard dashboard If yoursquore going to build your own dashboard from this install it asa page type plugin

dashboardhtm (hint right click save as)

1 lt-- Main --gt2

3 ltstylegt4 media (max-width 767px) 5 panel-single panel-body 6 padding 2px7 8 9 dashboard highcharts-data-label text

10 font-size 2em11 12 dashboard overlay 13 position absolute14 z-index 1015 top 6216 text-align center17 left 018 right 019 20 dashboard overlay value 21 color 04282b22 background 97b59723 padding 2px 5px

(continues on next page)

331 TLDR Examples 303

Open Vehicles

(continued from previous page)

24 margin-right 02em25 text-align center26 border 1px inset c3c3c38027 font-family Monaco Menlo Consolas QuickType Mono Lucida Console

rarr˓Roboto Mono Ubuntu Mono DejaVu Sans Mono Droid Sans Mono monospace28 display inline-block29 30 night dashboard overlay value 31 color fff32 background 25252533 34 dashboard overlay unit 35 color 66636 font-size 12px37 38 dashboard overlay range-value value 39 margin-left 10px40 width 100px41 42 dashboard overlay energy-value 43 margin-top 4px44 45 dashboard overlay energy-value value 46 margin-left 18px47 width 100px48 font-size 12px49 50 ltstylegt51

52 ltdiv class=panel panel-primary id=panel-dashboardgt53 ltdiv class=panel-headinggtDashboardltdivgt54 ltdiv class=panel-bodygt55

56 ltdiv class=receiver get-window-resize id=livestatusgt57 ltdiv class=dashboard style=position relative width 100 height 300px

rarr˓margin 0 autogt58 ltdiv class=overlaygt59 ltdiv class=range-valuegtltspan class=valuegt0 0ltspangtltspan class=unitgtkm

rarr˓ltspangtltdivgt60 ltdiv class=energy-valuegtltspan class=valuegt00 00ltspangtltspan class=

rarr˓unitgtkWhltspangtltdivgt61 ltdivgt62 ltdiv id=gaugeset1 style=width 100 height 100gtltdivgt63 ltdivgt64 ltdivgt65

66 ltdivgt67 ltdivgt68

69

70 lt-- Chart --gt71

72 ltstylegt73 highcharts-plot-band highcharts-pane 74 fill-opacity 075 76 highcharts-plot-bandborder

(continues on next page)

304 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

77 stroke 66666678 stroke-width 1px79 80

81 green-band 82 fill 55BF3B83 fill-opacity 0484 85 yellow-band 86 fill DDDF0D87 fill-opacity 0588 89 red-band 90 fill DF535391 fill-opacity 0692 93 violet-band 94 fill 9622ff95 fill-opacity 0696 97 night violet-band 98 fill 9622ff99 fill-opacity 08

100 101

102 highcharts-gauge-series highcharts-pivot 103 stroke-width 1px104 stroke 757575105 fill-opacity 1106 fill black107 108 highcharts-gauge-seriesauxgauge highcharts-pivot 109 fill-opacity 1110 fill fff111 stroke-width 0112 113 night highcharts-gauge-seriesauxgauge highcharts-pivot 114 fill 000115 116 highcharts-gauge-series highcharts-dial 117 fill d80000118 stroke 000119 stroke-width 05px120 121 highcharts-yaxis-grid highcharts-grid-line122 highcharts-yaxis-grid highcharts-minor-grid-line 123 display none124 125 highcharts-yaxis highcharts-tick 126 stroke-width 2px127 stroke 666666128 129 night highcharts-yaxis highcharts-tick 130 stroke e0e0e0131 132 highcharts-yaxis highcharts-minor-tick 133 stroke-width 18px

(continues on next page)

331 TLDR Examples 305

Open Vehicles

(continued from previous page)

134 stroke 00000085135 stroke-dasharray 6136 stroke-dashoffset -48137 stroke-linecap round138 139 night highcharts-yaxis highcharts-minor-tick 140 stroke ffffff85141 142 highcharts-axis-labels 143 fill 000144 font-weight bold145 font-size 09em146 147 night highcharts-axis-labels 148 fill ddd149 150 highcharts-data-label text 151 fill 333333152 153 night highcharts-data-label text 154 fill fff155 156

157 highcharts-axis-labelsspeed 158 font-size 12em159 160 ltstylegt161

162 ltscript type=textjavascriptgt163

164 Vehicle specific configuration165

166 var vehicle_config_twizy = 167 yAxis [168 Speed169 min 0 max 120170 plotBands [171 from 0 to 70 className green-band 172 from 70 to 100 className yellow-band 173 from 100 to 120 className red-band ]174 175 Voltage176 min 45 max 60177 plotBands [178 from 45 to 475 className red-band 179 from 475 to 50 className yellow-band 180 from 50 to 60 className green-band ]181 182 SOC183 min 0 max 100184 plotBands [185 from 0 to 125 className red-band 186 from 125 to 25 className yellow-band 187 from 25 to 100 className green-band ]188 189 Efficiency190 min 0 max 300

(continues on next page)

306 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

191 plotBands [192 from 0 to 150 className green-band 193 from 150 to 250 className yellow-band 194 from 250 to 300 className red-band ]195 196 Power197 min -10 max 30198 plotBands [199 from -10 to 0 className violet-band 200 from 0 to 15 className green-band 201 from 15 to 25 className yellow-band 202 from 25 to 30 className red-band ]203 204 Charger temperature205 min 20 max 80 tickInterval 20206 plotBands [207 from 20 to 65 className normal-band border 208 from 65 to 80 className red-band border ]209 210 Battery temperature211 min -15 max 65 tickInterval 25212 plotBands [213 from -15 to 0 className red-band border 214 from 0 to 50 className normal-band border 215 from 50 to 65 className red-band border ]216 217 Inverter temperature218 min 20 max 80 tickInterval 20219 plotBands [220 from 20 to 70 className normal-band border 221 from 70 to 80 className red-band border ]222 223 Motor temperature224 min 50 max 125 tickInterval 25225 plotBands [226 from 50 to 110 className normal-band border 227 from 110 to 125 className red-band border ]228 ]229 230

231 var vehicle_config_default = 232 yAxis [233 Speed234 min 0 max 120235 plotBands [236 from 0 to 70 className green-band 237 from 70 to 100 className yellow-band 238 from 100 to 120 className red-band ]239 240 Voltage241 min 310 max 410242 plotBands [243 from 310 to 325 className red-band 244 from 325 to 340 className yellow-band 245 from 340 to 410 className green-band ]246 247 SOC

(continues on next page)

331 TLDR Examples 307

Open Vehicles

(continued from previous page)

248 min 0 max 100249 plotBands [250 from 0 to 125 className red-band 251 from 125 to 25 className yellow-band 252 from 25 to 100 className green-band ]253 254 Efficiency255 min 0 max 400256 plotBands [257 from 0 to 200 className green-band 258 from 200 to 300 className yellow-band 259 from 300 to 400 className red-band ]260 261 Power262 min -50 max 200263 plotBands [264 from -50 to 0 className violet-band 265 from 0 to 100 className green-band 266 from 100 to 150 className yellow-band 267 from 150 to 200 className red-band ]268 269 Charger temperature270 min 20 max 80 tickInterval 20271 plotBands [272 from 20 to 65 className normal-band border 273 from 65 to 80 className red-band border ]274 275 Battery temperature276 min -15 max 65 tickInterval 25277 plotBands [278 from -15 to 0 className red-band border 279 from 0 to 50 className normal-band border 280 from 50 to 65 className red-band border ]281 282 Inverter temperature283 min 20 max 80 tickInterval 20284 plotBands [285 from 20 to 70 className normal-band border 286 from 70 to 80 className red-band border ]287 288 Motor temperature289 min 50 max 125 tickInterval 25290 plotBands [291 from 50 to 110 className normal-band border 292 from 110 to 125 className red-band border ]293 ]294 295

296 var vehicle_config = vehicle_config_twizy297

298 var gaugeset1299

300 function get_dashboard_data() 301 var rmin = metrics[vbrangeest]||0 rmax = metrics[vbrangeideal]||0302 var euse = metrics[vbenergyused]||0 erec = metrics[vbenergyrecd]||0303 if (rmin gt rmax) var x = rmin rmin = rmax rmax = x 304 var md =

(continues on next page)

308 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

305 range value + rmaxtoFixed(0) + + rmintoFixed(0) 306 energy value + eusetoFixed(1) + + erectoFixed(1) 307 series [308 data [metrics[vpspeed]] 309 data [metrics[vbvoltage]] 310 data [metrics[vbsoc]] 311 data [metrics[vbconsumption]] 312 data [metrics[vbpower]] 313 data [metrics[vctemp]] 314 data [metrics[vbtemp]] 315 data [metrics[vitemp]] 316 data [metrics[vmtemp]] ]317 318 return md319 320

321 function update_dashboard() 322 var md = get_dashboard_data()323 $(range-value value)text(mdrangevalue)324 $(energy-value value)text(mdenergyvalue)325 gaugeset1update( series mdseries )326 327

328 function init_gaugeset1() 329 var chart_config = 330 chart 331 type gauge332 spacing [0 0 0 0]333 margin [0 0 0 0]334 animation duration 0 easing swing 335 336 title text null 337 credits enabled false 338 tooltip enabled false 339

340 pane [341 startAngle -125 endAngle 125 center [50 45] size 80

rarr˓Speed342 startAngle 70 endAngle 110 center [-20 20] size 100

rarr˓Voltage343 startAngle 70 endAngle 110 center [-20 60] size 100 SOC344 startAngle -110 endAngle -70 center [120 20] size 100

rarr˓Efficiency345 startAngle -110 endAngle -70 center [120 60] size 100

rarr˓Power346 startAngle -45 endAngle 45 center [20 100] size 30

rarr˓Charger temperature347 startAngle -45 endAngle 45 center [40 100] size 30

rarr˓Battery temperature348 startAngle -45 endAngle 45 center [60 100] size 30

rarr˓Inverter temperature349 startAngle -45 endAngle 45 center [80 100] size 30 ]

rarr˓Motor temperature350

351 responsive 352 rules [353 condition minWidth 0 maxWidth 400

(continues on next page)

331 TLDR Examples 309

Open Vehicles

(continued from previous page)

354 chartOptions 355 pane [356 size 60 Speed357 center [-20 20] Voltage358 center [-20 60] SOC359 center [120 20] Efficiency360 center [120 60] Power361 center [15 100] size 25 Charger temperature362 center [3833 100] size 25 Battery temperature363 center [6166 100] size 25 Inverter temperature364 center [85 100] size 25 ] Motor temperature365 yAxis [ labels step 1 ] Speed366 367 368 condition minWidth 401 maxWidth 450 369 chartOptions 370 pane [371 size 70 Speed372 center [-15 20] Voltage373 center [-15 60] SOC374 center [115 20] Efficiency375 center [115 60] Power376 center [15 100] size 275 Charger temperature377 center [3833 100] size 275 Battery temperature378 center [6166 100] size 275 Inverter temperature379 center [85 100] size 275 ] Motor temperature380 381 382 condition minWidth 451 maxWidth 600 383 chartOptions 384 pane [385 size 80 Speed386 center [-10 20] Voltage387 center [-10 60] SOC388 center [110 20] Efficiency389 center [110 60] ] Power390 391 392 condition minWidth 601 393 chartOptions 394 pane [395 size 85 Speed396 center [0 20] Voltage397 center [0 60] SOC398 center [100 20] Efficiency399 center [100 60] ] Power400 401 ]402 403

404 yAxis [405 Speed axis406 pane 0 className speed title text kmh 407 reversed false408 minorTickInterval auto minorTickLength 5 minorTickPosition inside409 tickPixelInterval 30 tickPosition inside tickLength 13410 labels step 2 distance -28 x 0 y 5 zIndex 2

(continues on next page)

310 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

411 412 Voltage axis413 pane 1 className voltage title text Volt align low x 90 y

rarr˓35 414 reversed true415 minorTickInterval auto minorTickLength 5 minorTickPosition inside416 tickPixelInterval 30 tickPosition inside tickLength 13417 labels step 1 distance -25 x 0 y 5 zIndex 2 418 419 SOC axis420 pane 2 className soc title text SOC align low x 85 y 35 421 reversed true422 minorTickInterval auto minorTickLength 5 minorTickPosition inside423 tickPixelInterval 30 tickPosition inside tickLength 13424 labels step 1 distance -25 x 0 y 5 zIndex 2 425 426 Efficiency axis427 pane 3 className efficiency title text Whkm align low x -125

rarr˓ y 35 428 reversed false429 minorTickInterval auto minorTickLength 5 minorTickPosition inside430 tickPixelInterval 30 tickPosition inside tickLength 13431 labels step 1 distance -25 x 0 y 5 zIndex 2 432 433 Power axis434 pane 4 className power title text kW align low x -115 y 35

rarr˓435 reversed false436 minorTickInterval auto minorTickLength 5 minorTickPosition inside437 tickPixelInterval 30 tickPosition inside tickLength 13438 labels step 1 distance -25 x 0 y 5 zIndex 2 439 440 Charger temperature axis441 pane 5 className temp-charger title text CHG degC y 10 442 tickPosition inside tickLength 10 minorTickInterval null443 labels step 1 distance 3 x 0 y 0 zIndex 2 444 445 Battery temperature axis446 pane 6 className temp-battery title text BAT degC y 10 447 tickPosition inside tickLength 10 minorTickInterval null448 labels step 1 distance 3 x 0 y 0 zIndex 2 449 450 Inverter temperature axis451 pane 7 className temp-inverter title text PEM degC y 10 452 tickPosition inside tickLength 10 minorTickInterval null453 labels step 1 distance 3 x 0 y 0 zIndex 2 454 455 Motor temperature axis456 pane 8 className temp-motor title text MOT degC y 10 457 tickPosition inside tickLength 10 minorTickInterval null458 labels step 1 distance 3 x 0 y 0 zIndex 2 459 ]460

461 plotOptions 462 gauge 463 dataLabels enabled false 464 overshoot 1

(continues on next page)

331 TLDR Examples 311

Open Vehicles

(continued from previous page)

465 466 467 series [468 Speed value469 yAxis 0 name Speed className speed fullgauge data [0]470 pivot radius 10 471 dial radius 88 topWidth 1 baseLength 20 baseWidth 10

rarr˓rearLength 20 472 473 Voltage value474 yAxis 1 name Voltage className voltage auxgauge data [0]475 pivot radius 85 476 dial radius 95 baseWidth 5 baseLength 90 477 478 SOC value479 yAxis 2 name SOC className soc auxgauge data [0]480 pivot radius 85 481 dial radius 95 baseWidth 5 baseLength 90 482 483 Efficiency value484 yAxis 3 name Efficiency className efficiency auxgauge data [0]485 pivot radius 85 486 dial radius 95 baseWidth 5 baseLength 90 487 488 Power value489 yAxis 4 name Power className power auxgauge data [0]490 pivot radius 85 491 dial radius 95 baseWidth 5 baseLength 90 492 493 Charger temperature value494 yAxis 5 name Charger temperature className temp-charger tempgauge

rarr˓data [0]495 dial radius 90 baseWidth 3 baseLength 90 496 497 Battery temperature value498 yAxis 6 name Battery temperature className temp-battery tempgauge

rarr˓data [0]499 dial radius 90 baseWidth 3 baseLength 90 500 501 Inverter temperature value502 yAxis 7 name Inverter temperature className temp-inverter tempgauge

rarr˓data [0]503 dial radius 90 baseWidth 3 baseLength 90 504 505 Motor temperature value506 yAxis 8 name Motor temperature className temp-motor tempgauge data

rarr˓[0]507 dial radius 90 baseWidth 3 baseLength 90 508 ]509 510

511 Inject vehicle config512 for (var i = 0 i lt chart_configyAxislength i++) 513 $extend(chart_configyAxis[i] vehicle_configyAxis[i])514 515

516 gaugeset1 = Highchartschart(gaugeset1 chart_config(continues on next page)

312 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

517 function (chart) 518 chartupdate( chart animation duration 1000 easing swing )519 $(livestatus)on(msgmetrics function(e update)520 update_dashboard()521 )on(window-resize function(e)522 chartreflow()523 )524 525 )526 527

528 function init_charts() 529 init_gaugeset1()530 531

532 if (windowHighcharts) 533 init_charts()534 else 535 $ajax(536 url windowassetscharts_js537 dataType script538 cache true539 success function() init_charts() 540 )541 542

543 ltscriptgt544

545

546

547 lt-- TESTDATENGENERATOR --gt548 ltbr class=clearfixgt549 ltdiv id=viewportinfogtWxHltdivgt550 ltdiv id=debugfsgtltdivgt551 ltbutton class=btn btn-info id=mkmetricsgtMake test metricsltbuttongt552 ltbr class=clearfixgt553 ltscript type=textjavascriptgt554 $(mkmetrics)on(click function()555 var msg = 556 metrics 557 vbrangeest Mathrandom()80558 vbrangeideal Mathrandom()80559 vbenergyused Mathrandom()20560 vbenergyrecd Mathrandom()20561 vpspeed Mathrandom()120562 vbvoltage 45 + Mathrandom()15563 vbsoc Mathrandom()100564 vbconsumption Mathrandom()300565 vbpower Mathrandom()40 - 10566 vctemp Mathrandom()80567 vbtemp Mathrandom()80568 vitemp Mathrandom()80569 vmtemp Mathrandom()80570 571 572 $extend(metrics msgmetrics)573 $(receiver)trigger(msgmetrics msgmetrics)

(continues on next page)

331 TLDR Examples 313

Open Vehicles

(continued from previous page)

574 )575 $(window)on(resize function()576 $(viewportinfo)text($(window)width() + x + $(window)height())577 )trigger(resize)578 ltscriptgt

33115 Twizy Dashboard Tuning Plugin

This plugin adds two sliders to adjust neutral and braking recuperation levels to the dashboard

The sliders listen to driving profile changes and update accordingly

If not yet logged in the sliders are disabled

Install add the plugin as a hook type to page dashboard hook bodypre

dashboard-tunesliderhtm (hint right click save as)

1 lt--2 Hook plugin for dashboardbodypre or bodypost3 - add sliders to adjust recuperation power levels

(continues on next page)

314 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

4 --gt5

6 ltstylegt7 tuneslider 8 margin 10px 8px 09

10 form-inline form-controlslider-value 11 width 80px12 13 ltstylegt14

15 ltdiv class=receiver id=tuneslider style=displaynonegt16 ltdiv class=form-groupgt17 ltlabel class=control-label for=input-neutralgtNeutral recuperationltlabelgt18 ltdiv class=form-control slider id=neutral gt19 ltdivgt20 ltdiv class=form-groupgt21 ltlabel class=control-label for=input-brakegtBrake recuperationltlabelgt22 ltdiv class=form-control slider id=brake gt23 ltdivgt24 ltdivgt25

26 ltscriptgt27 (function()28

29 Init sliders30 $(neutral)slider( min0 max100 step1 unit default18 value18

rarr˓checkedfalse )31 $(brake)slider( min0 max100 step1 unit default18 value18

rarr˓checkedfalse )32

33 Update sliders on profile changes34 var profile35 $(tuneslider)on(msgmetrics function(ev update) 36 if (update[xrtcfgprofile] = null) 37 profile = update[xrtcfgprofile]38 var neutral = profile[7] brake = profile[8] see cfgconvc tagnames for

rarr˓profile structure39 $(neutral)slider( checked (neutral=-1) value (neutral=-1) neutral

rarr˓null )40 $(brake)slider( checked (brake=-1) value (brake=-1) brake null )41 42 )43

44 Update profile on slider changes45 $(tuneslider slider-value)on(change function(ev) 46 var neutral = $(input-neutral)prop(checked) $(input-neutral)val() -

rarr˓147 brake = $(input-brake)prop(checked) $(input-brake)val() -148 autorecup_minprc = profile[43] autorecup_ref = profile[44]49 var cmd = xrt cfg recup + neutral + + brake + + autorecup_ref + +

rarr˓autorecup_minprc50 loadcmd(cmd loadres)51 )52

53 Install into panel54 $(main)one(load function(ev)

(continues on next page)

331 TLDR Examples 315

Open Vehicles

(continued from previous page)

55 if (loggedin) 56 $(tuneslider slider)slider( disabled true )57 58 $(tuneslider)appendTo(panel-dashboard panel-body)show()59 )60

61 )()62 ltscriptgt

33116 Twizy Tuning Profile Editor

This plugin has been added to the Twizy code Itrsquos used here as a more complex example of what can be done byplugins

Itrsquos a full featured SEVCON tuning profile editor including dialogs to load amp save profiles from the OVMS configura-tion and to create amp read base64 profile codes

See Twizy documentation for details on tuning profiles and capabilities

Install not necessary if vehicle Twizy is configured (see ldquoTwizyrdquo menu) If yoursquod like to test this for another vehicleadd as a page plugin eg testprofed

profile-editorhtm (hint right click save as)

1 lt--2 Twizy page plugin Tuning Profile Editor3 Note included in firmware v32

(continues on next page)

316 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

4 --gt5

6 ltstylegt7 form-inline form-controlslider-value 8 width 70px9

10 radio-list 11 height 313px12 overflow-y auto13 overflow-x hidden14 padding-right 15px15 16 radio-list radio 17 overflow hidden18 19 radio-list key 20 min-width 20px21 display inline-block22 text-align center23 margin 0 10px24 25 radio-list kbd 26 min-width 60px27 display inline-block28 text-align center29 margin 0 20px 0 10px30 31 radio-list radio label 32 width 10033 text-align left34 padding 8px 30px35 36 radio-list radio labelactive 37 background-color 337ab738 color fff39 outline none40 41 radio-list radio labelactive input 42 outline none43 44 night radio-list radio labelhover 45 color fff46 47 ltstylegt48

49 ltdiv class=panel panel-primarygt50 ltdiv class=panel-headinggtTuning Profile ltspan id=headkeygtEditorltspangtltdivgt51 ltdiv class=panel-bodygt52 ltform action=gt53

54 ltdiv class=form-groupgt55 ltdiv class=flex-groupgt56 ltbutton type=button class=btn btn-default action-newgtNewltbuttongt57 ltbutton type=button class=btn btn-default action-loadgtLoadltbuttongt58 ltinput type=hidden id=input-key name=key value=gt59 ltinput type=hidden id=input-base64-reset name=base64-reset value=gt60 ltinput type=text class=form-control font-monospace placeholder=Base64

rarr˓profile code (continues on next page)

331 TLDR Examples 317

Open Vehicles

(continued from previous page)

61 name=base64 id=input-base64 value= autocapitalize=none autocorrect=rarr˓off

62 autocomplete=off spellcheck=falsegt63 ltdivgt64 ltdivgt65

66 ltul class=nav nav-tabsgt67 ltli class=activegtlta data-toggle=tab href=tab-drive aria-expanded=truegt

rarr˓Driveltagtltligt68 ltli class=gtlta data-toggle=tab href=tab-recup aria-expanded=falsegtRecup

rarr˓ltagtltligt69 ltli class=gtlta data-toggle=tab href=tab-ramps aria-expanded=falsegtRamps

rarr˓ltagtltligt70 ltulgt71 ltdiv class=tab-contentgt72

73 ltdiv id=tab-drive class=tab-pane section-drive active ingt74

75 ltfieldset id=part-speedgt76 ltlegendgtSpeedltlegendgt77 ltdiv class=form-horizontalgt78 ltdiv class=form-groupgt79 ltlabel class=control-label col-sm-2 for=input-speedgtMax speedlt

rarr˓labelgt80 ltdiv class=col-sm-10gtltdiv class=form-control slider id=speed gtlt

rarr˓divgt81 ltdivgt82 ltdiv class=form-groupgt83 ltlabel class=control-label col-sm-2 for=input-warngtWarn speedlt

rarr˓labelgt84 ltdiv class=col-sm-10gtltdiv class=form-control slider id=warn gtlt

rarr˓divgt85 ltdivgt86 ltdivgt87 ltfieldsetgt88

89 ltfieldset id=part-powergt90 ltlegendgtPowerltlegendgt91 ltdiv class=form-horizontalgt92 ltdiv class=form-groupgt93 ltlabel class=control-label col-sm-2 for=input-currentgtCurrentlt

rarr˓labelgt94 ltdiv class=col-sm-10gtltdiv class=form-control slider id=current gt

rarr˓ltdivgt95 ltdivgt96 ltdiv class=form-groupgt97 ltlabel class=control-label col-sm-2 for=input-torquegtTorqueltlabelgt98 ltdiv class=col-sm-10gtltdiv class=form-control slider id=torque gtlt

rarr˓divgt99 ltdivgt

100 ltdiv class=form-groupgt101 ltlabel class=control-label col-sm-2 for=input-power_lowgtPower lowlt

rarr˓labelgt102 ltdiv class=col-sm-10gtltdiv class=form-control slider id=power_low

rarr˓gtltdivgt103 ltdivgt104 ltdiv class=form-groupgt

(continues on next page)

318 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

105 ltlabel class=control-label col-sm-2 for=input-power_highgtPower highrarr˓ltlabelgt

106 ltdiv class=col-sm-10gtltdiv class=form-control slider id=power_highrarr˓gtltdivgt

107 ltdivgt108 ltdivgt109 ltfieldsetgt110

111 ltfieldset id=part-drivegt112 ltlegendgtDriveltlegendgt113 ltdiv class=form-horizontalgt114 ltdiv class=form-groupgt115 ltlabel class=control-label col-sm-2 for=input-drivegtDrive levellt

rarr˓labelgt116 ltdiv class=col-sm-10gtltdiv class=form-control slider id=drive gtlt

rarr˓divgt117 ltdivgt118 ltdiv class=form-groupgt119 ltlabel class=control-label col-sm-2 for=input-autodrive_refgtAuto 100

rarr˓ refltlabelgt120 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autodrive_

rarr˓ref gtltdivgt121 ltdivgt122 ltdiv class=form-groupgt123 ltlabel class=control-label col-sm-2 for=input-autodrive_minprcgtAuto

rarr˓min levelltlabelgt124 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autodrive_

rarr˓minprc gtltdivgt125 ltdivgt126 ltdivgt127 ltfieldsetgt128

129 ltfieldset id=part-tsmapdgt130 ltlegendgtTorqueSpeed-Map Driveltlegendgt131 ltdiv class=form-horizontalgt132 ltdiv class=form-groupgt133 ltlabel class=control-label col-sm-2 for=input-tsd_prc1gtTrq level 1

rarr˓ltlabelgt134 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc1 gt

rarr˓ltdivgt135 ltdivgt136 ltdiv class=form-groupgt137 ltlabel class=control-label col-sm-2 for=input-tsd_spd1gtat speed

rarr˓ltlabelgt138 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd1 gt

rarr˓ltdivgt139 ltdivgt140 ltdiv class=form-groupgt141 ltlabel class=control-label col-sm-2 for=input-tsd_prc2gtTrq level 2

rarr˓ltlabelgt142 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc2 gt

rarr˓ltdivgt143 ltdivgt144 ltdiv class=form-groupgt145 ltlabel class=control-label col-sm-2 for=input-tsd_spd2gtat speed

rarr˓ltlabelgt146 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd2 gt

rarr˓ltdivgt (continues on next page)

331 TLDR Examples 319

Open Vehicles

(continued from previous page)

147 ltdivgt148 ltdiv class=form-groupgt149 ltlabel class=control-label col-sm-2 for=input-tsd_prc3gtTrq level 3

rarr˓ltlabelgt150 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc3 gt

rarr˓ltdivgt151 ltdivgt152 ltdiv class=form-groupgt153 ltlabel class=control-label col-sm-2 for=input-tsd_spd3gtat speed

rarr˓ltlabelgt154 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd3 gt

rarr˓ltdivgt155 ltdivgt156 ltdiv class=form-groupgt157 ltlabel class=control-label col-sm-2 for=input-tsd_prc4gtTrq level 4

rarr˓ltlabelgt158 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_prc4 gt

rarr˓ltdivgt159 ltdivgt160 ltdiv class=form-groupgt161 ltlabel class=control-label col-sm-2 for=input-tsd_spd4gtat speed

rarr˓ltlabelgt162 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsd_spd4 gt

rarr˓ltdivgt163 ltdivgt164 ltdivgt165 ltfieldsetgt166

167 ltdivgt168

169 ltdiv id=tab-recup class=tab-pane section-recupgt170

171 ltfieldset id=part-recupgt172 ltlegendgtRecupltlegendgt173 ltdiv class=form-horizontalgt174 ltdiv class=form-groupgt175 ltlabel class=control-label col-sm-2 for=input-neutralgtNeutral level

rarr˓ltlabelgt176 ltdiv class=col-sm-10gtltdiv class=form-control slider id=neutral gt

rarr˓ltdivgt177 ltdivgt178 ltdiv class=form-groupgt179 ltlabel class=control-label col-sm-2 for=input-brakegtBrake levellt

rarr˓labelgt180 ltdiv class=col-sm-10gtltdiv class=form-control slider id=brake gtlt

rarr˓divgt181 ltdivgt182 ltdiv class=form-groupgt183 ltlabel class=control-label col-sm-2 for=input-autorecup_refgtAuto 100

rarr˓ refltlabelgt184 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autorecup_

rarr˓ref gtltdivgt185 ltdivgt186 ltdiv class=form-groupgt187 ltlabel class=control-label col-sm-2 for=input-autorecup_minprcgtAuto

rarr˓min levelltlabelgt188 ltdiv class=col-sm-10gtltdiv class=form-control slider id=autorecup_

rarr˓minprc gtltdivgt (continues on next page)

320 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

189 ltdivgt190 ltdivgt191 ltfieldsetgt192

193 ltfieldset id=part-tsmapngt194 ltlegendgtTorqueSpeed-Map Neutralltlegendgt195 ltdiv class=form-horizontalgt196 ltdiv class=form-groupgt197 ltlabel class=control-label col-sm-2 for=input-tsn_prc1gtTrq level 1

rarr˓ltlabelgt198 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc1 gt

rarr˓ltdivgt199 ltdivgt200 ltdiv class=form-groupgt201 ltlabel class=control-label col-sm-2 for=input-tsn_spd1gtat speed

rarr˓ltlabelgt202 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd1 gt

rarr˓ltdivgt203 ltdivgt204 ltdiv class=form-groupgt205 ltlabel class=control-label col-sm-2 for=input-tsn_prc2gtTrq level 2

rarr˓ltlabelgt206 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc2 gt

rarr˓ltdivgt207 ltdivgt208 ltdiv class=form-groupgt209 ltlabel class=control-label col-sm-2 for=input-tsn_spd2gtat speed

rarr˓ltlabelgt210 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd2 gt

rarr˓ltdivgt211 ltdivgt212 ltdiv class=form-groupgt213 ltlabel class=control-label col-sm-2 for=input-tsn_prc3gtTrq level 3

rarr˓ltlabelgt214 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc3 gt

rarr˓ltdivgt215 ltdivgt216 ltdiv class=form-groupgt217 ltlabel class=control-label col-sm-2 for=input-tsn_spd3gtat speed

rarr˓ltlabelgt218 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd3 gt

rarr˓ltdivgt219 ltdivgt220 ltdiv class=form-groupgt221 ltlabel class=control-label col-sm-2 for=input-tsn_prc4gtTrq level 4

rarr˓ltlabelgt222 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_prc4 gt

rarr˓ltdivgt223 ltdivgt224 ltdiv class=form-groupgt225 ltlabel class=control-label col-sm-2 for=input-tsn_spd4gtat speed

rarr˓ltlabelgt226 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsn_spd4 gt

rarr˓ltdivgt227 ltdivgt228 ltdivgt229 ltfieldsetgt

(continues on next page)

331 TLDR Examples 321

Open Vehicles

(continued from previous page)

230

231 ltfieldset id=part-tsmapbgt232 ltlegendgtTorqueSpeed-Map Brakeltlegendgt233 ltdiv class=form-horizontalgt234 ltdiv class=form-groupgt235 ltlabel class=control-label col-sm-2 for=input-tsb_prc1gtTrq level 1

rarr˓ltlabelgt236 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc1 gt

rarr˓ltdivgt237 ltdivgt238 ltdiv class=form-groupgt239 ltlabel class=control-label col-sm-2 for=input-tsb_spd1gtat speed

rarr˓ltlabelgt240 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd1 gt

rarr˓ltdivgt241 ltdivgt242 ltdiv class=form-groupgt243 ltlabel class=control-label col-sm-2 for=input-tsb_prc2gtTrq level 2

rarr˓ltlabelgt244 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc2 gt

rarr˓ltdivgt245 ltdivgt246 ltdiv class=form-groupgt247 ltlabel class=control-label col-sm-2 for=input-tsb_spd2gtat speed

rarr˓ltlabelgt248 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd2 gt

rarr˓ltdivgt249 ltdivgt250 ltdiv class=form-groupgt251 ltlabel class=control-label col-sm-2 for=input-tsb_prc3gtTrq level 3

rarr˓ltlabelgt252 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc3 gt

rarr˓ltdivgt253 ltdivgt254 ltdiv class=form-groupgt255 ltlabel class=control-label col-sm-2 for=input-tsb_spd3gtat speed

rarr˓ltlabelgt256 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd3 gt

rarr˓ltdivgt257 ltdivgt258 ltdiv class=form-groupgt259 ltlabel class=control-label col-sm-2 for=input-tsb_prc4gtTrq level 4

rarr˓ltlabelgt260 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_prc4 gt

rarr˓ltdivgt261 ltdivgt262 ltdiv class=form-groupgt263 ltlabel class=control-label col-sm-2 for=input-tsb_spd4gtat speed

rarr˓ltlabelgt264 ltdiv class=col-sm-10gtltdiv class=form-control slider id=tsb_spd4 gt

rarr˓ltdivgt265 ltdivgt266 ltdivgt267 ltfieldsetgt268

269 ltdivgt270

(continues on next page)

322 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

271 ltdiv id=tab-ramps class=tab-pane section-rampsgt272

273 ltfieldset id=part-rampsglobalgt274 ltlegendgtGeneralltlegendgt275 ltdiv class=form-horizontalgt276 ltdiv class=form-groupgt277 ltlabel class=control-label col-sm-2 for=input-ramplimit_accelgtLimit

rarr˓upltlabelgt278 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramplimit_

rarr˓accel gtltdivgt279 ltdivgt280 ltdiv class=form-groupgt281 ltlabel class=control-label col-sm-2 for=input-ramplimit_decelgtLimit

rarr˓downltlabelgt282 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramplimit_

rarr˓decel gtltdivgt283 ltdivgt284 ltdiv class=form-groupgt285 ltlabel class=control-label col-sm-2 for=input-smoothgtSmoothinglt

rarr˓labelgt286 ltdiv class=col-sm-10gtltdiv class=form-control slider id=smooth gtlt

rarr˓divgt287 ltdivgt288 ltdivgt289 ltfieldsetgt290

291 ltfieldset id=part-rampsgt292 ltlegendgtRamp Speedsltlegendgt293 ltdiv class=form-horizontalgt294 ltdiv class=form-groupgt295 ltlabel class=control-label col-sm-2 for=input-ramp_startgtStart

rarr˓reverseltlabelgt296 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_start

rarr˓gtltdivgt297 ltdivgt298 ltdiv class=form-groupgt299 ltlabel class=control-label col-sm-2 for=input-ramp_accelgtAccelerate

rarr˓ltlabelgt300 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_accel

rarr˓gtltdivgt301 ltdivgt302 ltdiv class=form-groupgt303 ltlabel class=control-label col-sm-2 for=input-ramp_decelgtDecelerate

rarr˓ltlabelgt304 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_decel

rarr˓gtltdivgt305 ltdivgt306 ltdiv class=form-groupgt307 ltlabel class=control-label col-sm-2 for=input-ramp_neutralgtNeutral

rarr˓ltlabelgt308 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_neutral

rarr˓ gtltdivgt309 ltdivgt310 ltdiv class=form-groupgt311 ltlabel class=control-label col-sm-2 for=input-ramp_brakegtBrakelt

rarr˓labelgt312 ltdiv class=col-sm-10gtltdiv class=form-control slider id=ramp_brake

rarr˓gtltdivgt (continues on next page)

331 TLDR Examples 323

Open Vehicles

(continued from previous page)

313 ltdivgt314 ltdivgt315 ltfieldsetgt316

317 ltdivgt318

319 ltdivgt320

321 ltbrgt322 ltdiv class=form-horizontalgt323 ltdiv class=form-groupgt324 ltlabel class=control-label col-sm-2 for=input-labelgtLabelltlabelgt325 ltdiv class=col-sm-10gt326 ltinput type=text class=form-control placeholder=Short button label327 name=label id=input-label value= autocapitalize=none autocorrect=

rarr˓off328 autocomplete=off spellcheck=falsegt329 ltdivgt330 ltdivgt331 ltdiv class=form-groupgt332 ltlabel class=control-label col-sm-2 for=input-titlegtTitleltlabelgt333 ltdiv class=col-sm-10gt334 ltinput type=text class=form-control placeholder=optional titlename335 name=title id=input-title value= autocapitalize=none autocorrect=

rarr˓off336 autocomplete=off spellcheck=falsegt337 ltdivgt338 ltdivgt339 ltdivgt340

341 ltbrgt342 ltdiv class=text-centergt343 ltbutton type=button class=btn btn-default action-resetgtResetltbuttongt344 ltbutton type=button class=btn btn-default action-saveasgtSave asltbuttongt345 ltbutton type=button class=btn btn-primary action-savegtSaveltbuttongt346 ltdivgt347

348 ltformgt349 ltdivgt350 ltdivgt351

352 ltdiv id=key-dialog gt353

354 ltscriptgt355 (function()356

357 init sliders358

359 $(speed)slider( unitkph min6 max120 default80 value80rarr˓checkedfalse )

360 $(warn)slider( unitkph min6 max120 default89 value89 checkedfalserarr˓)

361

362 $(current)slider( unit min10 max123 default100 value100rarr˓checkedfalse )

363 $(torque)slider( unit min10 max130 default100 value100rarr˓checkedfalse )

(continues on next page)

324 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

364 $(power_low)slider( unit min10 max139 default100 value100rarr˓checkedfalse )

365 $(power_high)slider( unit min10 max130 default100 value100rarr˓checkedfalse )

366

367 $(drive)slider( unit min10 max100 default100 value100rarr˓checkedfalse )

368 $(autodrive_ref)slider( unitkW min0 max25 step01 default0 value0rarr˓ checkedfalse )

369 $(autodrive_minprc)slider( unit min0 max100 default0 value0rarr˓checkedfalse )

370

371 $(tsd_prc1)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

372 $(tsd_spd1)slider( unitkph min0 max120 default33 value33rarr˓checkedfalse )

373 $(tsd_prc2)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

374 $(tsd_spd2)slider( unitkph min0 max120 default39 value39rarr˓checkedfalse )

375 $(tsd_prc3)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

376 $(tsd_spd3)slider( unitkph min0 max120 default50 value50rarr˓checkedfalse )

377 $(tsd_prc4)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

378 $(tsd_spd4)slider( unitkph min0 max120 default66 value66rarr˓checkedfalse )

379

380 $(neutral)slider( unit min0 max100 default18 value18rarr˓checkedfalse )

381 $(brake)slider( unit min0 max100 default18 value18 checkedfalse rarr˓)

382 $(autorecup_ref)slider( unitkW min0 max25 step01 default0 value0rarr˓ checkedfalse )

383 $(autorecup_minprc)slider( unit min0 max100 default0 value0rarr˓checkedfalse )

384

385 $(tsn_prc1)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

386 $(tsn_spd1)slider( unitkph min0 max120 default33 value33rarr˓checkedfalse )

387 $(tsn_prc2)slider( unit min0 max100 default80 value80rarr˓checkedfalse )

388 $(tsn_spd2)slider( unitkph min0 max120 default39 value39rarr˓checkedfalse )

389 $(tsn_prc3)slider( unit min0 max100 default50 value50rarr˓checkedfalse )

390 $(tsn_spd3)slider( unitkph min0 max120 default50 value50rarr˓checkedfalse )

391 $(tsn_prc4)slider( unit min0 max100 default20 value20rarr˓checkedfalse )

392 $(tsn_spd4)slider( unitkph min0 max120 default66 value66rarr˓checkedfalse )

393

394 $(tsb_prc1)slider( unit min0 max100 default100 value100rarr˓checkedfalse )

(continues on next page)

331 TLDR Examples 325

Open Vehicles

(continued from previous page)

395 $(tsb_spd1)slider( unitkph min0 max120 default33 value33rarr˓checkedfalse )

396 $(tsb_prc2)slider( unit min0 max100 default80 value80rarr˓checkedfalse )

397 $(tsb_spd2)slider( unitkph min0 max120 default39 value39rarr˓checkedfalse )

398 $(tsb_prc3)slider( unit min0 max100 default50 value50rarr˓checkedfalse )

399 $(tsb_spd3)slider( unitkph min0 max120 default50 value50rarr˓checkedfalse )

400 $(tsb_prc4)slider( unit min0 max100 default20 value20rarr˓checkedfalse )

401 $(tsb_spd4)slider( unitkph min0 max120 default66 value66rarr˓checkedfalse )

402

403

404 $(ramplimit_accel)slider( unit min1 max100 default30 value30rarr˓checkedfalse )

405 $(ramplimit_decel)slider( unit min0 max100 default30 value30rarr˓checkedfalse )

406 $(smooth)slider( unit min0 max100 default70 value70 checkedfalserarr˓)

407

408 $(ramp_start)slider( unitpermil min1 max250 default40 value40rarr˓checkedfalse )

409 $(ramp_accel)slider( unit min1 max100 default25 value25rarr˓checkedfalse )

410 $(ramp_decel)slider( unit min0 max100 default20 value20rarr˓checkedfalse )

411 $(ramp_neutral)slider( unit min0 max100 default40 value40rarr˓checkedfalse )

412 $(ramp_brake)slider( unit min0 max100 default40 value40rarr˓checkedfalse )

413

414 profile handling415

416 const keys = [417 checksum418 speed419 warn420 torque421 power_low422 power_high423 drive424 neutral425 brake426 tsd_spd1427 tsd_spd2428 tsd_spd3429 tsd_spd4430 tsd_prc1431 tsd_prc2432 tsd_prc3433 tsd_prc4434 tsn_spd1435 tsn_spd2436 tsn_spd3

(continues on next page)

326 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

437 tsn_spd4438 tsn_prc1439 tsn_prc2440 tsn_prc3441 tsn_prc4442 tsb_spd1443 tsb_spd2444 tsb_spd3445 tsb_spd4446 tsb_prc1447 tsb_prc2448 tsb_prc3449 tsb_prc4450 ramp_start451 ramp_accel452 ramp_decel453 ramp_neutral454 ramp_brake455 smooth456 brakelight_on457 brakelight_off458 ramplimit_accel459 ramplimit_decel460 autorecup_minprc461 autorecup_ref462 autodrive_minprc463 autodrive_ref464 current465 ]466

467 const scale = 468 autodrive_ref 01469 autorecup_ref 01470 471

472 var profile = 473

474 var plist = [475 label - title Working Set 476 label PWR title Power 477 label ECO title Economy 478 label ICE title Winter 479 ]480

481 load profile list482 var plistloader = loadcmd(config list xrt)then(function(data) 483 var lines = datasplit(n) line i key484 for (i = 0 i lt lineslength i++) 485 line = lines[i]match(profile([0-9]2)([^]) ())486 if (line ampamp linelength == 4) 487 key = Number(line[1])488 if (key lt 1 || key gt 99) continue489 if (plist[key]) plist[key] = 490 plist[key][line[2]||profile] = line[3]491 492 493 )

(continues on next page)

331 TLDR Examples 327

Open Vehicles

(continued from previous page)

494

495 current control rarr power ranges496 function currentControl(on trigger) 497 if (on) 498 $(input-torque input-power_low input-power_high)

rarr˓slider( max 254 )499 else 500 $(input-torque input-power_high)slider( max 130 )501 $(input-power_low)slider( max 139 )502 503 504 $(input-current)on(change function(ev) 505 currentControl(thischecked)506 $(input-torque input-power_low input-power_high)trigger(change)507 )508

509 load profile into sliders510 function loadProfile() 511 currentControl(profile[current] gt= 0)512 $map(profile function(val key) 513 $(input-+key)slider( value (val gt= 0) (val (scale[key]||1)) null

rarr˓checked (val gt= 0) )514 )515 516

517 calculate profile checksum518 function calcChecksum() 519 var checksum i520 checksum = 0x0101521 for (i=1 iltkeyslength i++)522 checksum += profile[keys[i]] + 1523 if ((checksum amp 0x0ff) == 0)524 checksum gtgt= 8525 return (checksum amp 0x0ff) - 1526 527

528 load a base64 string into profile529 function loadBase64(base64) 530 var bin = atob(base64)531 $map(keys function(key i) profile[key] = (bincharCodeAt(i)||0) - 1 )532 if (profile[checksum] == calcChecksum()) 533 loadProfile()534 return true535 else 536 confirmdialog(Profile Error Invalid base64 code (checksum mismatch) [

rarr˓Close])537 return false538 539 540

541 make a base64 string from profile542 function makeBase64() 543 profile[checksum] = calcChecksum()544 var u8 = new Uint8Array(keyslength)545 $map(keys function(key i) u8[i] = profile[key] + 1 )546 return btoa(StringfromCharCodeapply(null u8))547

(continues on next page)

328 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

548

549 load a profile550 function loadKey(key) 551 if (key lt 0 || key gt 99) return552 plistloaderthen(function() 553 $(input-label)val(plist[key] ampamp plist[key][label] || )554 $(input-title)val(plist[key] ampamp plist[key][title] || )555 loadcmd(xrt cfg get + key)fail(function(request textStatus errorThrown) 556 confirmdialog(Load Profile xhrErrorInfo(request textStatus errorThrown)

rarr˓[Close])557 )done(function(res) 558 var base64559 if (resmatch(errori))560 base64 = AQ561 else562 base64 = ressubstr(reslastIndexOf( )+1)563 if (loadBase64(base64)) 564 $(input-key)val(key)565 $(input-base64 input-base64-reset)val(base64)566 $(headkey)text( + key)567 568 )569 )570 571

572 save profile573 function saveKey(key) 574 if (key lt 0 || key gt 99) return575 var base64 = $(input-base64)val()576 label = $(input-label)val()replace(g )577 title = $(input-title)val()replace(g )578 ckey = profile + ((keylt10)0) + key579 var cmd = xrt cfg set + key + + base64 + + label + + title +

rarr˓580 loadcmd(cmd)fail(function(request textStatus errorThrown) 581 confirmdialog(Save Profile xhrErrorInfo(request textStatus errorThrown) [

rarr˓Close])582 )done(function(res) 583 confirmdialog(Save Profile res [Close])584 if (resmatch(errori)) 585 if (key gt 0) 586 if (plist[key]) plist[key] = 587 plist[key][label] = label588 plist[key][title] = title589 590 $(input-key)val(key)591 $(input-base64-reset)val(base64)592 $(headkey)text( + key)593 594 )595 596

597 base64 input598 $(input-base64)on(change function(ev) 599 var base64 = $(this)val() || AQ600 if (loadBase64(base64))601 $(input-base64-reset)val(base64)

(continues on next page)

331 TLDR Examples 329

Open Vehicles

(continued from previous page)

602 )603

604 update profile amp base64 on slider changes605 $(slider-value)on(change function(ev) 606 var key = thisname607 var val = Mathmax(thismin Mathmin(thismax 1thisvalue))608 profile[key] = thischecked (val (scale[key]||1)) -1609 var base64 = makeBase64()610 $(input-base64)val(base64)611 )612

613 prep key dialog614 $(key-dialog)dialog(615 show false616 onShow function(input) 617 var $this = $(this)618 $thisaddClass(loading)619 plistloaderthen(function(data) 620 var curkey = $(input-key)val() || 0 i label title621 $plist = $(ltdiv class=radio-list data-toggle=buttons gt)622 for (i = 0 i lt= Mathmin(99 plistlength + 2) i++) 623 if (plist[i] ampamp (i==0 || plist[i]profile)) 624 label = plist[i]label || -625 title = plist[i]title || (plist[i]profilesubstr(0 10) + )626 else 627 label = -628 title = -new-629 630 $plistappend(ltdiv class=radiogtltlabel class=btngt +631 ltinput type=radio name=key value= + i + gtltspan class=keygt +632 ((i==0) WS ( + ((ilt10)0) + i)) + ltspangt ltkbdgt +633 encode_html(label) + ltkbdgt + encode_html(title) + ltlabelgtltdivgt)634 635 $thisfind(modal-body)append($plist)find(input[value=+curkey+])636 prop(checked true)parent()addClass(active)637 $plist638 on(dblclick labelbtn function(ev) $thisdialog(triggerButton

rarr˓1) )639 on(keypress function(ev) if (evwhich==13) $thisdialog(triggerButton

rarr˓ 1) )640 $thisremoveClass(loading)641 )642 643 onShown function(input) 644 $(this)find(btnactive)focus()645 646 onHide function(input) 647 var $this = $(this) dlg = $thisdata(dialog)648 var key = $thisfind(input[name=key]checked)val()649 if (key == undefined ampamp inputbutton ampamp inputbuttonindex)650 dlgoptionsonActioncall(this key)651 652 )653

654 buttons655 $(action-new)on(click function(ev) 656 $(slider)slider( value null )

(continues on next page)

330 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

657 $(headkey)text(Editor)658 $(input-base64 input-label input-title)val()trigger(change)659 )660 $(action-reset)on(click function(ev) 661 $(input-base64)val($(input-base64-reset)val())trigger(change)662 )663 $(action-load)on(click function(ev) 664 $(key-dialog)dialog(665 show true title Load Profile body 666 buttons [ label Cancel btnClass default label Load btnClass

rarr˓primary ]667 onAction function(key) loadKey(key) 668 )669 )670 $(action-saveas)on(click function(ev) 671 $(key-dialog)dialog(672 show true title Save Profile body 673 buttons [ label Cancel btnClass default label Save btnClass

rarr˓primary ]674 onAction function(key) saveKey(key) 675 )676 )677 $(action-save)on(click function(ev) 678 var key = $(input-key)val()679 if (key === )680 $(action-saveas)trigger(click)681 else682 saveKey(key)683 )684

685 start load profile open load dialog686 if (pageparams[key] == undefined)687 loadKey(pageparams[key])688 else689 $(action-load)trigger(click)690

691 )()692 ltscriptgt

331 TLDR Examples 331

Open Vehicles

33117 Twizy Drivemode Button Editor

This plugin has been added to the Twizy code Itrsquos used here as a more complex example of what can be done byplugins

Itrsquos an editor for the drivemode buttons the Twizy adds to the dashboard for quick tuning profile changes The editorallows to change the layout (number and order of buttons) and the profiles to use

It includes a profile selector built with the dialog widget that retrieves the available profiles from the OVMS configstore

Install not necessary if vehicle Twizy is configured (see ldquoTwizyrdquo menu) If yoursquod like to test this for another vehicleadd as a page plugin eg testdmconfig

drivemode-confightm (hint right click save as)

1 lt--2 Twizy page plugin Drivemode Button Configuration3 Note included in firmware v324 --gt5

6 ltstylegt7 fullscreened panel-single panel-body 8 padding 10px9

10

11 btn-group-lggtbtn12 btn-lg 13 padding 10px 3px14 overflow hidden15 16 loadmenu btn 17 font-weight bold18 19 btn-groupbtn-group-lgexchange 20 width 221

(continues on next page)

332 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

22 editor btnhover 23 background-color e6e6e624 25 editor btn-group-lggtbtn26 editor btn-lg 27 padding 10px 0px28 font-size 15px29 30 editor exchange btn 31 font-weight bold32 33 night editor btn 34 color 00035 background 88836 37 night editor btnfocus38 night editor btnfocus39 night editor btnhover 40 background-color e0e0e041 42

43 radio-list 44 height 313px45 overflow-y auto46 overflow-x hidden47 padding-right 15px48 49 radio-list radio 50 overflow hidden51 52 radio-list key 53 min-width 20px54 display inline-block55 text-align center56 margin 0 10px57 58 radio-list kbd 59 min-width 60px60 display inline-block61 text-align center62 margin 0 20px 0 10px63 64 radio-list radio label 65 width 10066 text-align left67 padding 8px 30px68 69 radio-list radio labelactive 70 background-color 337ab771 color fff72 outline none73 74 radio-list radio labelactive input 75 outline none76 77 night radio-list radio labelhover 78 color fff

(continues on next page)

331 TLDR Examples 333

Open Vehicles

(continued from previous page)

79 80 ltstylegt81

82 ltdiv class=panel panel-primarygt83 ltdiv class=panel-headinggtDrivemode Button Configurationltdivgt84 ltdiv class=panel-bodygt85 ltform action=gt86

87 ltp id=infogtLoading button configurationltpgt88

89 ltdiv id=loadmenu class=btn-group btn-group-justifiedgtltdivgt90 ltdiv id=editor class=btn-group btn-group-justifiedgt91 ltdiv class=btn-group btn-group-lg add backgt92 ltbutton type=button class=btn title=Add buttongtltbuttongt93 ltdivgt94 ltdivgt95

96 ltbrgt97 ltbrgt98 ltdiv class=text-centergt99 ltbutton type=button class=btn btn-default onclick=reloadpage()gtResetlt

rarr˓buttongt100 ltbutton type=button class=btn btn-primary action-savegtSaveltbuttongt101 ltdivgt102

103 ltformgt104 ltdivgt105 ltdiv class=panel-footergt106 lta class=btn btn-sm btn-default target=main href=dashboardgtDashboardltagt107 lta class=btn btn-sm btn-default target=main href=xrtdrivemodegtDrivemodelt

rarr˓agt108 ltdivgt109 ltdivgt110

111 ltdiv id=key-dialog gt112

113 ltscriptgt114 (function()115

116 var $menu = $(loadmenu) $edit = $(editor) $back = $editfind(back)117

118 var pbuttons = [0123]119 var plist = [120 label STD title Standard 121 label PWR title Power 122 label ECO title Economy 123 label ICE title Winter 124 ]125

126 load profile list amp button config127 $(panel)addClass(loading)128 var plistloader = loadcmd(config list xrt)then(function(data) 129 var lines = datasplit(n) line i key130 for (i = 0 i lt lineslength i++) 131 line = lines[i]match(profile([0-9]2)([^]) ())132 if (line ampamp linelength == 4) 133 key = Number(line[1])

(continues on next page)

334 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

134 if (key lt 1 || key gt 99) continue135 if (plist[key]) plist[key] = 136 plist[key][line[2]||profile] = line[3]137 continue138 139 line = lines[i]match(profile_buttons ())140 if (line ampamp linelength == 2) 141 try 142 pbuttons = JSONparse([ + line[1] + ])143 catch (e) 144 consoleerror(e)145 146 147 148 )149

150 prep key dialog151 $(key-dialog)dialog(152 show false153 title Select Profile154 buttons [ label Cancel btnClass default label Select btnClass

rarr˓primary ]155 onShow function(input) 156 var $this = $(this) dlg = $thisdata(dialog)157 $thisaddClass(loading)158 plistloaderthen(function(data) 159 var curkey = dlgoptionskey || 0 i label title160 $plist = $(ltdiv class=radio-list data-toggle=buttons gt)161 for (i = 0 i lt= Mathmin(99 plistlength-1) i++) 162 if (plist[i] ampamp (i==0 || plist[i]profile)) 163 label = plist[i]label || -164 title = plist[i]title || (plist[i]profilesubstr(0 10) + )165 else 166 label = -167 title = -new-168 169 $plistappend(ltdiv class=radiogtltlabel class=btngt +170 ltinput type=radio name=key value= + i + gtltspan class=keygt +171 ((i==0) STD ( + ((ilt10)0) + i)) + ltspangt ltkbdgt +172 encode_html(label) + ltkbdgt + encode_html(title) + ltlabelgtltdivgt)173 174 $thisfind(modal-body)html($plist)find(input[value=+curkey+])175 prop(checked true)parent()addClass(active)176 $plist177 on(dblclick labelbtn function(ev) $thisdialog(triggerButton

rarr˓1) )178 on(keypress function(ev) if (evwhich==13) $thisdialog(triggerButton

rarr˓ 1) )179 $thisremoveClass(loading)180 )181 182 onShown function(input) 183 $(this)find(btnactive)focus()184 185 onHide function(input) 186 var $this = $(this) dlg = $thisdata(dialog)187 var key = $thisfind(input[name=key]checked)val()

(continues on next page)

331 TLDR Examples 335

Open Vehicles

(continued from previous page)

188 if (key == undefined ampamp inputbutton ampamp inputbuttonindex)189 dlgoptionsonActioncall(this key)190 191 )192

193 profile selection194 $(loadmenu)on(click button function(ev) 195 var $this = $(this)196 $(key-dialog)dialog(197 show true198 key $thisval()199 onAction function(key) 200 var prof = plist[key] || 201 $thisval(key)202 $thisattr(title proftitle || )203 $thistext(proflabel || (+((keylt10)0)+key))204 205 )206 )207

208 create buttons209

210 function addButton(key front) 211 var prof = plist[key] || 212 if ($menu[0]childElementCount == 0) 213 $backbefore(214 ltdiv class=btn-group btn-group-lg add frontgt215 ltbutton type=button class=btn title=Add buttongtltbuttongt216 ltdivgt217 ltdiv class=btn-group btn-group-lg removegt218 ltbutton type=button class=btn title=Remove buttongtltbuttongt219 ltdivgt)220 else 221 $backbefore(222 ltdiv class=btn-group btn-group-lg exchangegt223 ltbutton type=button class=btn title=Exchange buttonsgtltbuttongt224 ltdivgt225 ltdiv class=btn-group btn-group-lg removegt226 ltbutton type=button class=btn title=Remove buttongtltbuttongt227 ltdivgt)228 229 var $btn = $(230 ltdiv class=btn-group btn-group-lggt231 ltbutton type=button value=key class=btn btn-default title=titlegt

rarr˓labelltbuttongt232 ltdivgt233 replace(key key)234 replace(title encode_html(proftitle || ))235 replace(label encode_html(proflabel || +((keylt10)0)+key)))236 if (front)237 $menuprepend($btn)238 else239 $menuappend($btn)240 241

242 plistloaderthen(function() 243 var key prof

(continues on next page)

336 Chapter 33 Web Framework amp Plugins

Open Vehicles

(continued from previous page)

244 for (var i = 0 i lt pbuttonslength i++) 245 addButton(pbuttons[i])246 247 $(panel)removeClass(loading)248 $(info)text(Click button to select profile)249 )250

251 editor buttons252 $(editor)on(click add btn function(ev) 253 addButton(0 $(this)parent()hasClass(front))254 )on(click remove btn function(ev) 255 var $this = $(this) pos = $editfind(btn)index(this) gtgt 1256 $($menuchildren()get(pos))detach()257 if (pos gt 0 || $menu[0]childElementCount == 0)258 $thisparent()prev()detach()259 else if ($menu[0]childElementCount = 0)260 $thisparent()next()detach()261 $thisparent()detach()262 )on(click exchange btn function(ev) 263 var pos = $editfind(btn)index(this) gtgt 1264 if (pos gt 0) $($menuchildren()get(pos))insertBefore($($menuchildren()get(pos-

rarr˓1)))265 )266

267 save268 $(action-save)on(click function(ev) 269 pbuttons = []270 $menufind(btn)each(function() pbuttonspush(thisvalue) )271 loadcmd(config set xrt profile_buttons + pbuttonstoString())272 fail(function(request textStatus errorThrown) 273 confirmdialog(Save Configuration xhrErrorInfo(request textStatus

rarr˓errorThrown) [Close])274 )275 done(function(res) 276 confirmdialog(Save Configuration res [Close])277 )278 )279

280 )()281 ltscriptgt

332 Installing Plugins

The framework supports installing user content as pages or extensions to pages To install an example

1 Menu Config rarr Web Plugins

2 Add plugin type ldquoPagerdquo name eg ldquodevmetricsrdquo (used as the file name in storeplugin)

3 Save rarr Edit

4 Set page to eg ldquousrdevmetricsrdquo label to eg ldquoDev Metricsrdquo

5 Set the menu to eg ldquoToolsrdquo and auth to eg ldquoNonerdquo

6 Paste the page source into the content area

332 Installing Plugins 337

Open Vehicles

7 Save rarr the page is now accessible in the ldquoToolsrdquo menu

Hint use the standard editor (tools menu) in a second session to edit a plugin repeatedly during test development

333 Basics

The OVMS web framework is based on HTML 5 Bootstrap 3 and jQuery 3 Plenty documentation and guides onthese basic web technologies is available on the web a very good resource is w3schoolscom

For charts the framework includes Highcharts 6 Info and documentation on this is available on Highchartscom

The framework is ldquoAJAXrdquo based The index page loads the framework assets and defines a default container structureincluding a menu and a main container Content pages are loaded into the main container The window URLincludes the page URL after the hash mark

bull httpovmslocalstatus ndash this loads page status into main

bull httpovmslocaldashboardnm=1 ndash this loads the dashboard and activates night mode

Links and forms having id targets are automatically converted to AJAX by the framework

bull lta href=editpath=sdindextxt target=maingtEdit indextxtltagt ndash loadthe editor

Pages can be loaded outside the framework as well (eg httpovmslocalstatus) See index source onframework scripts and styles to include if yoursquod like to design standalone pages using the framework methods

If file system access is enabled all URLs not handled by the system or a user plugin (see below) are mapped onto thefile system under the configured web root Of course files can be loaded into the framework as well For example ifthe web root is sd (default)

bull httpovmslocalmypagehtm ndash load file sdmypagehtm into main

bull httptest1locallogs ndash load directory listing sdlogs into main

Important Note the framework has a global shared context (ie the window object) To avoid polluting the globalcontext with local variables good practice is to wrap your local scripts into closures Pattern

ltscriptgt(function()

insert your code here )()ltscriptgt

334 Authorization

Page access can be restricted to authorized users either session based or per access File access can be restricted usingdigest authentication

The module password is used for all authorizations A user account or API key administration is not yet included themain username is admin

To create a session call the login page and store the resulting cookie

1 curl -c auth -b auth http19216841login -d username=admin -dpassword=

2 curl -c auth -b auth http19216841apiexecutecommand=xrt+cfg+info

338 Chapter 33 Web Framework amp Plugins

Open Vehicles

To issue a single call eg to execute a command from a Wifi button supply the password as apikey

bull curl http19216841apiexecuteapikey=passwordampcommand=xrt+cfg+info

bull curl http19216841apiexecuteapikey=passwordamptype=jsampcommand=print(Duktapeversion)

335 Web UI Development Framework

To simplify and speed up UI and plugin development you can simply run a local web server from the dev directoryof the ovms_webserver component source

Preparation create your local git clone if you donrsquot have one already

gt cd ~gt git clone httpsgithubcomopenvehiclesOpen-Vehicle-Monitoring-System-3git

Local web server options List of static web servers

Example

gt cd ~Open-Vehicle-Monitoring-System-3vehicleOVMSV3componentsovms_webserverdevgt python3 -m httpserver 8000Serving HTTP on 0000 port 8000 (http00008000)

Now open the development framework in your browser at URI httplocalhost8000 If that doesnrsquot workcheck your firewall settings for port 8000 on localhost

You should see the examples home Edit indexhtm to add custom menus edit homehtm to add custom homebuttons

Hint to test your plugin for mobile devices use the mobile emulation mode of your browserrsquos development toolkitMobile mode allows to test small screen resolutions rotation and touch events

A static local HTTP server allows to use all frontend features but cannot emulate the backend API (commandscriptexecution) If using a CGI capable HTTP server you can also add a proxy handler for apiexecute that forwardsthe requests to your module by HTTP or SSH

If you want to add your results to a C++ module use the tools mksrc and mksrcf to convert your HTML files intoC++ compatible strings mksrc is meant for static strings mksrcf for strings with printf style placeholders

335 Web UI Development Framework 339

Open Vehicles

340 Chapter 33 Web Framework amp Plugins

CHAPTER 34

Scripting

341 Example Foglight

This is an example for combining a script module implementing some functional extension with a web plugin toprovide a user interface

The plugin realizes a fog light with automatic speed adaption ie the light will be turned off above a configurablespeed and on again when the vehicle slows down again It also switches off automatically when the vehicle is parked

The plugin shows how to

bull read custom config variables

bull use module state variables

341

Open Vehicles

bull react to events

bull send custom events

bull read metrics

bull execute system commands

bull provide new commands

bull provide a web UI

3411 Installation

bull Save foglightjs as storescriptslibfoglightjs (add the lib directory as necessary)

bull Add foglighthtm as a web hook type plugin at page dashboard hook bodypre

bull Execute script eval foglight = require(libfoglight)

Optionally

bull To test the module execute script eval foglightinfo() ndash it should print config and state

bull To automatically load the module on boot add the line foglight = require(libfoglight) tostorescriptsovmsmainjs

3412 Commands Functions

The module provides two public API functions

Function Descriptionfoglightset(onoff) switch fog light on (1) off (0)foglightinfo() output config amp state in JSON format

To call these from a shell use script eval Example

bull script eval foglightset(1)

3413 Configuration

Wersquoll add the configuration for this to the vehicle section

Config Default Descriptionfoglightport 1 EGPIO output port numberfoglightauto no yes = speed automationfoglightspeedon 45 auto turn on below this speedfoglightspeedoff 55 auto turn off above this speed

Note You can add arbitrary config instances to defined sections simply by setting them config set vehiclefoglightauto yes

342 Chapter 34 Scripting

Open Vehicles

Update Beginning with firmware release 32009 a general configuration section usr is provided for plugins Werecommend using this for all custom parameters now Keep in mind to prefix all instances introduced by the pluginname so your plugin can nicely coexist with others

To store the config for simple amp quick script access and implement the defaults we introduce an internal modulemember object cfg

Listing 1 Module Plugin

28 var cfg = 29 foglightport 130 foglightauto no31 foglightspeedon 4532 foglightspeedoff 5533

By foglight = require() the module is added to the global name space as a javascript object This objectcan contain any internal standard javascript variables and functions Internal members are hidden by default if youwould like to expose the cfg object you would simply add a reference to it to the exports object as is done belowfor the API methods

Reading OVMS config variables from a script currently needs to be done by executing config list and parsingthe output This is done by the readconfig() function

42 function readconfig() 43 var cmdres lines cols i44 cmdres = OvmsCommandExec(config list vehicle)45 lines = cmdressplit(n)46 for (i=0 iltlineslength i++) 47 if (lines[i]indexOf(foglight) gt= 0) 48 cols = lines[i]substr(2)split( )49 cfg[cols[0]] = cols[1]50 51

Update OVMS release 32009 adds the OvmsConfigGetValues() API To use this we would now omit theldquofoglightrdquo prefix from our cfg properties Reading the foglight configuration can then be reduced to a single line

Objectassign(cfg OvmsConfigGetValues(vehicle foglight))

3414 Listen to Events

The module needs to listen to three events

bull configchanged triggers reloading the configuration

bull ticker1 is used to check the speed once per second

bull vehicleoff automatically also turns off the fog light

The per second ticker is only necessary when the speed adaption is enabled so we can use this to show how todynamically add and remove event handlers through the PubSub API

341 Example Foglight 343

Open Vehicles

Listing 2 Module Plugin

52 update ticker subscription53 if (cfg[foglightauto] == yes ampamp stateticker) 54 stateticker = PubSubsubscribe(ticker1 checkspeed)55 else if (cfg[foglightauto] = yes ampamp stateticker) 56 PubSubunsubscribe(stateticker)57 stateticker = false58

state is another internal object for our state variables

3415 Send Events

Sending custom events is a lightweight method to inform the web UI (or other plugins) about simple state changes Inthis case wersquod like to inform listeners when the fog light actually physically is switched on or off so the web UI cangive visual feedback to the driver on this

Beginning with firmware release 32006 there is a native API OvmsEventsRaise() available to send events

Before 32006 we simply use the standard command event raise

Listing 3 Module Plugin

61 EGPIO port control62 function toggle(onoff) 63 if (stateport = onoff) 64 OvmsCommandExec(egpio output + cfg[foglightport] + + onoff)65 stateport = onoff66 OvmsCommandExec(event raise usrfoglight + (onoff on off))67 68

The web plugin subscribes to the foglight events just as to any system event

Listing 4 Web Plugin

64 Listen to foglight events65 $(foglight)on(msgevent function(e event) 66 if (event == usrfoglighton)67 update( state port 1 )68 else if (event == usrfoglightoff)69 update( state port 0 )70 else if (event == vehicleoff) 71 update( state on 0 )72 $(action-foglight-output)empty()73 74 )

Note You can raise any event you like but you shouldnrsquot raise system events without good knowledge of theireffects Event codes are simply strings so yoursquore free to extend them Use the prefix usr for custom events to avoidpotential conflicts with future system event additions

344 Chapter 34 Scripting

Open Vehicles

3416 Read Metrics

Reading metrics is straight forward through the OvmsMetrics API

Listing 5 Module Plugin

74 var speed = OvmsMetricsAsFloat(vpspeed)

Use Value() instead of AsFloat() for non-numerical metrics

Note You cannot subscribe to metrics changes directly (yet) Metrics can change thousands of times per secondwhich would overload the scripting capabilities To periodically check a metric register for a ticker event (as shownhere)

3417 Provide Commands

To add commands simply expose their handler functions through the exports object By this users will be able tocall these functions using the script eval command from any shell or from any script by referencing them viathe global module variable foglight in our case

Listing 6 Module Plugin

99 API method foglightinfo()100 exportsinfo = function() 101 JSONprint( cfg cfg state state )102

JSONprint() is a convenient way to communicate with a web plugin as that wonrsquot need to parse some potentiallyambigous textual output but can simply use JSONparse() to read it into a variable

Listing 7 Web Plugin

82 Init amp install83 $(main)one(load function(ev) 84 loadcmd(script eval foglightinfo())then(function(output) 85 update(JSONparse(output))

Note Keep in mind commands should always output some textual response indicating their action and result If acommand does nothing it should tell the user so If a command is not intended for shell use it should still providesome clue about this when called from the shell

3418 Module Plugin

foglightjs (hint right click save as)

1 2 storescriptslibfoglightjs3 4 Module plugin5 Foglight control with speed adaption and auto off on vehicle off

(continues on next page)

341 Example Foglight 345

Open Vehicles

(continued from previous page)

6 7 Version 10 Michael Balzer ltdexterdexters-webdegt8 9 Enable

10 - install at above path11 - add to storescriptsovmsmainjs12 foglight = require(libfoglight)13 - script reload14 15 Config16 - vehicle foglightport EGPIO output port number17 - vehicle foglightauto yes = speed automation18 - vehicle foglightspeedon auto turn on below this speed19 - vehicle foglightspeedoff auto turn off above this speed20 21 Usage22 - script eval foglightset(1) toggle foglight on23 - script eval foglightset(0) toggle foglight off24 - script eval foglightinfo() show config amp state (JSON)25 26 27

28 var cfg = 29 foglightport 130 foglightauto no31 foglightspeedon 4532 foglightspeedoff 5533 34

35 var state = 36 on 0 foglight onoff37 port 0 current port output state38 ticker false ticker subscription39 40

41 Read config42 function readconfig() 43 var cmdres lines cols i44 cmdres = OvmsCommandExec(config list vehicle)45 lines = cmdressplit(n)46 for (i=0 iltlineslength i++) 47 if (lines[i]indexOf(foglight) gt= 0) 48 cols = lines[i]substr(2)split( )49 cfg[cols[0]] = cols[1]50 51 52 update ticker subscription53 if (cfg[foglightauto] == yes ampamp stateticker) 54 stateticker = PubSubsubscribe(ticker1 checkspeed)55 else if (cfg[foglightauto] = yes ampamp stateticker) 56 PubSubunsubscribe(stateticker)57 stateticker = false58 59 60

61 EGPIO port control62 function toggle(onoff)

(continues on next page)

346 Chapter 34 Scripting

Open Vehicles

(continued from previous page)

63 if (stateport = onoff) 64 OvmsCommandExec(egpio output + cfg[foglightport] + + onoff)65 stateport = onoff66 OvmsCommandExec(event raise usrfoglight + (onoff on off))67 68 69

70 Check speed71 function checkspeed() 72 if (stateon)73 return74 var speed = OvmsMetricsAsFloat(vpspeed)75 if (speed lt= cfg[foglightspeedon])76 toggle(1)77 else if (speed gt= cfg[foglightspeedoff])78 toggle(0)79 80

81 API method foglightset(onoff)82 exportsset = function(onoff) 83 if (onoff) 84 stateon = 185 if (cfg[foglightauto] == yes) 86 checkspeed()87 print(Foglight AUTO moden)88 else 89 toggle(1)90 print(Foglight ONn)91 92 else 93 stateon = 094 toggle(0)95 print(Foglight OFFn)96 97 98

99 API method foglightinfo()100 exportsinfo = function() 101 JSONprint( cfg cfg state state )102 103

104 Init105 readconfig()106 PubSubsubscribe(configchanged readconfig)107 PubSubsubscribe(vehicleoff function() exportsset(0) )

3419 Web Plugin

foglighthtm (hint right click save as)

1 lt--2 foglighthtm Web plugin for hook dashboardbodypre3 - add button to activatedeactivate foglight4 - add indicator to show current foglight state5

(continues on next page)

341 Example Foglight 347

Open Vehicles

(continued from previous page)

6 Requires module plugin foglightjs7

8 Version 10 Michael Balzer ltdexterdexters-webdegt9 --gt

10

11 ltstylegt12 foglight 13 margin 10px 8px 014 15 foglight indicator gt label 16 font-size 13017 line-height 16018 margin 0px19 padding 10px20 display block21 border-radius 50px22 23 ltstylegt24

25 ltdiv class=receiver id=foglight style=displaynonegt26 ltformgt27 ltdiv class=form-groupgt28 ltdiv class=col-xs-6gt29 ltdiv class=indicator indicator-foglightgt30 ltspan class=label label-defaultgtFOGLIGHTltspangt31 ltdivgt32 ltdivgt33 ltdiv class=col-xs-6gt34 ltdiv class=btn-group btn-group-justified action-foglight-set data-toggle=

rarr˓buttonsgt35 ltlabel class=btn btn-default action-foglight-0gtltinput type=radio name=

rarr˓foglight value=0gtOFFltlabelgt36 ltlabel class=btn btn-default action-foglight-1gtltinput type=radio name=

rarr˓foglight value=1gtONAUTOltlabelgt37 ltdivgt38 ltsamp id=action-foglight-output class=text-centergtltsampgt39 ltdivgt40 ltdivgt41 ltformgt42 ltdivgt43

44 ltscriptgt45 (function()46

47 var foglight = cfg state on 0 port 0 48 var $indicator = $(foglight indicator-foglight gt label)49 var $actionset = $(foglight action-foglight-set gt label)50

51 State amp UI update52 function update(data) 53 $extend(true foglight data)54 update indicator55 if (foglightstateport)56 $indicatorremoveClass(label-default)addClass(label-danger)57 else58 $indicatorremoveClass(label-danger)addClass(label-default)59 update buttons

(continues on next page)

348 Chapter 34 Scripting

Open Vehicles

(continued from previous page)

60 $actionsetremoveClass(active)61 $actionsetfind(input[value=+foglightstateon+])prop(checked true)

rarr˓parent()addClass(active)62 63

64 Listen to foglight events65 $(foglight)on(msgevent function(e event) 66 if (event == usrfoglighton)67 update( state port 1 )68 else if (event == usrfoglightoff)69 update( state port 0 )70 else if (event == vehicleoff) 71 update( state on 0 )72 $(action-foglight-output)empty()73 74 )75

76 Button action77 $(foglight action-foglight-set input)on(change function(e) 78 foglightstateon = $(this)val()79 loadcmd(script eval foglightset(+foglightstateon+) action-foglight-

rarr˓output)80 )81

82 Init amp install83 $(main)one(load function(ev) 84 loadcmd(script eval foglightinfo())then(function(output) 85 update(JSONparse(output))86 $(foglight)appendTo(panel-dashboard panel-body)show()87 )88 )89

90 )()91 ltscriptgt

341 Example Foglight 349

Open Vehicles

350 Chapter 34 Scripting

CHAPTER 35

CANopen

351 CANopen Basics

3511 Communication Objects

A CANopen network consists of ldquomastersrdquo and ldquoslavesrdquo masters are clients slaves are servers At most one mastermay be active at a time

CANopen supports addressing of up to 127 slaves on a bus using node IDs 1-127 Node address 0 is used for broadcaststo all nodes Node addressing is simply mapped onto CAN IDs by adding the node id to a base ID

The CANopen protocol mainly consists of

bull PDO (process data objects)

bull SDO (service data objects)

bull NMT (network management)

bull SYNC (synchronisation)

bull EMCY (emergency events)

PDO are regular normally periodical status update frames for example sensor data You can log them using theCAN monitor (can log start monitor ) PDOs can be sent at any CAN ID except those reserved forother CANopen services

SDO are memory registers of nodes that can be read and written by masters on request SDO requests are normally sentat ID 0x600 + nodeid responses at ID 0x580 + nodeid SDOs are addressed by a 16 bit index + 8 bit subindex Reg-isters and data types for a given device are documented by the device specific object dictionary normally representedas an EDS (electronic data sheet) file

NMT are short datagrams to control node startup shutdown Therersquos a special node state ldquopre-operationalrdquo allowingaccess to all operation and communication parameters of a node in a standardized way NMT requests are sent at ID0x000 responses and unsolicited updates (aka heartbeats) are sent at ID 0x700 + nodeid with length 1

SYNC messages are datagrams of length 0 normally sent at ID 0x080

351

Open Vehicles

EMCY messages are sent if a node encounters some kind of alert or warning condition they are normally sent at ID0x080 + nodeid with a length of 8 bytes

CAN IDs Communication objects0x000 NMT requests0x080 SYNC0x081 - 0x0FF EMCY0x581 - 0x5FF SDO responses0x601 - 0x67F SDO requests0x701 - 0x77F NMT responses heartbeats

So if any of these IDs look familiar to you chances are yoursquove got a CANopen network

Note CANopen coexists nicely with OBD-II and often does in a vehicle (ie Renault Twizy) OBD-II devicesnormally are addressed at IDs gt 0x780 so are outside the CANopen ID range Even if they use non-standard IDs thedevices normally will detect and ignore frames not matching their protocol

3512 SDO Addresses

The SDO address space layout is standardized

Index (hex) Object0000 not used0001-001F Static Data Types0020-003F Complex Data Types0040-005F Manufacturer Specific Complex Data Types0060-007F Device Profile Specific Static Data Types0080-009F Device Profile Specific Complex Data Types00A0-0FFF Reserved for further use1000-1FFF Communication Profile Area2000-5FFF Manufacturer Specific Profile Area6000-9FFF Standardised Device Profile AreaA000-BFFF Standardised Interface Profile AreaC000-FFFF Reserved for further use

See CiA DS301 for details on standard SDOs

For example a device shall tell about the PDOs it transmits or listens to their IDs update frequency and contentstructure at SDO registers 1400-1BFF This is mandatory in theory but real devices may not fully comply to that rule

CANopen compliant standard device types like motor controllers need to implement some standard profile registersSee CiA DS401 for the generic IO device class definition and CiA DS402 for motor controllers

Most devices will require some kind of login before allowing you to change operational parameters This is also doneusing SDO writes but there is no standard for this so yoursquoll need to dig into the device documentation

Of course therersquos a lot more on CANopen but this should get you going

3513 CAN in Automation

More info on the standard and specific device profiles can be found on the CiA website

352 Chapter 35 CANopen

Open Vehicles

httpswwwcan-ciaorg

CAN in Automation (CiA) is the international usersrsquo and manufacturersrsquo group for the CAN network (Controller AreaNetwork) internationally standardized in the ISO 11898 series The nonprofit association was established in 1992The aim is to provide an unbiased platform for future developments of the CAN protocol and to promote the image ofthe CAN technology

352 How to detect and identify CANopen nodes

So yoursquove got a CAN bus with some devices but you donrsquot know which of them speaks ldquoCANopenrdquo if any TheOVMS v3 will help you to detect them and open their CANs )

3521 Before you begin

you need to activate the CAN bus(es) yoursquore going to use As a CANopen master needs to write to the networkyou need to start the interfaces in active mode ie

OVMS can can1 start active 500000OVMS can can2 start active 125000

and then start the CANopen master for the bus(es) ie

OVMS copen can1 startOVMS copen can2 start

3522 Detecting CANopen nodes

The ldquoopenrdquo in ldquoCANopenrdquo means any implementation can decide how much of the standard it implements There aresome few mandatory features though a CANopen slave has to implement if it wants to comply with the standard

The mandatory features helping to detect and identify CANopen nodes on a CAN bus are

bull NMT (network management) especially RESET and PREOP

bull NMT bootup event messages

bull Standard SDO access in pre-operational mode

If yoursquove got CANopen nodes on a bus even silent ones issuing copen nmt reset will tell all of them toreboot and as bootup messages are mandatory you will see them in the OVMS log output like this

I (162904) canopen can1 node 1 new state Booting

The OVMS CANopen master continously monitors the network for NMT and EMCY messages After bootup of allnodes you can get a list of all nodes that have been detected by issuing metrics list co

OVMS metrics list cococan1nd1emcycodecocan1nd1emcytypecocan1nd1state Operational

Note if you request a reset nodes may decide to boot into pre-operational state That may produce some errormessages Donrsquot worry you can resolve this anytime by issuing copen nmt start

352 How to detect and identify CANopen nodes 353

Open Vehicles

3523 Identifying CANopen nodes

In pre-operational state a CANopen node must be accessible at the CANopen default IDs That means if the nodesupports SDO access we can query some standard attributes from it

Thatrsquos what copen info and copen scan do

bull copen info queries the standard device attributes from a specific node

bull copen scan queries all 127 node IDs

Caution There may be non-CANopen devices on the bus producing regular data frames at CANopen responseIDs andor reading and possibly misinterpreting CANopen requests sent to node IDs not planned by the manufac-turer Chances are low this triggers problems but you should be ready to switch off the vehicle when doing a scanndash just in case

A complete scan takes about 20 seconds A typical scan could look like this

OVMS level debug canopenOVMS copen can1 scanScan 1-127Node 1

Device type 0x00000000Error state 0x00Vendor ID 0x0000001eProduct 0x0712302dRevision 0x00010019SN 0x47c5Device name Gen4 (Renault Twizy)11 November 2011 12HW version 0x00000003SW version 07120001

Node 23 SDO access failedNode 25 SDO access failedNode 27 SDO access failedNode 30 SDO access failedNode 87 SDO access failedDoneD (227994) canopen ReadSDO 23 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (228194) canopen ReadSDO 25 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (228444) canopen ReadSDO 27 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (228844) canopen ReadSDO 30 0x100000 InitUpload failed CANopen error coderarr˓0xffffffffD (238384) canopen ReadSDO 87 0x100000 InitUpload failed CANopen error coderarr˓0xffffffff

This means one CANopen node was found and some non-CANopen frames were received on IDs 0x580 +23 +25+27 +30 and +87

3524 Great What now

As you now know therersquos a CANopen node you can look for documentation on it You can also try to access moredefault SDOs to see if you can control and configure the node

354 Chapter 35 CANopen

Open Vehicles

bull If yoursquore lucky the device will provide its own EDS file at SDO 102100 You can check that by issuing

OVMS copen ltbusgt readsdo ltnodeidgt 1021 0

bull Check out the CiA specifications for CANopen standards for example

ndash DS301 for details on general standard SDOs

ndash DS401 for the generic IO device class definition

ndash DS402 for motor controller SDOs

bull Look up the manufacturer of your device by itrsquos vendor ID

httpswwwcan-ciaorgservicescanopen-vendor-id

bull Contact the manufacturer of your device for specific documentation and EDS files

353 CANopen Shell Commands

Show status report

copen status

Start stop workers

copen ltbusgt startcopen ltbusgt stop

bull stop will fail if clients are still running

Send NMT commands

copen ltbusgt nmt ltstart|stop|preop|reset|commresetgt [id=0] [timeout_ms=0]

bull id 0 = broadcast

bull timeout gt 0 wait for state change (heartbeat) 3 tries Note state change response is not a mandatoryCANopen feature

Read SDO

copen ltbusgt readsdo ltidgt ltindex_hexgt ltsubindex_hexgt [timeout_ms=50]

bull index amp subindex hexadecimal without ldquo0xrdquo or ldquohrdquo

bull defaults to 3 tries on timeout

Write SDO

copen ltbusgt writesdo ltidgt ltindex_hexgt ltsubindex_hexgt ltvaluegt [timeout_ms=50]

bull index amp subindex hexadecimal without ldquo0xrdquo or ldquohrdquo

bull value prefix ldquo0xrdquo = hex else decimal string if no decimal

bull defaults to 3 tries on timeout

Show node core attributes

353 CANopen Shell Commands 355

Open Vehicles

copen ltbusgt info ltidgt [timeout_ms=50]

bull prints device type error register device name etc

bull Note some attributes read are optional and may be emptyzero

Scan bus for nodes

copen ltbusgt scan [[startid=1][-][endid=127]] [timeout_ms=50]

bull loops ldquoinfordquo over multiple node ids (default all)

bull Note a full scan with default timeout takes ~20 seconds

354 CANopen API Usage

3541 Synchronous API

The synchronous use is very simple all you need is a CANopenClient instance

On creation the client automatically connects to the active CANopen worker or starts a new worker instance if neces-sary

The CANopenClient methods will block until the job is done (or has failed) Job results andor error details arereturned in the caller provided job

Caution Do not make synchronous calls from code that may run in a restricted context eg within a metricupdate handler Avoid using synchronous calls from time critical code eg a CAN or event handler

Example

include canopenh

find CAN interfacecanbus bus = (canbus) MyPcpAppFindDeviceByName(can1) or simply use m_can1 if youre a vehicle subclass

create CANopen clientCANopenClient client(bus)

a CANopen job holds request and response dataCANopenJob job

read value from node 1 SDO 0x100800uint32_t valueif (clientReadSDO(ampjob 1 0x1008 0x00 (uint8_t)ampvalue sizeof(value)) == COR_OK) read result is now in value

start node 2 wait for presenceif (clientSendNMT(ampjob 2 CONC_Start true) == COR_OK)

node 2 is now started

(continues on next page)

356 Chapter 35 CANopen

Open Vehicles

(continued from previous page)

write value into node 3 SDO 0x234518if (clientWriteSDO(ampjob 3 0x2345 0x18 (uint8_t)ampvalue 0) == COR_OK)

value has now been written into register 0x234518

Main API methods

SendNMT send NMT request and optionally wait for NMT state change

aka heartbeat message

Note NMT responses are not a part of the CANopen NMT protocol and

sending heartbeat NMT state updates is optional for CANopen nodes

If the node sends no state info waiting for it will result in timeout

even though the state has in fact changed -- theres no way to know

if the node doesnt tell

CANopenResult_t SendNMT(CANopenJobamp job

uint8_t nodeid CANopenNMTCommand_t commandbool wait_for_state=false int resp_timeout_ms=1000 int max_tries=3)

ReceiveHB wait for next heartbeat message of a node

return state received

Use this to read the current state or synchronize to the heartbeat

Note heartbeats are optional in CANopen

CANopenResult_t ReceiveHB(CANopenJobamp job

uint8_t nodeid CANopenNMTState_t statebuf=NULLint recv_timeout_ms=1000 int max_tries=1)

ReadSDO read bytes from SDO server into buffer

- reads data into buf (up to bufsize bytes)

- returns data length read in jobsdoxfersize

- and data length available in jobsdocontsize (if known)

- remaining buffer space will be zeroed

- on result COR_ERR_BufferTooSmall the buffer has been filled up to bufsize

- on abort the CANopen error code can be retrieved from jobsdoerror

Note result interpretation is up to caller (check device object dictionary

for data types amp sizes) As CANopen is little endian as ESP32 we dont

need to check lengths on numerical results ie anything from int8_t to

uint32_t can simply be read into a uint32_t buffer

CANopenResult_t ReadSDO(CANopenJobamp job

uint8_t nodeid uint16_t index uint8_t subindex uint8_t buf size_t bufsizeint resp_timeout_ms=50 int max_tries=3)

WriteSDO write bytes from buffer into SDO server

- sends bufsize bytes from buf

- or 4 bytes from buf if bufsize is 0 (use for integer SDOs of unknown type)(continues on next page)

354 CANopen API Usage 357

Open Vehicles

(continued from previous page)

- returns data length sent in jobsdoxfersize

- on abort the CANopen error code can be retrieved from jobsdoerror

Note the caller needs to know data type amp size of the SDO register (check

device object dictionary) As CANopen servers normally are intelligent

anything from int8_t to uint32_t can simply be sent as a uint32_t with

bufsize=0 the server will know how to convert it

CANopenResult_t WriteSDO(CANopenJobamp job

uint8_t nodeid uint16_t index uint8_t subindex uint8_t buf size_t bufsizeint resp_timeout_ms=50 int max_tries=3)

If you want to create custom jobs use the low level method ExecuteJob() to execute them

3542 Asynchronous API

The CANopenAsyncClient class provides the asynchronous interface and the response queue

To use the asynchronous API you need to handle asynchronous responses which normally means adding a dedicatedtask for this A minimal handling would be to simply discard the responses (just empty the queue) if you donrsquot needto care about the results

Example

Instantiate the async client for a CAN bus and a queue size like this

CANopenAsyncClient m_async(m_can1 50)

Example response handler task

void MyAsyncTask()

CANopenJob jobwhile (true) if (m_asyncReceiveDone(job portMAX_DELAY) = COR_ERR_QueueEmpty)

process job results

Sending requests is following the same scheme as with the synchronous API Standard result code is COR_WAIT anerror may occur if the queue is full

if (m_asyncWriteSDO(m_nodeid index subindex (uint8_t)value 0) = COR_WAIT) handle error

Main API methods

The API methods are similar to the synchronous methods (see above)

358 Chapter 35 CANopen

Open Vehicles

CANopenResult_t SendNMT(uint8_t nodeid CANopenNMTCommand_t commandbool wait_for_state=false int resp_timeout_ms=1000 int max_tries=3)

CANopenResult_t ReceiveHB(uint8_t nodeid CANopenNMTState_t statebuf=NULLint recv_timeout_ms=1000 int max_tries=1)

CANopenResult_t ReadSDO(uint8_t nodeid uint16_t index uint8_t subindexuint8_t buf size_t bufsizeint resp_timeout_ms=100 int max_tries=3)

CANopenResult_t WriteSDO(uint8_t nodeid uint16_t index uint8_t subindexuint8_t buf size_t bufsizeint resp_timeout_ms=100 int max_tries=3)

CANopenJob objects are created automatically by these methods Jobs done need to be fetched by loopingReceiveDone() until it returns COR_ERR_QueueEmpty

If you want to create custom jobs use the low level method SubmitJob() to add them to the worker queue

3543 Error Handling

If an error occurs it will be given as a CANopenResult_t other than COR_OK or COR_WAIT either by a methodresult or by the CANopenJobresult field

Result codes are

COR_OK = 0

API levelCOR_WAIT job waiting to be processedCOR_ERR_UnknownJobTypeCOR_ERR_QueueFullCOR_ERR_QueueEmptyCOR_ERR_NoCANWriteCOR_ERR_ParamRangeCOR_ERR_BufferTooSmall

Protocol levelCOR_ERR_TimeoutCOR_ERR_SDO_AccessCOR_ERR_SDO_SegMismatch

General purpose application levelCOR_ERR_DeviceOffline = 0x80COR_ERR_UnknownDeviceCOR_ERR_LoginFailedCOR_ERR_StateChangeFailed

Additionally if an SDO readwrite error occurs an abortion error code may be given by the slave These codes followthe CANopen standard and may be extended by device specific codes

To translate a CANopenResult_t andor a known SDO abort code into a string use the CANopen class utilitymethods

stdstring GetAbortCodeName(const uint32_t abortcode)stdstring GetResultString(const CANopenResult_t result)

(continues on next page)

354 CANopen API Usage 359

Open Vehicles

(continued from previous page)

stdstring GetResultString(const CANopenResult_t result const uint32_t abortcode)stdstring GetResultString(const CANopenJobamp job)

Example

if (jobresult = COR_OK) ESP_LOGE(TAG Result for s sCANopenGetJobName(job)c_str()CANopenGetResultString(job)c_str())

3544 Custom Address Schemes

The standard clients use the CiA DS301 default IDs for node addressing ie

NMT request rarr 0x000NMT response rarr 0x700 + nodeidSDO request rarr 0x600 + nodeidSDO response rarr 0x580 + nodeid

If you need another address scheme create a sub class of CANopenAsyncClient or CANopenClient and over-ride the Init() methods as necessary

3545 More Code Examples

bull See shell commands in canopen_shellcpp

bull See classes SevconClient and SevconJob in the Twizy SEVCON module

360 Chapter 35 CANopen

CHAPTER 36

OVMS Server

361 Welcome

The OVMS (Open Vehicle Monitoring System) team is a group of enthusiasts who are developing a means to remotelycommunicate with our cars and are having fun while doing it

The OVMS module is a low-cost hardware device that you install in your car simply by installing a SIM card con-necting the module to your carrsquos Diagnostic port connector and positioning a cellular antenna Once connected theOVMS module enables remote control and monitoring of your car

This guide documents the installation and operation of an OVMS server

You should however start by asking yourself the question lsquodo I need thisrsquo You donrsquot need to run your own OVMSserver as you can just use one of the public Open Vehicles OVMS servers The choice is yours

362 Installation

3621 Prerequisites

Yoursquoll need a Linux OSX BSD or other flavour of Unix server with a public IP address and a shell account able tosetup a daemon listening on a port Yoursquoll need a modern version of perl running on that server and a bunch of perlmodules (from cpan)

Yoursquoll need a MYSQL server running on the same machine or another machine and credentials to be able to create adatabase and accounts

This could possibly run on a windows server but you are on your own -) [ let us know instructions if you manage toget it running ]

3622 Clone from GitHub

Start the installation with a clone from GitHub

361

Open Vehicles

git clone httpsgithubcomopenvehiclesOpen-Vehicle-Servergit

You can then change into the v3server directory and start the installation process

3623 Perl Module Installation

You will need at a minimum the following modules from CPAN (or from your distributionrsquos package manager)

bull ConfigIniFiles

bull DigestMD5

bull DigestHMAC

bull CryptRC4XS

bull MIMEBase64

bull DBI

bull DBDmysql

bull EV

bull AnyEvent

bull AnyEventHTTP

bull AnyEventHTTPD

bull HTTPParserXS

bull DataUUID

bull EmailMIME

bull EmailSenderSimple

bull NetSSLeay

bull JSONXS

bull ProtocolWebSocket

bull TimePiece

3624 MySQL Setup

Create a mysql database ldquoopenvehiclesrdquo and use the ovms_serversql script to create the necessary ovms_ tablesCreate a mysql username and password with access to the database

Insert a record into the ovms_cars table to give you access to your own car

vehicleid DEMOowner 1carpass DEMOuserpass DEMOcryptscheme 0v_ptokenv_lastupdate 0000-00-00 000000

362 Chapter 36 OVMS Server

Open Vehicles

Obviously change the vehicleid carpass and userpass as necessary The only required fields are vehicleid and carpass

If you are upgrading from server v2 to v3 you can instead source the ovms_server_v2_to_v3sql code to migrate yourdatabase schema

3625 OVMS Server Configuration

Copy confovms_serverconfdefault to confovms_serverconf to provide a template for your configuration Thenmodify the configuration as appropriate

3626 OVMS Server Access to MySQL

In the configovms_serverconf file define the access to the mysql database

[db]path=DBImysqldatabase=openvehicleshost=127001user=ltmysqlusernamegtpass=ltmysqlpasswordgt

If the host is remote change the host= parameter to be the remote IP address Use 127001 for local

Test the connection with

$ mysql -h 127001 -u ltmysqlusernamegt -pEnter password ltmysqlpasswordgtWelcome to the MySQL monitor Commands end with or g

If you get ldquoERROR 1044 (42000) Access deniedrdquo fix it before proceeding The most likely cause is a mistake inyour mysql user grant rights

3627 Enable SSL (optional)

If you want to support SSL connections to your server (port 6869 for the REST API port 6870 for OVMS MP) youneed to supply a certificate You can create a self-signed certificate or get a certificate signed by some root CA foryour server

In both cases you need to merge the private key PEM and the chain PEM into the file ldquoovms_serverpemrdquo located inthe same directory as the ldquoovms_serverplrdquo Also take care to secure the file as it now contains your private key

To create a self-signed certificate do

$ openssl req -sha256 -newkey rsa4096 -nodes -keyout privkeypem -x509 -days 365 -rarr˓out fullchainpem$ cat privkeypem fullchainpem gtconfovms_serverpem$ chmod 0600 confovms_serverpem

Or if you want to reuse eg your Letrsquos Encrypt server certificate do this as root

cat etcletsencryptliveyourhostprivkeypem etcletsencryptliveyourhostrarr˓fullchainpem gtconfovms_serverpem chmod 0600 confvms_serverpem chown youruid confovms_serverpem

and add a cron job or certbot hook to check for renewals and redo these steps as necessary

362 Installation 363

Open Vehicles

3628 Configure the Plugins

The OVMS Server v3 is based on a pluggable architecture The plugins themselves are stored in pluginssystem andpluginslocal directories You must configure (in confovms_serverconf) the plugins that you require

We recommend the following

[plugins]load=ltltEOTVECEDbDBIAuthDrupalApiV2PushPushAPNSPushGCMPushMAILApiHttpApiHttpCoreApiHttpMqapiEOT

3629 Run The Server

You can run the server manually with

$ ovms_serverpl

If your linux host is running systemd you can also look at supportovms_serverservice and supportovmslogrotate asexamples for how you can run this as a background daemon

7 ENJOY

Any questionscomments please let us know

Mark Webb-Johnson March 2020

363 Plugins

3631 ApiHttp

This plugin provides an HTTP (and optional HTTPS) server and is used by subsequent API plugins to provide HTTPservices The HTTP server is on port tcp6868 If you provide a confovms_serverpem file it will also use that tolaunch a HTTPS server on port tcp6869

3632 ApiHttpCore

This plugin provides support for the HTTP API in OVMS Server v3 It supports the api HTTP endpoint

If you want to use this plugin you need to also include lsquoApiHttprsquo before loading this

364 Chapter 36 OVMS Server

Open Vehicles

3633 ApiHttpFile

This plugin provides support serving static files from the httpfiles directory It supports the file HTTP endpoint

If you want to use this plugin you need to also include lsquoApiHttprsquo before loading this

3634 ApiHttpMqapi

This plugin provides support for Mosquitto API functions for authentication and ACL access control It supports themqapi HTTP endpoint

If you want to use this plugin you need to also include lsquoApiHttprsquo before loading this

You will also need to configure your mosquittoconf to include

auth_opt_superusers ltyour-superuser-usernamegtauth_opt_acl_cacheseconds 300auth_opt_auth_cacheseconds 300auth_opt_backends httpauth_opt_http_ip 127001auth_opt_http_port 6868auth_opt_http_getuser_uri mqapiauthauth_opt_http_superuser_uri mqapisuperuserauth_opt_http_aclcheck_uri mqapiacl

3635 ApiV2

This plugin provides support for the v2 OVMS protocol including crypto protocols 0x30 and 0x31 It provides a rawv2 protocol server on tcp6867 If you provide a confovms_serverpem file it will also launch an SSL enabled v2protocol server on tcp6870

3636 AuthDrupal

This plugin provides support for authentication via the Drupal database It also provides a facility to periodicallysynchronise drupal users to OVMS owner table records

Note that only one Auth plugin should be enabled

3637 AuthNone

This is a stub authentication plugin It will always fail authentication and is only provided as an example (or for usein systems where user authentication is not required)

Note that only one Auth plugin should be enabled

3638 DbDBI

This is the core database plugin for perl DBI style SQL databases It is used for example to provide access to MySQLdatabases

363 Plugins 365

Open Vehicles

3639 Push

This provides the core support for Push Notifications The actual notifications themselves are issued by sub-pluginswhich register with this

36310 PushAPNS

This plugin supports the lsquoapnsrsquo notification type for push notifications to Apple devices (iPhones iPadsetc) It requires apple certificates in PEM format to be placed in confovms_apns_sandboxpem andconfovms_apns_productionpem

36311 PushGCM

This plugin supports the lsquogcmrsquo notification type for push notifications to Android devices It requires a google APIkey to be placed in the confovms_serverconf file under [gcm] section parameter lsquoapikeyrsquo You can obtain that keyby

Log in to your Google account Open httpsdevelopersgooglecommobileadd Select platform ldquoAndroidrdquo Enter an arbitrary project name eg ldquoMyOvmsServerrdquo Package name should be ldquocomopenvehiclesOVMSrdquo Activate ldquoCloud Messagingrdquo and generate the key Note the API key and project number (= GCM sender ID)

36312 PushMAIL

This plugin supports the lsquomailrsquo notification type for push notifications by eMail It simply requires a sendmail stylemailer installed on the server

You can configure confovms_serverconf [mail] section parameter lsquosenderrsquo as the sender address to be used (otherwisedefaulting to lsquonotificationsopenvehiclescomrsquo

36313 VECE

This plugin extends the notification system to translate error codes into textual error messgaes It uses files in the vecedirectory named ltvehicletypegtvece (for example trvece vavece etc)

The vece files themselves are ini style files

366 Chapter 36 OVMS Server

CHAPTER 37

OVMS Protocol v2

371 Welcome

The OVMS (Open Vehicle Monitoring System) team is a group of enthusiasts who are developing a means to remotelycommunicate with our cars and are having fun while doing it

The OVMS module is a low-cost hardware device that you install in your car simply by installing a SIM card con-necting the module to your carrsquos Diagnostic port connector and positioning a cellular antenna Once connected theOVMS module enables remote control and monitoring of your car

This developerrsquos guide documents version 2 of the OVMS protocol

372 Terms

Server The OVMS server

Car The OVMS car module

App An OVMS client application one of

bull Active client interactive user applications ie mobile App (Note the car module will raise the updatefrequency when active clients are connected)

bull Batch client a non-interactive application ie shell script

373 Startup

On startup there is no bannerwelcome message from the server The caller initiates the protocol by sending a welcomemessage to the server

1 For cars

MP-C ltprotection schemegt lttokengt ltdigestgt ltcar idgt

367

Open Vehicles

2 For interactive user apps

MP-A ltprotection schemegt lttokengt ltdigestgt ltcar idgt

3 For noninteractive batch apps

MP-B ltprotection schemegt lttokengt ltdigestgt ltcar idgt

4 For servers

MP-S ltprotection schemegt lttokengt ltdigestgt ltcar idgt

The server responds with a welcome message to the caller

MP-S ltprotection schemegt lttokengt ltdigestgt

374 Encryption Scheme 0x30

This scheme is based on using shared secrets hmac digest for authentication and encryption key negotiation withRC4 stream cipher and base64 encoding

Upon startup both the server and callers generate random tokens (encoded as textual characters) Each party thenhmac-md5s the token with the shared secret to create a digest base64 encoded

Note that the server will only issue itrsquos welcome message after receiving and validating the callerrsquos welcome message

Validation of the welcome message is performed by

1 Checking the received token to ensure that it is different from its own token and aborting the connection if thesame

2 Hmac-md5s the received token with the shared secret and comparing the result to the received digest

3 If the digest match then the partner had authenticated itself (proven it knows the shared secret or has listenedto a previous conversation)

4 If the digests donrsquot match then abort the connection as the partner doesnrsquot agree with the shared secret

Once the partner has been authenticated

1 Create a new hmac-md5 based on the client and server tokens concatenated with the shared secret

2 Use the new hmac digest as the key for symmetric rc4 encryption

3 Generate and discard 1024 bytes of cipher text

From this point on messages are rc4 encrypted and base64 encoded before transmission Lines are terminated withCR+LF

375 Encryption Scheme 0x31

This scheme is based on server authentication and is supported in OVMS server v3 and later Typically serversprovide two methods of authentication

bull Username + Password The usual username and associated password as used when registering on the server

bull Username + ApiToken An API token based authentication scheme where each user may maintain one or moreaccess tokens (which can be created or revoked at will)

The arguments to the MP- startup command are

bull ltprotection schemegt Must be set to lsquo1rsquo (0x31)

368 Chapter 37 OVMS Protocol v2

Open Vehicles

bull lttokengt Must be the username pre-registered with the server

bull ltdigestgt Must be the password or api token for that user

bull ltcar idgt Must be the vehicle ID to connect to or the special value lsquorsquo to request connection to the first vehicleon that userrsquos account

Once the partner has been authenticated a response lsquoMP-S 1 ltusergt ltvehicleidgt ltlist-of-all-other-vehiclesgtrsquo will besent from the server to indicate a successful authentication

From then onwards the messages are in plaintext with no further encryption or encoding Lines are terminated withCR+LF

Note that this scheme is intended to be used with external encryption schemes such as SSLTLS

376 Auto Provisioning

A caller can perform auto-provisioning at any time (authenticated or not) However only one auto-provision can beperformed for each connection

Auto-Provisioning relies on two secrets known both to the server and client The first is usually the VIN of the vehicleand the second is usually the ICCID of the SIM card in the vehicle module The reason these two are chosen is thatthey can be auto-determined by the vehicle module but also clearly seen by the user (for entry into the server)

The mechanism works by the client module first determining its VIN and ICCID secrets then connecting to the serverand sending a AP-C message to the server proving its VIN The server will then lookup the auto-provisioning recordand reply with that to the client (via a AP-S or AP-X message)

The auto-provisioning record itself is platform dependent but will typically be an ordered space separated list ofparameter values For OVMS hardware and OVMSX PIC firmware these are merely parameters 0 1 2 etc tobe stored in the car module

3761 Auto Provisioning Protection Scheme 0x30

1 For cars

AP-C ltprotection schemegt ltapkeygt

2 For servers

AP-S ltprotection schemegt ltserver tokengt ltserver digestgt ltprovisioninggt

AP-X

When the provisioning record is created at the server a random token is generated (encoded as textual characters) Theserver then hmac-md5s this token with the shared secret (usually the ICCID known by the server) to create a digestbase64 encoded Using this hmac digest the server generates and discards 1024 bytes of cipher text The serverthen rc4 encrypts and base64 encodes the provisioning information and stores its token digest and encoded provisionrecord ready for the client to request

The car knows its VIN and ICCID With this information it makes a connection to the OVMS service on the serverand provides the VIN as the ltapkeygt in a AP-C message to the server

The server will ensure that it only responds to one AP-C message for any one connection Once responded allsubsequent AP-C requests will always be replied with a AP-X message

Upon receiving the AP-C message the server looks up any provisioning records it has for the given ltapkeygt If it hasnone it replies with an AP-X message

376 Auto Provisioning 369

Open Vehicles

If the server does find a matching provisioning record it replies with an AP-S message sending the previously savedserver token digest and encoded provisioning record to the car

If the car receives an AP-X message it knows that auto-provisioning was not successful

If the car receives an AP-S message it can first validate the server authenticity By producing its own hmac-md5 ofthe server token and secret ICCID the car can validate the server-provided digest is as expected If this validation stepdoes not succeed the car should abort the auto-provisioning

If acceptable the car can decrypt the provisioning record by first generating and discarding 1024 bytes of cipher textthen decoding the provisioning record provided by the server

377 Backwards Compatibility

Typically comma-separated lists are used to transmit parameters Applications Servers and the Car firmware shouldin general ignore extra parameters not expected In this way the protocol messages can be extended by adding extraparameters without breaking old AppsCars that donrsquot expect the new parameters

Similarly unrecognized messages should due ignored Unrecognised commands in the ldquoCrdquo (command) messageshould be responded to with a generic ldquounrecognizedrdquo response (in the ldquocrdquo (command response) messages)

378 Messages

3781 Car lt-gt Server lt-gt App

After discarding CR+LF line termination and base64 decoding the following protocol messages are defined

ltmessagegt = ltmagicgt ltversiongt ltspacegt ltprotmsggt

ltmagicgt = MP-

ltversiongt = 1 byte version number - this protocol is 0x30

ltspacegt = lsquo lsquo (ascii 0x20)

ltprotmsggt = ltservertocargt | ltcartoservergt | ltservertoappgt | ltapptoservergt

ltservertocargt - ldquoSrdquo ltpayloadgt

ltcartoservergt = ldquoCrdquo ltpayloadgt

ltservertoappgt = ldquosrdquo ltpayloadgt

ltapptoservergt = ldquocrdquo ltpayloadgt

ltpayloadgt = ltcodegt ltdatagt

ltcodegt = 1 byte instruction code

ltdatagt = N bytes data (dependent on instruction code)

3782 Ping message 0x41 ldquoArdquo

This message may be sent by any party to test the link The expected response is a 0x61 ping acknowledgementThere is no expected payload to this message an any given can be discarded

370 Chapter 37 OVMS Protocol v2

Open Vehicles

3783 Ping Acknowledgement message 0x61 ldquoardquo

This message is sent in response to a 0x41 ping message There is no expected payload to this message an any givencan be discarded

3784 Command message 0x43 ldquoCrdquo

This message is sent ltapptoservergt then ltservertocargt and carries a command to be executed on the car The messagewould normally be paranoid-encrypted

ltdatagt is a comma-separated list of

bull command (a command code 065535)

bull parameters (dependent on the command code)

For further information on command codes and parameters see the command section below

3785 Command response 0x63 ldquocrdquo

This message is sent ltcartoservergt then ltservertoappgt and carries the response to a command executed on the carThe message would normally be paranoid-encrypted

ltdatagt is a comma-separated list of

bull command (a command code 065535)

bull result (0=ok 1=failed 2=unsupported 3=unimplemented)

bull parameters (dependent on the command code and result)

For result=0 the parameters depend on the command being responded to (see the command section below for furtherinformation)

For result=1 the parameter is a textual string describing the fault

For result=2 or 3 the parameter is not used

3786 Car Environment message 0x44 ldquoDrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the environment settings of the vehicle

ltdatagt is comma-separated list of

Door state 1

bull bit0 = Left Door (open=1closed=0)

bull bit1 = Right Door (open=1closed=0)

bull bit2 = Charge port (open=1closed=0)

bull bit3 = Pilot present (true=1false=0) (always 1 on my 25)

bull bit4 = Charging (true=1false=0)

bull bit5 = always 1

bull bit6 = Hand brake applied (true=1false=0)

bull bit7 = Car ON (ldquoignitionrdquo) (true=1false=0)

378 Messages 371

Open Vehicles

Door state 2

bull bit3 = Car Locked (locked=1unlocked=0)

bull bit4 = Valet Mode (active=1inactive=0)

bull bit6 = Bonnet (open=1closed=0)

bull bit7 = Trunk (open=1closed=0)

LockUnlock state

bull 4 = car is locked

bull 5 = car is unlocked

Temperature of the PEM (celcius)

Temperature of the Motor (celcius)

Temperature of the Battery (celcius)

Car trip meter (in 110th of a distance unit)

Car odometer (in 110th of a distance unit)

Car speed (in distance units per hour)

Car parking timer (0 for not parked or number of seconds car parked for)

Ambient Temperature (in Celcius)

Door state 3

bull bit0 = Car awake (turned on=1 off=0)

bull bit1 = Cooling pump (on=1off=0)

bull bit6 = 1=Logged into motor controller

bull bit7 = 1=Motor controller in configuration mode

Stale PEMMotorBattery temps indicator (-1=none 0=stale gt0 ok)

Stale ambient temp indicator (-1=none 0=stale gt0 ok)

Vehicle 12V line voltage

Door State 4

bull bit2 = alarm sounds (on=1off=0)

Reference voltage for 12v power

Door State 5

bull bit0 = Rear left door (open=1closed=0)

bull bit1 = Rear right door (open=1closed=0)

bull bit2 = Frunk (open=1closed=0)

bull bit4 = 12V battery charging

bull bit5 = Auxiliary 12V systems online

bull bit7 = HVAC running

372 Chapter 37 OVMS Protocol v2

Open Vehicles

Temperature of the Charger (celsius)

Vehicle 12V current (ie DC converter output)

Cabin temperature (celsius)

3787 Paranoid-mode encrypted message 0x45 ldquoErdquo

This message is sent for any of the four message ltprotmsggt types and represents an encrypted transmission that theserver should just relay (or is relaying) without being able to interpret it The encryption is based on a shared secretbetween the car and the apps to which the server is not privy

ltdatagt is

bull ltparanoidtokengt | ltparanoidcodegt

bull ltparanoidtokengt = ldquoTrdquo ltptokengt

bull ltparanoidcodegt = ldquoMrdquo ltcodegt ltdatagt

In the case of ltparanoidtokengt the ltptokengt is a random token that represent the encryption key It can only besent ltcartoservergt or ltservertoappgt Upon receiving this token the server discards all previously stored paranoidmessages sends it on to all connected apps and then stores the token Every time an app connects the server alsosends this token to the app

In the case of ltparanoidcodegt the ltcodegt is a sub-message code and can be any of the codes listed in this document(except for ldquoArdquo ldquoardquo and ldquoErdquo) The ltdatagt is the corresponding encrypted payload message The encryption isperformed on the ltdatagt by

bull Create a new hmac-md5 based on the ltptokengt with the shared secret

bull Use the new hmac digest as the key for symmetric rc4 encryption

bull Generate and discard 1024 bytes of cipher text

and the data is base64 encoded Upon receiving a paranoid message from the car the server forwards it on the allconnected apps and then stores the message Every time an app connects the server sends all such stored messagesUpon receiving a paranoid message from an app if the car is connected the server merely forwards it on to the carotherwise discarding it

3788 Car firmware message 0x46 ldquoFrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the firmware versions of the vehicle

ltdatagt is comma-separated list of

bull OVMS firmware version

bull VIN (vehicle identification number)

bull Current network signal quality (Wifi GSM in SQ units)

bull Write-enabled firmware (0=read-only 1=write-enabled)

bull Vehicle type code (eg TR = Tesla Roadster see command output vehicle list)

bull Current network name (Wifi SSID GSM provider)

bull Distance to next scheduled maintenanceservice [km]

bull Time to next scheduled maintenanceservice [seconds]

bull OVMS hardware version

378 Messages 373

Open Vehicles

3789 Server firmware message 0x66 ldquofrdquo

This message is sent ltservertocargt ldquoSrdquo or ltservertoappgt ldquosrdquo and transmits the firmware versions of the server

ltdatagt is comma-separated list of

bull Server firmware version

37810 Car group subscription message 0x47 ldquoGrdquo

This message is sent ltapptoservergt ldquoArdquo and requests subscription to the specified group

ltdatagt is comma-separated list of

bull Group name

37811 Car group update message 0x67 ldquogrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits a group location message for the vehicle

ltdatagt is comma-separated list of

bull Vehicle ID (only ltservertoappgt not sent ltcartoservergt)

bull Group name

bull Car SOC

bull Car Speed

bull Car direction

bull Car altitude

bull Car GPS lock (0=nogps 1=goodgps)

bull Stale GPS indicator (-1=none 0=stale gt0 ok)

bull Car latitude

bull Car longitude

37812 Historical Data update message 0x48 ldquoHrdquo

This message is sent ltcartoservergt ldquoC and transmits a historical data message for storage on the server

ltdatagt is comma-separated list of

bull type (unique storage class identification type)

bull recordnumber (integer record number)

bull lifetime (in seconds)

bull data (a blob of data to be dealt with as the application requires)

The lifetime is specified in seconds and indicates to the server the minimum time the vehicle expects the server toretain the historical data for Consideration should be made as to server storage and bandwidth requirements

The type is composed of ltvehicletypegt - ltclassgt - ltpropertygt

ltVehicletypegt is the usual vehicle type or lsquorsquo to indicate generic storage suitable for all vehicles

374 Chapter 37 OVMS Protocol v2

Open Vehicles

ltClassgt is one of

bull PWR (power)

bull ENG (engine)

bull TRX (transmission)

bull CHS (chassis)

bull BDY (body)

bull ELC (electrics)

bull SAF (safety)

bull SEC (security)

bull CMF (comfort)

bull ENT (entertainment)

bull COM (communications)

bull X (unclassified and experimental with replaced with 2 digits code)

ltPropertygt is a property code which the vehicle decides

The server will timestamp the incoming historical records and will set an expiry date of timestamp + ltlifetimegtseconds The server will endeavor to retain the records for that time period but may expend data earlier if necessary

37813 Historical Data update+ack message 0x68 ldquohrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltsevertocargt ldquocrdquo and transmitsacknowledges historical data message forstorage on the server

For ltcartoservergt the ltdatagt is comma-separated list of

bull ackcode (an acknowledgement code)

bull timediff (in seconds)

bull type (unique storage class identification type)

bull recordnumber (integer record number)

bull lifetime (in seconds)

bull data (a blob of data to be dealt with as the application requires)

The ackcode is a numeric acknowledgement code - if the server successfully receives the message it will reply withldquohrdquo and this ackcode to acknowledge reception

The timediff is the time difference in seconds to use when storing the record (eg -3600 would indicate the recorddata is from one hour ago)

The lifetime is specified in seconds and indicates to the server the minimum time the vehicle expects the server toretain the historical data for Consideration should be made as to server storage and bandwidth requirements

For ltservertocargt the ltdatagt is

bull ackcode (an acknowledgement code)

The ltcartoservergt message sends the data to the server The ltservertocargt message acknowledges the data

378 Messages 375

Open Vehicles

37814 Push notification message 0x50 ldquoPrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo When used by the car it requests the server to send atextual push notification alert message to all apps registered for this car The ltdatagt is 1 byte alert type followed by Nbytes of textual message The server will use this message to send the notification to any connected apps and can alsosend via external mobile frameworks for unconnected apps

37815 Push notification subscription 0x70 ldquoprdquo

This message is sent ltapptoservergt Ardquo It is used by app to register for push notifications and is normally at the startof a connection The ltdatagt is made up of

ltappidgtltpushtypegtltpushkeytypegtltvehicleidgtltnetpassgtltpushkeyvaluegt

The server will verify the credentials for each vehicle and store the required notification information

Note As of June 2020 only one vehicleid can be subscribed at a time If multiple vehicles are required then theyshould each be subscribed in individual messages

37816 Server -gt Server Record message 0x52 ldquoRrdquo

This message is sent ltservertoservergt ldquoSrdquo and transmits an update to synchronized database table records

Sub-type RV (Vehicle record) ltdatagt is comma-separated list of

bull Vehicleid

bull Owner

bull Carpass

bull v_server

bull deleted

bull changed

Sub-type RO (Owner record) ltdatagt is comma-separated list of

bull Ownerid

bull OwnerName

bull OwnerMail

bull PasswordHash

bull OwnerStatus

bull deleted

bull changed

37817 Server -gt Server Message Replication message 0x72 ldquorrdquo

This message is sent ltservertoservergt ldquoSrdquo and replicates a message for a particular car

ltdatagt is comma-separated list of

bull vehicleid

bull message code

376 Chapter 37 OVMS Protocol v2

Open Vehicles

bull message data

37818 Car state message 0x53 ldquoSrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the last known status of the vehicle

ltdatagt is comma-separated list of

bull SOC

bull Units (ldquoMrdquo for miles ldquoKrdquo for kilometers)

bull Line voltage

bull Charge current (amps)

bull Charge state (charging topoff done prepare heating stopped)

bull Charge mode (standard storage range performance)

bull Ideal range

bull Estimated range

bull Charge limit (amps)

bull Charge duration (minutes)

bull Charger B4 byte (tba)

bull Charge energy consumed (110 kWh)

bull Charge sub-state

bull Charge state (as a number)

bull Charge mode (as a number)

bull Charge Timer mode (0=onplugin 1=timer)

bull Charge Timer start time

bull Charge timer stale (-1=none 0=stale gt0 ok)

bull Vehicle CAC100 value (calculated amp hour capacity in Ah)

bull ACC Mins remaining until car will be full

bull ACC Mins remaining until car reaches charge limit

bull ACC Configured range limit

bull ACC Configured SOC limit

bull Cooldown Car is cooling down (0=no 1=yes)

bull Cooldown Lower limit for battery temperature

bull Cooldown Time limit (minutes) for cooldown

bull ACC charge time estimation for current charger capabilities (min)

bull Charge ETR for range limit (min)

bull Charge ETR for SOC limit (min)

bull Max ideal range

378 Messages 377

Open Vehicles

bull Chargeplug type ID according to OpenChargeMapsorg connectiontypes (see httpapiopenchargemapiov2referencedata)

bull Charge power output (kW)

bull Battery voltage (V)

bull Battery SOH (state of health) ()

bull Charge power input (kW)

bull Charger efficiency ()

bull Battery current (A)

bull Battery ideal range gainloss speed (mphkph gain=positive)

37819 Car update time message 0x53 ldquoTrdquo

This message is sent ltservertoappgt ldquosrdquo and transmits the last known update time of the vehicle

ltdatagt is the number of seconds since the car last sent an update message

37820 Car location message 0x4C ldquoLrdquo

This message is sent ltcartoservergt ldquoCrdquo and transmits the last known location of the vehicle

ltdatagt is comma-separated list of

bull Latitude

bull Longitude

bull Car direction

bull Car altitude

bull Car GPS lock (0=nogps 1=goodgps)

bull Stale GPS indicator (-1=none 0=stale gt0 ok)

bull Car speed (in distance units per hour)

bull Car trip meter (in 110th of a distance unit)

bull Drive mode (car specific encoding of current drive mode)

bull Battery power level (in kW negative = charging)

bull Energy used (in Wh)

bull Energy recovered (in Wh)

bull Inverter motor power (kW) (positive = output)

bull Inverter efficiency ()

bull GPS mode indicator (see below)

bull GPS satellite count

bull GPS HDOP (see below)

bull GPS speed (in distance units per hour)

378 Chapter 37 OVMS Protocol v2

Open Vehicles

GPS mode indicator this shows the NMEA receiver mode If using the SIM5360 modem for GPS this is a twocharacter string The first character represents the GPS receiver mode the second the GLONASS receiver mode Eachmode character may be one of

bull N = No fix Satellite system not used in position fix or fix not valid

bull A = Autonomous Satellite system used in non-differential mode in position fix

bull D = Differential (including all OmniSTAR services) Satellite system used in differential mode in position fix

bull P = Precise Satellite system used in precision mode Precision mode is defined as no deliberate degradation(such as Selective Availability) and higher resolution code (P-code) is used to compute position fix

bull R = Real Time Kinematic Satellite system used in RTK mode with fixed integers

bull F = Float RTK Satellite system used in real time kinematic mode with floating integers

bull E = Estimated (dead reckoning) Mode

bull M = Manual Input Mode

bull S = Simulator Mode

GPS HDOP HDOP = horizontal dilution of precision This is a measure for the currently achievable precision ofthe horizontal coordinates (latitude amp longitude) which depends on the momentary relative satellite positions andvisibility to the device

The lower the value the higher the precision Values up to 2 mean high precision up to 5 is good If the value ishigher than 20 coordinates may be off by 300 meters from the actual position

See httpsenwikipediaorgwikiDilution_of_precision_(navigation) for further details

37821 Car Capabilities message 0x56 ldquoVrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the vehicle capabilities It was introducedwith v2 of the protocol

ltdata is comma-separated list of vehicle capabilities of the form

bull Cltcmdgt indicates vehicle support command ltcmdgt

bull CltcmdLgt-ltcmdHgt indicates vehicle will support all commands in the specified range

37822 Car TPMS message 0x57 ldquoWrdquo (oldobsolete)

Note Message ldquoWrdquo has been replaced by ldquoYrdquo (see below) for OVMS V3 The V3 module will still send ldquoWrdquomessages along with ldquoYrdquo for old clients for some time Clients shall adapt to using ldquoYrdquo if available ASAP ldquoWrdquomessages will be removed from V3 in the near future

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the last known TPMS values of thevehicle

ltdatagt is comma-separated list of

bull front-right wheel pressure (psi)

bull front-right wheel temperature (celcius)

bull rear-right wheel pressure (psi)

bull rear-right wheel temperature (celcius)

378 Messages 379

Open Vehicles

bull front-left wheel pressure (psi)

bull front-left wheel temperature (celcius)

bull rear-left wheel pressure (psi)

bull rear-left wheel temperature (celcius)

bull Stale TPMS indicator (-1=none 0=stale gt0 ok)

37823 Car TPMS message 0x59 ldquoYrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits the last known TPMS values of thevehicle

ltdatagt is comma-separated list of

bull number of defined wheel names

bull list of defined wheel names

bull number of defined pressures

bull list of defined pressures (kPa)

bull pressures validity indicator (-1=undefined 0=stale 1=valid)

bull number of defined temperatures

bull list of defined temperatures (Celcius)

bull temperatures validity indicator (-1=undefined 0=stale 1=valid)

bull number of defined health states

bull list of defined health states (Percent)

bull health states validity indicator (-1=undefined 0=stale 1=valid)

bull number of defined alert levels

bull list of defined alert levels (0=none 1=warning 2=alert)

bull alert levels validity indicator (-1=undefined 0=stale 1=valid)

Note Pressures are transported in kPa now instead of the former PSI To convert to PSI multiply by014503773773020923

37824 Peer connection message 0x5A ldquoZrdquo

This message is sent ltservertocargt or ltservertoappgt to indicate the connection status of the peer (car for ltserver-toappgt interactive apps for ltservertocargt) It indicates how many peers are currently connected

It is suggested that the car should use this to immediately report on and to increase the report frequency of status - inthe case that one or more interactive Apps are connected and watching the car

Batch client connections do not trigger any peer count change for the car but they still receive the car peer status fromthe server

ltdatagt is

bull Number of peers connected expressed as a decimal string

380 Chapter 37 OVMS Protocol v2

Open Vehicles

37825 Car export power message 0x47 ldquoGrdquo

This message is sent ltcartoservergt ldquoCrdquo or ltservertoappgt ldquosrdquo and transmits ldquovgrdquo metrics from the vehicle

ltdatagt is comma-separated list of

bull vggenerating (1 = currently delivering power)

bull vgpilot (1 = pilot present)

bull vgvoltage (in V)

bull vgcurrent (in A)

bull vgpower (in kW)

bull vgefficiency (in )

bull vgtype (eg ldquochademordquo)

bull vgstate (eg ldquoexportingrdquo)

bull vgsubstate (eg ldquoonrequestrdquo)

bull vgmode (eg ldquostandardrdquo)

bull vgclimit (in A)

bull vglimitrange (in km)

bull vglimitsoc (in )

bull vgkwh (in kWh)

bull vgkwhgrid (in kWh)

bull vgkwhgridtotal (in kWh)

bull vgtime (in s)

bull vgtimermode (1 = generator timer enabled)

bull vgtimerstart

bull vgdurationempty (in min)

bull vgdurationrange (in min)

bull vgdurationsoc (in min)

bull vgtemp (in deg C)

Refer httpsdocsopenvehiclescomenlatestuserguidemetricshtml

379 Commands

3791 Commands and Expected Responses

For message types ldquoCrdquo and ldquocrdquo the following commands and responses are expected to be supported

379 Commands 381

Open Vehicles

3792 1 - Request feature list

Command parameters are unused and ignored by the car

Response is a sequence of individual messages with each message containing the following parameters

bull feature number

bull maximum number of features

bull feature value

Registered features are

bull 0 Digital SPEEDO (experimental)

bull 8 Location STREAM mode (consumes more bandwidth)

bull 9 Minimum SOC

bull 15 CAN bus can write-enabled

Note that features 0 through 7 are lsquovolatilersquo and will be lost (reset to zero value) if the power is lost to the car moduleor module is reprogrammed These features are considered extremely experimental and potentially dangerous

Features 8 through 15 are lsquopermanentrsquo and will be stored as parameters 23 through 31 These features are consideredmore stable but optional

3793 2 - Set feature

Command parameters are

bull feature number to set

bull value to set

Response parameters are unused and will merely indicate the success or not of the result

3794 3 - Request parameter list

Command parameters are unused and ignored by the car

Response is a sequence of individual messages with each message containing the following parameters

bull parameter number

bull maximum number of parameters

bull parameter value

Registered parameters are

bull 0 Registered telephone number

bull 1 Registration Password

bull 2 Miles Kilometer flag

bull 3 Notification method list

bull 4 Server IP

bull 5 GPRS APN

bull 6 GPRS User

382 Chapter 37 OVMS Protocol v2

Open Vehicles

bull 7 GPRS Password

bull 8 Vehicle ID

bull 9 Network Password

bull 10 Paranoid Password

Note that some parameters (24 through 31) are tied directly to the features system (for permanent features) and arethus not directly maintained by the parameter system or shown by this command

3795 4 - Set parameter

Command parameters are

bull parameter number to set

bull value to set

Response parameters are unused and will merely indicate the success or not of the result

3796 5 - Reboot

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result Shortly after sending theresponse the module will reboot

3797 6 - Charge Alert

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result Shortly after sending theresponse the module will issue a charge alert

3798 7 - Execute SMS command

Command parameter is

bull SMS command with parameters

Response is the output of the SMS command that would otherwise have been sent as the reply SMS with LF charactersconverted to CR

The caller id is set to the registered phone number Return code 1 is used for all errors ie authorization failurecommand failure and unknownunhandled commands

Note SMS commands with multiple replies are not yet supported only the last reply will be returned

3799 10 - Set Charge Mode

Command parameters are

bull mode (0=standard 1=storage3=range4=performance)

Response parameters are unused and will merely indicate the success or not of the result

379 Commands 383

Open Vehicles

37910 11 - Start Charge

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

37911 12 - Stop Charge

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

37912 15 - Set Charge Current

Command parameters are

bull current (specified in Amps)

Response parameters are unused and will merely indicate the success or not of the result

37913 16 - Set Charge Mode and Current

Command parameters are

bull mode (0=standard 1=storage3=range4=performance)

bull current (specified in Amps)

Response parameters are unused and will merely indicate the success or not of the result

37914 17 - Set Charge Timer Mode and Start Time

Command parameters are

bull timermode (0=plugin 1=timer)

bull start time (0x059F for midnight GMT 0x003B for 1am GMT etc)

Response parameters are unused and will merely indicate the success or not of the result

37915 18 - Wakeup car

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

37916 19 - Wakeup temperature subsystem

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

384 Chapter 37 OVMS Protocol v2

Open Vehicles

37917 20 - Lock Car

Command parameters are

bull pin (the car pin to use for locking)

Response parameters are unused and will merely indicate the success or not of the result

NB unlocklock may not affect the immobilizer+alarm (when fitted)

37918 21 - Activate Valet Mode

Command parameters are

bull pin (the car pin to activate valet mode)

Response parameters are unused and will merely indicate the success or not of the result

37919 22 - Unlock Car

Command parameters are

bull pin (the car pin to use for unlocking)

Response parameters are unused and will merely indicate the success or not of the result

NB unlocklock does not affect the immobilizer+alarm (when fitted)

37920 23 - Deactivate Value Mode

Command parameters are

bull pin (the car pin to use for deactivating value mode)

Response parameters are unused and will merely indicate the success or not of the result

37921 24 - Home Link

Command parameters are

bull button (home link button 0 1 or 2)

Response parameters are unused and will merely indicate the success or not of the result

37922 25 - Cooldown

Command parameters are unused and ignored by the car

Response parameters are unused and will merely indicate the success or not of the result

379 Commands 385

Open Vehicles

37923 30 - Request GPRS utilization data

Command parameters are unused and ignored by the car

Response is a sequence of individual messages with each message containing the following parameters

bull record number

bull maximum number of records

bull date

bull car received bytes

bull car transmitted bytes

bull apps received bytes

bull apps transmitted bytes

Note that this request is handled by the server not the car so must not be sent in paranoid mode The response (fromthe server) will also not be sent in paranoid mode

NB Dates (and GPRS utilization data) are in UTC

37924 31 - Request historical data summary

Command parameters are

bull since (optional timestamp condition)

Response is a sequence of individual messages with each message containing the following parameters

bull type number

bull maximum number of types

bull type value

bull number of unique records (per type)

bull total number of records (per type)

bull storage usage (in bytes per type)

bull oldest data timestamp (per type)

bull newest data timestamp (per type)

NB Timestamps are in UTC

37925 32 - Request historical data records

Command parameters are

bull type (the record type to retrieve)

bull since (optional timestamp condition)

Response is a sequence of individual messages with each message containing the following parameters

bull response record number

bull maximum number of response records

bull data record type

386 Chapter 37 OVMS Protocol v2

Open Vehicles

bull data record timestamp

bull data record number

bull data record value

37926 40 - Send SMS

Command parameters are

bull number (telephone number to send sms to)

bull message (sms message to be sent)

Response parameters are unused and will merely indicate the success or not of the submission (not delivery) of theSMS

37927 41 - Send MMIUSSD Codes

Command parameters are

bull USSD_CODE (the ussd code to send)

Response parameters are unused and will merely indicate the success or not of the submission (not delivery) of therequest

37928 49 - Send raw AT Command

Command parameters are

bull at (the AT command to send - including the AT prefix)

Response parameters are unused and will merely indicate the success or not of the submission (not delivery) of therequest

379 Commands 387

Open Vehicles

388 Chapter 37 OVMS Protocol v2

CHAPTER 38

OVMS HTTP API

381 Welcome

For some time now Irsquove wanted to offer an HTTP API for OVMS The existing carlt-gtserver and serverlt-gtapp protocolis cool but requires going through some hoops (perl whatever) to handle the encryption and protocol level stuff AnHTTP API would make this much easier to externally script and would be great for pulling down logs and other suchthings

This document describes this HTTP API

Mark February 2013

382 Format

The API is a RESTfull service running at

bull httpapiopenvehiclescom6868api

bull httpsapiopenvehiclescom6869api

Other OVMS servers should provide this API on the same ports but for the rest of this manual we will simply refer toapiopenvehiclescom as the server being used

The return data is a json formatted array of hashes Each record is one for one vehicle and shows you the vehicle idas well as counts for the number of apps currently connected to that vehicle and whether the vehicle is connected tothe net (server) or not

From the server point of view we can treat an api session just like an app session From the vehicle point of view therewill be no difference - once an API connects to a vehicle the server will send a ldquoZ 1rdquo message to tell the module it hasa connection If the session times out or is logged out the server will inform the modules in the vehicles

389

Open Vehicles

3821 Example

For example once authenticated you can request a list of vehicles on your account

$ curl -v -X GET -b cookiejar httpapiopenvehiclescom6868apivehicles

About to connect() to apiopenvehiclescom port 6868 (0)

Trying apiopenvehiclescom

connected

Connected to tmcopenvehiclescom (641117040) port 6868 (0)gt GET apivehicles HTTP11User-Agent curl7240 (x86_64-apple-darwin120) libcurl7240OpenSSL098r zlib125Host apiopenvehiclescom6868Accept Cookie ovmsapisession=9ed66d0e-5768-414e-b06d-476f13be40ff

HTTP 10 assume close after bodylt HTTP10 200 Logout oklt Connection closelt Content-Length 280lt Cache-Control max-age=0lt Content-Type applicationjsonlt Date Fri 22 Feb 2013 124441 GMTlt Expires Fri 22 Feb 2013 124441 GMTlt[

idDEMOv_apps_connected0v_net_connected1idMARKSCARv_apps_connected1v_net_connected1idQCCARv_apps_connected0v_net_connected0idRALLYCARv_apps_connected0v_net_connected0idTESTCARv_apps_connected0v_net_connected0

]

(note that the above is re-formatted slightly to make it clearer to read)

383 Authentication

3831 Alternatives

Each API call must be authenticated and there are currently three options for this

Username+Passsword authentication Specify parameters lsquousernamersquo and lsquopasswordrsquo in the URL and they will bevalidated against registered users on the server Username+ApiToken authentication Specify parameter lsquousernamersquoas the registered user and lsquopasswordrsquo as a registered API token in the URL and they will be validated againstregistered API tokens for that user on the server Cookie authentication A cookie may be obtained (by either of theabove two authentication methods) and then used for subsequent API calls

3832 Cookie Based Authentication

Cookie based authentication avoids the requirement to authenticate each time It is also a requirement for sessionbased API calls This is done with a http ldquoGET apicookierdquo passing parameters lsquousernamersquo and lsquopasswordrsquo as yourwwwopenvehiclescom username and password (or API token) respectively

390 Chapter 38 OVMS HTTP API

Open Vehicles

$ curl -v -X GET -c cookiejarhttpapiopenvehiclescom6868apicookieusername=USERNAMEamppassword=PASSWORD

About to connect() to tmcopenvehiclescom port 6868 (0)

Trying 641117040

connected

Connected to tmcopenvehiclescom (641117040) port 6868 (0)GET apicookieusername=USERNAMEamppassword=PASSWORD HTTP11User-Agent curl7240 (x86_64-apple-darwin120) libcurl7240OpenSSL098r zlib125Host tmcopenvehiclescom6868Accept

HTTP 10 assume close after bodylt HTTP10 200 Authentication oklt Connection closelt Content-Length 9lt Cache-Control max-age=0lt Content-Type textplain

Added cookie ovmsapisession=9ed66d0e-5768-414e-b06d-476f13be40ff for domain tmcrarr˓openvehiclescom path api expire 0lt Set-Cookie ovmsapisession=9ed66d0e-5768-414e-b06d-476f13be40fflt Date Fri 22 Feb 2013 124356 GMTlt Expires Fri 22 Feb 2013 124356 GMTltLogin ok

Once logged in all subsequent requests should pass the cookie (ovmsapisession) The session will expire after 3minutes of no use or you can specifically terminate logout the session by calling ldquoDELETE apicookierdquo

The cookie can be destroyed (and session logged out) using the DELETE method (passing the original cookie)

$ curl -v -X DELETE -b cookiejarhttpapiopenvehiclescom6868apicookie

3833 API Token Maintenance

An API token can be created with a POST to the apitoken API endpoint

$ curl -v -X POST -F application=ltappgt -F purpose=ltpurposegt -F permit=ltpermitgthttpapiopenvehiclescom6868apitoken

Note that the lsquopurposersquo and lsquoapplicationrsquo fields are comments attached to the token and are intended to identify theapplication that createduses the token and the purpose that token is used for

The lsquopermitrsquo field defines the list of rights granted to the user of this token

Any of the three authentication mechanisms can be used for this so long as the permissions include either lsquoto-kenadminrsquo or lsquoadminrsquo rights

An API token can be deleted with a DELETE to the apitokenltTOKENgt API endpoint

$ curl -v -X DELETE httpapiopenvehiclescom6868apitokenltTOKENgt

383 Authentication 391

Open Vehicles

384 Requests

3841 GET apicookie

Login and return a session cookie

3842 DELETE apicookie

Delete the session cookie and logout

All vehicles still connected (via apivehicle) will be disconnected automatically

3843 GET apitoken

Return a list of registered API tokens

3844 POST apitoken

Create an API token

3845 DELETE apitokenltTOKENgt

Delete the specified API token

3846 GET apivehicles

Return a list of registered vehicles

bull id Vehicle ID

bull v_net_connected Number of vehicles currently connected

bull v_apps_connected Number of apps currently connected

bull v_btcs_connected Number of batch clients currently connected

3847 GET apivehicleltVEHICLEIDgt

Connect to the vehicle and return vehicle information

bull m_msgage_s age (seconds) of last status (S) message received if available

bull m_msgtime_s time stamp (UTC) of last status (S) message received if available

bull v_apps_connected number of apps currently connected (including the API connection)

bull v_btcs_connected number of batch clients currently connected

bull v_first_peer 01 1 = the API connection is the first peer connecting to the car

bull v_net_connected 01 1 = the car is currently connected to the server

392 Chapter 38 OVMS HTTP API

Open Vehicles

While no application is connected to the vehicle the module will send status updates using the configured ldquoidlerdquointerval to reduce data volume and energy consumption

Connecting to the car tells the module (if connected) to send status updates in the normally shorter ldquoconnectedrdquointervals (as configured) If yoursquore the first peer and the car is online the module will send a full status update withinthe next second after receiving the new peer count Depending on the connection speed you should give the car modulesome seconds to transmit the first update before proceeding to other status queries

You can also check m_msgage_s and m_msgtime_s to see if the status record is up to date (yet) These fields arealso included in the other status responses eg apichargeltVEHICLEIDgt

3848 DELETE apivehicleltVEHICLEIDgt

Disconnect from the vehicle

This is optional on session logout or expiry all vehicles will be disconnected automatically

3849 GET apiprotocolltVEHICLEIDgt

Return raw protocol records (no vehicle connection)

bull m_msgtime Datetime message received

bull m_paranoid Paranoid mode flag

bull m_ptoken Paranoid mode token

bull m_code Message code

bull m_msg Message body

38410 GET apistatusltVEHICLEIDgt

Return vehicle status

bull soc

bull units

bull idealrange

bull idealrange_max

bull estimatedrange

bull mode

bull chargestate

bull cac100

bull soh

bull cooldown_active

bull fl_dooropen

bull fr_dooropen

bull cp_dooropen

bull pilotpresent

384 Requests 393

Open Vehicles

bull charging

bull caron

bull carlocked

bull valetmode

bull bt_open

bull tr_open

bull temperature_pem

bull temperature_motor

bull temperature_battery

bull temperature_charger

bull temperature_cabin

bull tripmeter

bull odometer

bull speed

bull parkingtimer

bull temperature_ambient

bull carawake

bull staletemps

bull staleambient

bull charging_12v

bull vehicle12v

bull vehicle12v_ref

bull vehicle12v_current

bull alarmsounding

bull m_msgage_s age (seconds) of last status (S) message received if available

bull m_msgtime_s time stamp (UTC) of last status (S) message received if available

bull m_msgage_d age (seconds) of last doorsenv (D) message received if available

bull m_msgtime_d time stamp (UTC) of last doorsenv (D) message received if available

38411 GET apitpmsltVEHICLEIDgt

Return tpms status

bull fr_pressure

bull fr_temperature

bull rr_pressure

bull rr_temperature

bull fl_pressure

394 Chapter 38 OVMS HTTP API

Open Vehicles

bull fl_temperature

bull rl_pressure

bull rl_temperature

bull staletpms

bull m_msgage_w age (seconds) of last TPMS (W) message received if available

bull m_msgtime_w time stamp (UTC) of last TPMS (W) message received if available

38412 GET apilocationltVEHICLEIDgt

Return vehicle location

bull latitude

bull longitude

bull direction

bull altitude

bull gpslock

bull stalegps

bull speed

bull tripmeter

bull drivemode

bull power

bull energyused

bull energyrecd

bull m_msgage_l age (seconds) of last location (L) message received if available

bull m_msgtime_l time stamp (UTC) of last location (L) message received if available

38413 GET apichargeltVEHICLEIDgt

Return vehicle charge status

bull linevoltage

bull battvoltage

bull chargecurrent

bull chargepower

bull chargetype

bull chargestate

bull soc

bull units

bull idealrange

bull estimatedrange

384 Requests 395

Open Vehicles

bull mode

bull chargelimit

bull chargeduration

bull chargeb4

bull chargekwh

bull chargesubstate

bull chargetimermode

bull chargestarttime

bull chargetimerstale

bull cac100

bull soh

bull charge_etr_full

bull charge_etr_limit

bull charge_limit_range

bull charge_limit_soc

bull cooldown_active

bull cooldown_tbattery

bull cooldown_timelimit

bull charge_estimate

bull charge_etr_range

bull charge_etr_soc

bull idealrange_max

bull cp_dooropen

bull pilotpresent

bull charging

bull caron

bull temperature_pem

bull temperature_motor

bull temperature_battery

bull temperature_charger

bull temperature_ambient

bull temperature_cabin

bull carawake

bull staletemps

bull staleambient

bull charging_12v

396 Chapter 38 OVMS HTTP API

Open Vehicles

bull vehicle12v

bull vehicle12v_ref

bull vehicle12v_current

bull m_msgage_s age (seconds) of last status (S) message received if available

bull m_msgtime_s time stamp (UTC) of last status (S) message received if available

bull m_msgage_d age (seconds) of last doorsenv (D) message received if available

bull m_msgtime_d time stamp (UTC) of last doorsenv (D) message received if available

38414 GET apihistoricalltVEHICLEIDgt

Request historical data summary (as array of)

bull h_recordtype

bull distinctrecs

bull totalrecs

bull totalsize

bull first

bull last

38415 GET apihistoricalltVEHICLEIDgtltDATATYPEgt

Request historical data records

bull h_timestamp

bull h_recordnumber

bull h_data

38416 Not Yet Implemented

bull PUT apichargeltVEHICLEIDgt Set vehicle charge status

bull DELETE apichargeltVEHICLEIDgt Abort a vehicle charge

bull GET apilockltVEHICLEIDgt Return vehicle lock status

bull PUT apilockltVEHICLEIDgt Lock a vehicle

bull DELETE apilockltVEHICLEIDgt Unlock a vehicle

bull GET apivaletltVEHICLEIDgt Return valet status

bull PUT apivaletltVEHICLEIDgt Enable valet mode

bull DELETE apivaletltVEHICLEIDgt Disable valet mode

bull GET apifeaturesltVEHICLEIDgt Return vehicle features

bull PUT apifeatureltVEHICLEIDgt Set a vehicle feature

bull GET apiparametersltVEHICLEIDgt Return vehicle parameters

384 Requests 397

Open Vehicles

bull PUT apiparameterltVEHICLEIDgt Set a vehicle parameter

bull PUT apiresetltVEHICLEIDgt Reset the module in a particular vehicle

bull PUT apihomelinkltVEHICLEIDgt Activate home link

398 Chapter 38 OVMS HTTP API

Index

AApp 367

CCar 367

SServer 367

399

  • Open-Vehicle-Monitoring-System-3 (OVMS3)
  • User Guide
  • Plugins
  • BMW i3 i3s
  • DBC Based Vehicles
  • DEMO Vehicle
  • Fiat 500e
  • Hyundai Ioniq vFL
  • Jaguar IPace
  • Kia e-Niro
  • Kia Soul EV
  • Maxus eDeliver3
  • Mercedes-Benz B250E W242
  • MG EV
  • Mitsubishi Trio
  • Nissan Leafe-NV200
  • OBDII Vehicles
  • Renault Twizy
  • Renault Zoe
  • Smart ED Gen3
  • Smart EDEQ Gen4 (453)
  • Tesla Model 3
  • Tesla Model S
  • Tesla Roadster
  • Toyota RAV4 EV
  • Tracking Vehicles
  • VW e-Up
  • VW e-Up via OBD2
  • VW e-Up via Comfort CAN (T26A)
  • Command Line Interpreter
  • CAN Bus Data Logging
  • CRTD CAN Log Format
  • Web Framework amp Plugins
  • Scripting
  • CANopen
  • OVMS Server
  • OVMS Protocol v2
  • OVMS HTTP API
  • Index
Page 5: Open Vehicles - Home | Read the Docs
Page 6: Open Vehicles - Home | Read the Docs
Page 7: Open Vehicles - Home | Read the Docs
Page 8: Open Vehicles - Home | Read the Docs
Page 9: Open Vehicles - Home | Read the Docs
Page 10: Open Vehicles - Home | Read the Docs
Page 11: Open Vehicles - Home | Read the Docs
Page 12: Open Vehicles - Home | Read the Docs
Page 13: Open Vehicles - Home | Read the Docs
Page 14: Open Vehicles - Home | Read the Docs
Page 15: Open Vehicles - Home | Read the Docs
Page 16: Open Vehicles - Home | Read the Docs
Page 17: Open Vehicles - Home | Read the Docs
Page 18: Open Vehicles - Home | Read the Docs
Page 19: Open Vehicles - Home | Read the Docs
Page 20: Open Vehicles - Home | Read the Docs
Page 21: Open Vehicles - Home | Read the Docs
Page 22: Open Vehicles - Home | Read the Docs
Page 23: Open Vehicles - Home | Read the Docs
Page 24: Open Vehicles - Home | Read the Docs
Page 25: Open Vehicles - Home | Read the Docs
Page 26: Open Vehicles - Home | Read the Docs
Page 27: Open Vehicles - Home | Read the Docs
Page 28: Open Vehicles - Home | Read the Docs
Page 29: Open Vehicles - Home | Read the Docs
Page 30: Open Vehicles - Home | Read the Docs
Page 31: Open Vehicles - Home | Read the Docs
Page 32: Open Vehicles - Home | Read the Docs
Page 33: Open Vehicles - Home | Read the Docs
Page 34: Open Vehicles - Home | Read the Docs
Page 35: Open Vehicles - Home | Read the Docs
Page 36: Open Vehicles - Home | Read the Docs
Page 37: Open Vehicles - Home | Read the Docs
Page 38: Open Vehicles - Home | Read the Docs
Page 39: Open Vehicles - Home | Read the Docs
Page 40: Open Vehicles - Home | Read the Docs
Page 41: Open Vehicles - Home | Read the Docs
Page 42: Open Vehicles - Home | Read the Docs
Page 43: Open Vehicles - Home | Read the Docs
Page 44: Open Vehicles - Home | Read the Docs
Page 45: Open Vehicles - Home | Read the Docs
Page 46: Open Vehicles - Home | Read the Docs
Page 47: Open Vehicles - Home | Read the Docs
Page 48: Open Vehicles - Home | Read the Docs
Page 49: Open Vehicles - Home | Read the Docs
Page 50: Open Vehicles - Home | Read the Docs
Page 51: Open Vehicles - Home | Read the Docs
Page 52: Open Vehicles - Home | Read the Docs
Page 53: Open Vehicles - Home | Read the Docs
Page 54: Open Vehicles - Home | Read the Docs
Page 55: Open Vehicles - Home | Read the Docs
Page 56: Open Vehicles - Home | Read the Docs
Page 57: Open Vehicles - Home | Read the Docs
Page 58: Open Vehicles - Home | Read the Docs
Page 59: Open Vehicles - Home | Read the Docs
Page 60: Open Vehicles - Home | Read the Docs
Page 61: Open Vehicles - Home | Read the Docs
Page 62: Open Vehicles - Home | Read the Docs
Page 63: Open Vehicles - Home | Read the Docs
Page 64: Open Vehicles - Home | Read the Docs
Page 65: Open Vehicles - Home | Read the Docs
Page 66: Open Vehicles - Home | Read the Docs
Page 67: Open Vehicles - Home | Read the Docs
Page 68: Open Vehicles - Home | Read the Docs
Page 69: Open Vehicles - Home | Read the Docs
Page 70: Open Vehicles - Home | Read the Docs
Page 71: Open Vehicles - Home | Read the Docs
Page 72: Open Vehicles - Home | Read the Docs
Page 73: Open Vehicles - Home | Read the Docs
Page 74: Open Vehicles - Home | Read the Docs
Page 75: Open Vehicles - Home | Read the Docs
Page 76: Open Vehicles - Home | Read the Docs
Page 77: Open Vehicles - Home | Read the Docs
Page 78: Open Vehicles - Home | Read the Docs
Page 79: Open Vehicles - Home | Read the Docs
Page 80: Open Vehicles - Home | Read the Docs
Page 81: Open Vehicles - Home | Read the Docs
Page 82: Open Vehicles - Home | Read the Docs
Page 83: Open Vehicles - Home | Read the Docs
Page 84: Open Vehicles - Home | Read the Docs
Page 85: Open Vehicles - Home | Read the Docs
Page 86: Open Vehicles - Home | Read the Docs
Page 87: Open Vehicles - Home | Read the Docs
Page 88: Open Vehicles - Home | Read the Docs
Page 89: Open Vehicles - Home | Read the Docs
Page 90: Open Vehicles - Home | Read the Docs
Page 91: Open Vehicles - Home | Read the Docs
Page 92: Open Vehicles - Home | Read the Docs
Page 93: Open Vehicles - Home | Read the Docs
Page 94: Open Vehicles - Home | Read the Docs
Page 95: Open Vehicles - Home | Read the Docs
Page 96: Open Vehicles - Home | Read the Docs
Page 97: Open Vehicles - Home | Read the Docs
Page 98: Open Vehicles - Home | Read the Docs
Page 99: Open Vehicles - Home | Read the Docs
Page 100: Open Vehicles - Home | Read the Docs
Page 101: Open Vehicles - Home | Read the Docs
Page 102: Open Vehicles - Home | Read the Docs
Page 103: Open Vehicles - Home | Read the Docs
Page 104: Open Vehicles - Home | Read the Docs
Page 105: Open Vehicles - Home | Read the Docs
Page 106: Open Vehicles - Home | Read the Docs
Page 107: Open Vehicles - Home | Read the Docs
Page 108: Open Vehicles - Home | Read the Docs
Page 109: Open Vehicles - Home | Read the Docs
Page 110: Open Vehicles - Home | Read the Docs
Page 111: Open Vehicles - Home | Read the Docs
Page 112: Open Vehicles - Home | Read the Docs
Page 113: Open Vehicles - Home | Read the Docs
Page 114: Open Vehicles - Home | Read the Docs
Page 115: Open Vehicles - Home | Read the Docs
Page 116: Open Vehicles - Home | Read the Docs
Page 117: Open Vehicles - Home | Read the Docs
Page 118: Open Vehicles - Home | Read the Docs
Page 119: Open Vehicles - Home | Read the Docs
Page 120: Open Vehicles - Home | Read the Docs
Page 121: Open Vehicles - Home | Read the Docs
Page 122: Open Vehicles - Home | Read the Docs
Page 123: Open Vehicles - Home | Read the Docs
Page 124: Open Vehicles - Home | Read the Docs
Page 125: Open Vehicles - Home | Read the Docs
Page 126: Open Vehicles - Home | Read the Docs
Page 127: Open Vehicles - Home | Read the Docs
Page 128: Open Vehicles - Home | Read the Docs
Page 129: Open Vehicles - Home | Read the Docs
Page 130: Open Vehicles - Home | Read the Docs
Page 131: Open Vehicles - Home | Read the Docs
Page 132: Open Vehicles - Home | Read the Docs
Page 133: Open Vehicles - Home | Read the Docs
Page 134: Open Vehicles - Home | Read the Docs
Page 135: Open Vehicles - Home | Read the Docs
Page 136: Open Vehicles - Home | Read the Docs
Page 137: Open Vehicles - Home | Read the Docs
Page 138: Open Vehicles - Home | Read the Docs
Page 139: Open Vehicles - Home | Read the Docs
Page 140: Open Vehicles - Home | Read the Docs
Page 141: Open Vehicles - Home | Read the Docs
Page 142: Open Vehicles - Home | Read the Docs
Page 143: Open Vehicles - Home | Read the Docs
Page 144: Open Vehicles - Home | Read the Docs
Page 145: Open Vehicles - Home | Read the Docs
Page 146: Open Vehicles - Home | Read the Docs
Page 147: Open Vehicles - Home | Read the Docs
Page 148: Open Vehicles - Home | Read the Docs
Page 149: Open Vehicles - Home | Read the Docs
Page 150: Open Vehicles - Home | Read the Docs
Page 151: Open Vehicles - Home | Read the Docs
Page 152: Open Vehicles - Home | Read the Docs
Page 153: Open Vehicles - Home | Read the Docs
Page 154: Open Vehicles - Home | Read the Docs
Page 155: Open Vehicles - Home | Read the Docs
Page 156: Open Vehicles - Home | Read the Docs
Page 157: Open Vehicles - Home | Read the Docs
Page 158: Open Vehicles - Home | Read the Docs
Page 159: Open Vehicles - Home | Read the Docs
Page 160: Open Vehicles - Home | Read the Docs
Page 161: Open Vehicles - Home | Read the Docs
Page 162: Open Vehicles - Home | Read the Docs
Page 163: Open Vehicles - Home | Read the Docs
Page 164: Open Vehicles - Home | Read the Docs
Page 165: Open Vehicles - Home | Read the Docs
Page 166: Open Vehicles - Home | Read the Docs
Page 167: Open Vehicles - Home | Read the Docs
Page 168: Open Vehicles - Home | Read the Docs
Page 169: Open Vehicles - Home | Read the Docs
Page 170: Open Vehicles - Home | Read the Docs
Page 171: Open Vehicles - Home | Read the Docs
Page 172: Open Vehicles - Home | Read the Docs
Page 173: Open Vehicles - Home | Read the Docs
Page 174: Open Vehicles - Home | Read the Docs
Page 175: Open Vehicles - Home | Read the Docs
Page 176: Open Vehicles - Home | Read the Docs
Page 177: Open Vehicles - Home | Read the Docs
Page 178: Open Vehicles - Home | Read the Docs
Page 179: Open Vehicles - Home | Read the Docs
Page 180: Open Vehicles - Home | Read the Docs
Page 181: Open Vehicles - Home | Read the Docs
Page 182: Open Vehicles - Home | Read the Docs
Page 183: Open Vehicles - Home | Read the Docs
Page 184: Open Vehicles - Home | Read the Docs
Page 185: Open Vehicles - Home | Read the Docs
Page 186: Open Vehicles - Home | Read the Docs
Page 187: Open Vehicles - Home | Read the Docs
Page 188: Open Vehicles - Home | Read the Docs
Page 189: Open Vehicles - Home | Read the Docs
Page 190: Open Vehicles - Home | Read the Docs
Page 191: Open Vehicles - Home | Read the Docs
Page 192: Open Vehicles - Home | Read the Docs
Page 193: Open Vehicles - Home | Read the Docs
Page 194: Open Vehicles - Home | Read the Docs
Page 195: Open Vehicles - Home | Read the Docs
Page 196: Open Vehicles - Home | Read the Docs
Page 197: Open Vehicles - Home | Read the Docs
Page 198: Open Vehicles - Home | Read the Docs
Page 199: Open Vehicles - Home | Read the Docs
Page 200: Open Vehicles - Home | Read the Docs
Page 201: Open Vehicles - Home | Read the Docs
Page 202: Open Vehicles - Home | Read the Docs
Page 203: Open Vehicles - Home | Read the Docs
Page 204: Open Vehicles - Home | Read the Docs
Page 205: Open Vehicles - Home | Read the Docs
Page 206: Open Vehicles - Home | Read the Docs
Page 207: Open Vehicles - Home | Read the Docs
Page 208: Open Vehicles - Home | Read the Docs
Page 209: Open Vehicles - Home | Read the Docs
Page 210: Open Vehicles - Home | Read the Docs
Page 211: Open Vehicles - Home | Read the Docs
Page 212: Open Vehicles - Home | Read the Docs
Page 213: Open Vehicles - Home | Read the Docs
Page 214: Open Vehicles - Home | Read the Docs
Page 215: Open Vehicles - Home | Read the Docs
Page 216: Open Vehicles - Home | Read the Docs
Page 217: Open Vehicles - Home | Read the Docs
Page 218: Open Vehicles - Home | Read the Docs
Page 219: Open Vehicles - Home | Read the Docs
Page 220: Open Vehicles - Home | Read the Docs
Page 221: Open Vehicles - Home | Read the Docs
Page 222: Open Vehicles - Home | Read the Docs
Page 223: Open Vehicles - Home | Read the Docs
Page 224: Open Vehicles - Home | Read the Docs
Page 225: Open Vehicles - Home | Read the Docs
Page 226: Open Vehicles - Home | Read the Docs
Page 227: Open Vehicles - Home | Read the Docs
Page 228: Open Vehicles - Home | Read the Docs
Page 229: Open Vehicles - Home | Read the Docs
Page 230: Open Vehicles - Home | Read the Docs
Page 231: Open Vehicles - Home | Read the Docs
Page 232: Open Vehicles - Home | Read the Docs
Page 233: Open Vehicles - Home | Read the Docs
Page 234: Open Vehicles - Home | Read the Docs
Page 235: Open Vehicles - Home | Read the Docs
Page 236: Open Vehicles - Home | Read the Docs
Page 237: Open Vehicles - Home | Read the Docs
Page 238: Open Vehicles - Home | Read the Docs
Page 239: Open Vehicles - Home | Read the Docs
Page 240: Open Vehicles - Home | Read the Docs
Page 241: Open Vehicles - Home | Read the Docs
Page 242: Open Vehicles - Home | Read the Docs
Page 243: Open Vehicles - Home | Read the Docs
Page 244: Open Vehicles - Home | Read the Docs
Page 245: Open Vehicles - Home | Read the Docs
Page 246: Open Vehicles - Home | Read the Docs
Page 247: Open Vehicles - Home | Read the Docs
Page 248: Open Vehicles - Home | Read the Docs
Page 249: Open Vehicles - Home | Read the Docs
Page 250: Open Vehicles - Home | Read the Docs
Page 251: Open Vehicles - Home | Read the Docs
Page 252: Open Vehicles - Home | Read the Docs
Page 253: Open Vehicles - Home | Read the Docs
Page 254: Open Vehicles - Home | Read the Docs
Page 255: Open Vehicles - Home | Read the Docs
Page 256: Open Vehicles - Home | Read the Docs
Page 257: Open Vehicles - Home | Read the Docs
Page 258: Open Vehicles - Home | Read the Docs
Page 259: Open Vehicles - Home | Read the Docs
Page 260: Open Vehicles - Home | Read the Docs
Page 261: Open Vehicles - Home | Read the Docs
Page 262: Open Vehicles - Home | Read the Docs
Page 263: Open Vehicles - Home | Read the Docs
Page 264: Open Vehicles - Home | Read the Docs
Page 265: Open Vehicles - Home | Read the Docs
Page 266: Open Vehicles - Home | Read the Docs
Page 267: Open Vehicles - Home | Read the Docs
Page 268: Open Vehicles - Home | Read the Docs
Page 269: Open Vehicles - Home | Read the Docs
Page 270: Open Vehicles - Home | Read the Docs
Page 271: Open Vehicles - Home | Read the Docs
Page 272: Open Vehicles - Home | Read the Docs
Page 273: Open Vehicles - Home | Read the Docs
Page 274: Open Vehicles - Home | Read the Docs
Page 275: Open Vehicles - Home | Read the Docs
Page 276: Open Vehicles - Home | Read the Docs
Page 277: Open Vehicles - Home | Read the Docs
Page 278: Open Vehicles - Home | Read the Docs
Page 279: Open Vehicles - Home | Read the Docs
Page 280: Open Vehicles - Home | Read the Docs
Page 281: Open Vehicles - Home | Read the Docs
Page 282: Open Vehicles - Home | Read the Docs
Page 283: Open Vehicles - Home | Read the Docs
Page 284: Open Vehicles - Home | Read the Docs
Page 285: Open Vehicles - Home | Read the Docs
Page 286: Open Vehicles - Home | Read the Docs
Page 287: Open Vehicles - Home | Read the Docs
Page 288: Open Vehicles - Home | Read the Docs
Page 289: Open Vehicles - Home | Read the Docs
Page 290: Open Vehicles - Home | Read the Docs
Page 291: Open Vehicles - Home | Read the Docs
Page 292: Open Vehicles - Home | Read the Docs
Page 293: Open Vehicles - Home | Read the Docs
Page 294: Open Vehicles - Home | Read the Docs
Page 295: Open Vehicles - Home | Read the Docs
Page 296: Open Vehicles - Home | Read the Docs
Page 297: Open Vehicles - Home | Read the Docs
Page 298: Open Vehicles - Home | Read the Docs
Page 299: Open Vehicles - Home | Read the Docs
Page 300: Open Vehicles - Home | Read the Docs
Page 301: Open Vehicles - Home | Read the Docs
Page 302: Open Vehicles - Home | Read the Docs
Page 303: Open Vehicles - Home | Read the Docs
Page 304: Open Vehicles - Home | Read the Docs
Page 305: Open Vehicles - Home | Read the Docs
Page 306: Open Vehicles - Home | Read the Docs
Page 307: Open Vehicles - Home | Read the Docs
Page 308: Open Vehicles - Home | Read the Docs
Page 309: Open Vehicles - Home | Read the Docs
Page 310: Open Vehicles - Home | Read the Docs
Page 311: Open Vehicles - Home | Read the Docs
Page 312: Open Vehicles - Home | Read the Docs
Page 313: Open Vehicles - Home | Read the Docs
Page 314: Open Vehicles - Home | Read the Docs
Page 315: Open Vehicles - Home | Read the Docs
Page 316: Open Vehicles - Home | Read the Docs
Page 317: Open Vehicles - Home | Read the Docs
Page 318: Open Vehicles - Home | Read the Docs
Page 319: Open Vehicles - Home | Read the Docs
Page 320: Open Vehicles - Home | Read the Docs
Page 321: Open Vehicles - Home | Read the Docs
Page 322: Open Vehicles - Home | Read the Docs
Page 323: Open Vehicles - Home | Read the Docs
Page 324: Open Vehicles - Home | Read the Docs
Page 325: Open Vehicles - Home | Read the Docs
Page 326: Open Vehicles - Home | Read the Docs
Page 327: Open Vehicles - Home | Read the Docs
Page 328: Open Vehicles - Home | Read the Docs
Page 329: Open Vehicles - Home | Read the Docs
Page 330: Open Vehicles - Home | Read the Docs
Page 331: Open Vehicles - Home | Read the Docs
Page 332: Open Vehicles - Home | Read the Docs
Page 333: Open Vehicles - Home | Read the Docs
Page 334: Open Vehicles - Home | Read the Docs
Page 335: Open Vehicles - Home | Read the Docs
Page 336: Open Vehicles - Home | Read the Docs
Page 337: Open Vehicles - Home | Read the Docs
Page 338: Open Vehicles - Home | Read the Docs
Page 339: Open Vehicles - Home | Read the Docs
Page 340: Open Vehicles - Home | Read the Docs
Page 341: Open Vehicles - Home | Read the Docs
Page 342: Open Vehicles - Home | Read the Docs
Page 343: Open Vehicles - Home | Read the Docs
Page 344: Open Vehicles - Home | Read the Docs
Page 345: Open Vehicles - Home | Read the Docs
Page 346: Open Vehicles - Home | Read the Docs
Page 347: Open Vehicles - Home | Read the Docs
Page 348: Open Vehicles - Home | Read the Docs
Page 349: Open Vehicles - Home | Read the Docs
Page 350: Open Vehicles - Home | Read the Docs
Page 351: Open Vehicles - Home | Read the Docs
Page 352: Open Vehicles - Home | Read the Docs
Page 353: Open Vehicles - Home | Read the Docs
Page 354: Open Vehicles - Home | Read the Docs
Page 355: Open Vehicles - Home | Read the Docs
Page 356: Open Vehicles - Home | Read the Docs
Page 357: Open Vehicles - Home | Read the Docs
Page 358: Open Vehicles - Home | Read the Docs
Page 359: Open Vehicles - Home | Read the Docs
Page 360: Open Vehicles - Home | Read the Docs
Page 361: Open Vehicles - Home | Read the Docs
Page 362: Open Vehicles - Home | Read the Docs
Page 363: Open Vehicles - Home | Read the Docs
Page 364: Open Vehicles - Home | Read the Docs
Page 365: Open Vehicles - Home | Read the Docs
Page 366: Open Vehicles - Home | Read the Docs
Page 367: Open Vehicles - Home | Read the Docs
Page 368: Open Vehicles - Home | Read the Docs
Page 369: Open Vehicles - Home | Read the Docs
Page 370: Open Vehicles - Home | Read the Docs
Page 371: Open Vehicles - Home | Read the Docs
Page 372: Open Vehicles - Home | Read the Docs
Page 373: Open Vehicles - Home | Read the Docs
Page 374: Open Vehicles - Home | Read the Docs
Page 375: Open Vehicles - Home | Read the Docs
Page 376: Open Vehicles - Home | Read the Docs
Page 377: Open Vehicles - Home | Read the Docs
Page 378: Open Vehicles - Home | Read the Docs
Page 379: Open Vehicles - Home | Read the Docs
Page 380: Open Vehicles - Home | Read the Docs
Page 381: Open Vehicles - Home | Read the Docs
Page 382: Open Vehicles - Home | Read the Docs
Page 383: Open Vehicles - Home | Read the Docs
Page 384: Open Vehicles - Home | Read the Docs
Page 385: Open Vehicles - Home | Read the Docs
Page 386: Open Vehicles - Home | Read the Docs
Page 387: Open Vehicles - Home | Read the Docs
Page 388: Open Vehicles - Home | Read the Docs
Page 389: Open Vehicles - Home | Read the Docs
Page 390: Open Vehicles - Home | Read the Docs
Page 391: Open Vehicles - Home | Read the Docs
Page 392: Open Vehicles - Home | Read the Docs
Page 393: Open Vehicles - Home | Read the Docs
Page 394: Open Vehicles - Home | Read the Docs
Page 395: Open Vehicles - Home | Read the Docs
Page 396: Open Vehicles - Home | Read the Docs
Page 397: Open Vehicles - Home | Read the Docs
Page 398: Open Vehicles - Home | Read the Docs
Page 399: Open Vehicles - Home | Read the Docs
Page 400: Open Vehicles - Home | Read the Docs
Page 401: Open Vehicles - Home | Read the Docs
Page 402: Open Vehicles - Home | Read the Docs