Posted on 5 Comments

How To Article

This tutorial is about reading out the current state of charge (percentage value) of the Hyundai IONIQ electric and making it available on a small website.

Unfortunately, the Hyundai does not provide a possibility in Europe . This rather unpleasant condition I took as an opportunity to start this small project. More beautiful, of course, would be a ready-made solution from the manufacturer. Since this is not given, there is now this tinkering, but so far in my IONIQ its purpose fulfilled and always informed me about the battery level.

advance

I am a web developer and since 2014 enthusiastic about the topic of electromobility. Before I was interested in e-mobility, I had nothing to do with cars 🙂 I’m not a car enthusiast or have any prior knowledge of vehicle diagnosis or previous knowledge in dealing with the OBD2 interface.

This is a basic facility and neglects the subject of security.

Hardware + Costs

Basically, the system works well with other hardware e. g. with other OBD2 Bluetooth dongle or surf sticks. But I have had good experiences with it and therefore list it here.

Raspberry Pi Zero W (Starter Set) This includes housing and a USB adapter. You’ll need that later for the surfstick  26,00 EUR
Netzteil + Kabel für Stromversorgung  9,89 EUR
8GB Micro SD Karte  7,99 EUR
OBD2 Bluetooth Dongle The linked dongle is a bit large and the cover in the vehicle does not fit anymore.  10,99 EUR
Huawei E303 3G Surfstick I recommend this stick or another HUAWEI Surfstick that supports HiLink. That means you setup the stick as described in the manual – on a Windows PC. There is nothing left to do on the Raspberry Pi. Just plug it in.  25,49 EUR
Powerbank For charging, the Raspberry Pi needs to be powered by a power bank. The USB sockets in the vehicle do not work  31,99 EUR

So there are hardware costs of about 110,00 EUR

Please note, you need….

… Previous knowledge in Linux, SSH and webhosting. You also need a provider who will host you a MySQL database and a small PHP script. In addition, a PC / Mac with the ability to access the SD card.

1. Preparation

To save the state of charge you need a table in a database. In the tutorial here I use a MySQL database. The database must be reachable externally.

You can create the following table via the SQL script

CREATE TABLE IF NOT EXISTS `bms` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `soc` int(255) NOT NULL,
 `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1267 ;

Keep the access data for the database ready for the later step.

You need

  • hostname (Servername)
  • username
  • password
  • name of the database

2. Setup of the Raspberry Pi

If you are new to Raspberry Pi, you should get some information about it. For example, here

If you are already familiar with the Raspberry Pi, you can start. We start by writing the OS to the Micro SD card. The SD card is written with an image. This is a preconfigured operating system for the Pi. I have choose “Raspbian Stretch Lite”. You find the download here.

There are many different ways to write the Raspbian image on the SD card.

For Windows: Win32DiskImager
Instruction: https://www.raspberrypi.org/documentation/installation/installing-images/windows.md

For Mac: With the Terminal Application
Instruction: https://www.raspberrypi.org/documentation/installation/installing-images/mac.md

Both ways are sufficiently documented in the internet, which is why I do not go into it here.

2.1. WLAN and SSH configuration

Before you can put the SD card into the Pi and boot it, you should configure the WLAN in advance, so you can perform the further configuration via SSH. For this you create a file “wpa_supplicant.conf” with the following content

# File wpa_supplicant.conf in der Boot-Partition (Raspbian Stretch)
country=DE #omit if US
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
 ssid="<YOUR WLAN NAME (SSID)"
 psk="<YOUR WLAN PASSWORD>"
 key_mgmt=WPA-PSK
}

and copy it to the SD card.

In addition, create an empty file with the name “ssh” and copy it to the SD card as well. As a result, you can access the Pi via SSH.

After starting up, the Raspberry Pi will connect to your Wi-Fi network and you can now connect to the Pi over the network.

2.2. Commissioning of the Raspberry Pi Zero W

Now you can put the SD card into the Raspberry and start it. You should then find the device called “raspberrypi” in your network devices. E. g. over the web interface of the router (Fritz Box)

Or you can directly try to “ping” it – in Windows with the program “cmd” or if you use a Mac or Linux system, by the terminal.

ping raspberrypi

If the Raspberry is reachable in the network, you will also receive the IP address of the device in this way.

2.3. First connection with SSH and package installation

You use PuTTY or the terminal for SSH connections to the Raspberry Pi. The default username is “pi” the password “raspberry”

ssh pi@raspberrypi
pi@raspberrypi's password: raspberry

Now some packages have to be installed, but before that please do the obligatory update and upgrade

sudo apt-get update
sudo apt-get upgrade

sudo apt-get install bluetooth bluez-tools blueman python python-serial python-mysqldb

2.4. Pairing OBD2 Bluetooth Dongle with Raspberry Pi

There are three things to be given in this step.

  1. OBD2 Dongle is plugged into the IONIQ
  2. Raspberry Pi is within reach of the OBD2 dongle (<5m)
    Ideally, you will power the Raspberry Pi directly in the IONIQ. Simply hang on a USB port.
  3. Switch on the vehicle!
  4. Raspberry Pi is connected to the Wi-Fi

I could imagine that for one or the other is problematic because eg the vehicle is parked in the garage and there is no Wi-Fi for the Raspberry Pi. Then I can only recommend the pairing of the OBD2 dongle and the Raspberry Pi in a place where these conditions are given.

If you need to use a different Wi-Fi, then you can download the file in step 1.1. Simply expand by another network block, with additional access data.


network={ 
  ssid="<ANOTHER WLAN NAME (SSID)>" 
  psk="<ANOTHER WLAN PASSWORD>" 
  key_mgmt=WPA-PSK 
}

Now to pair the device:

sudo bluetoothctl

starts the program for setting up the Bluetooth device. Presumably you have to mess this up with the password of the user “pi”. So enter “raspberry” and confirm

agent on
scan on

lists all Bluetooth devices in range. Here should also appear your OBD2 dongle. You will also see the device address (Format: XX: XX: XX: XX: XX: XX). This is important for the next steps!

pair XX:XX:XX:XX:XX:XX

Now you have to enter the device code. Mostly it is “1234”or “0000”. If that worked, you still have to trust the device in general, so this procedure does not have to be repeated permanently

trust XX:XX:XX:XX:XX:XX

Mounting the OBD Dongle as a device

To be able to access the OBD2 dongle, it must still be integrated as a serial device. and this after each restart. To do this, we add the following line to the file /etc/rc.local

sudo rfcomm bind hci0 XX:XX:XX:XX:XX:XX 1

Then you should restart the Raspberry Pi

sudo reboot

2.5. Installing Python Script

As mentioned before, I have not written a line Python so far. Therefore, it may be that the Python professionals go crazy looking at the code. The code certainly offers a lot of optimization potential!


import serial
import MySQLdb
import re
import time
import string
import io

db = MySQLdb.connect(host="<DB HOST>",    # your host, usually localhost
                     user="<DB USER>",         # your username
                     passwd="<DB PASSWORT>",  # your password
                     db="<DB NAME>")        # name of the data base

cur = db.cursor()

ser = serial.Serial("/dev/rfcomm0", timeout=None)
ser.baudrate = 9600
ser.flushInput()
ser.write(b'2105\r\n')
ser.flush()
seq = []
while True:
    reading = ser.read()
    seq.append(reading)
    joineddata = ' '.join(str(v) for v in seq).replace(' ', '')

    err = re.search('ERROR', joineddata)
    if err:
        break
    m = re.search('4([^;]*)5:', joineddata) #'/4([^;]*)\n5', joineddata)
    if m:
        ser.close()
        test = str(m.group(0))
        x = (test[-8:])      
        SoC = (int( x[3:5], 16)/2)
        if SoC > 0 & SoC <= 100:
            print(SoC)
            cur.execute("""INSERT INTO bms (soc) VALUES (%s)""", (SoC,) )
            db.commit()
        break

Enter your database access data and save the code on the Raspberry Pi in the directory /home/pi/ under the name ioniq.py

You can test it for the first time by calling the program

python ioniq.py

After a short program period, you should see a new record in your bms table and there should appear the SoC.

2.6. Execute the Python Skript by Cronjob

In order not to have to execute the program mauell, we set up the call in the crontab.

To do this, enter the following command via SSH

crontab -e

and insert the following line

* * * * * python /home/pi/ioniq.py& PID=$!; sleep 15; kill $PID >/dev/null 2>&1

After saving the crontab the Python script is executes every minute.

2.7. Surfstick

Raspberry Pi Zero ! + Huawei E303 Surfstick

I use the HUAWEI E303 Surfstick. It supports HiLink. Again, I do not go into the details of the setup. Again this differs from Surfstick to Surfstick. I recommend to setup the device as described in the manual of the stick. This should not be done on the Raspberry Pi. Use a Windows PC or Notebook.

When you’re done setting up, you can usually plug the stick into the USB port of the Raspberry Pi, using the USB adapter (included in the starter set)

What you should do: Remove the PIN request of the SIM card during setup. This can be done during the configuration in the web browser.

Oh, I have a lot of good experiences with the SIM card from netzclub.de! 🙂

2.8. Powerbank

While driving, you can easily operate the Raspberry Pi on one of the USB sockets in the vehicle. However, it is usually useless while driving the system to run at all. Normally, the charge level is interesting, if the car is parked  and charging. And in this case, the Raspberry Pi has to be powered by a power bank, because the USB sockets in the IONIQ unfortunately are not supplied with power during the charging process.

I use an existing power bank, which I still have at home. Pay attention to 2 things when buying the powerbank

  1. It should support charging and power supplying at the same time
  2. The charging and discharging sockets should be sufficiently far apart so that both plugs can also be plugged together without any problems.

3. Webinterface

Das Webinterface ist eine kleine Webanwendung, die ich Quick and Dirty in PHP geschrieben habe. Du kannst einfach diese ZIP-Datei herunterladen, entpacken und den Inhalt auf Deinen Webspace hochladen.

Auch hier setze ich etwas Vorkenntnisse voraus und gehe nicht darauf ein. Es sollte klar sein, dass PHP ab Version 5.6 vom Webhoster unterstützt werden muss.

Du musst nun noch die 2. Zeile in der index.php anpassen. Trage hier wieder Deine Datenbankdaten ein

 

The webinterface is a small web application that I wrote Quick and Dirty in PHP. You can just download this zip file, extract it and upload the content to your webspace.

Again, I presuppose some prior knowledge and do not respond. It should be clear that PHP version 5.6 and higher must be supported by the web hoster.

You now have to adjust the 2nd line in index.php. Enter your database credentials here.