Giter Site home page Giter Site logo

leaf-python-mqtt's Introduction

leaf-python-mqtt

Hacked together script to extract data from Nissan Leaf API using pycarwings2 and post to MQTT. Once data is in MQTT it can easily be used to inform home automation and smart charging applications. e.g OpenHAB, Home Assistant, OpenEVSE.

Here is an example of displaying the MQTT data via openHAB Android app:

openhab-leaf-mqtt

Usage

Status

Every XX min as defined in config.ini the following status(s) are updated to MQTT sub topics:

leaf/status/last_updated
leaf/status/battery_percent
leaf/status/charging_status
leaf/status/connected

The raw json output from Nissan API request is posted to MQTT topic:

leaf/status/raw

These scheduled 'status' updates are polled from the Nissan API and not requested from the car. I.e. the last car status is returned. See the 'Control' section below for how to request an update from the car. Requesting the latest status from the API does not effect the car, eg. GSM telematics in the car are not activated.

It's not recommended to poll the Nissan API more fequently then about 10-15min, be a good citizen :-)

Control

By default the following control MQTT topics are used

leaf/control/update

Publishing 1 to the update control sub-topic will request and update from the car.

Caution: this will activate the cars GSM telematic modem. Frequent poilling is not recomended as it could drain the cars 12V aux batttery

leaf/control/climate

Publishing 1 to the climate control sub-topic will turn on the cars climate control. Publishing 0 will turn it off. Currently there does not seem to be anyway to retrieve the status of the climate control from the pycarwings2 lib


Install Requirements

Requires python 2.7.9 & python pip

Install carwings python lib

pip install git+https://github.com/jdhorne/pycarwings2.git

See pycarwings2 repo for more info

Note: as of May 18 the API URL changed for users in the UK see discussion. UK users should use this version of pycarwings with the updated UK API URL:

pip install git+https://github.com/gym22/pycarwings2.git

Install other python libs

pip install schedule datetime paho-mqtt time

pip may require sudo

Install Leaf-python-mqtt

Clone this repo:

$ git clone https://github.com/glynhudson/leaf-python-mqtt

Create config file using default file as a template, edit config to suit requirements. You will need to enter your CarWings / NissanConnect EV username and password.

$ cd leaf-python-mqtt
$ cp default.config.ini config.ini
$ nano config.ini

The default config is setup for Nissan Leaf cars in Europe with region code NE, change the region code to one of the following if you are in a different region:

NNA : USA
NE : Europe
NCI : Canada
NMA : Australia
NML : Japan

Test script by running

$ ./leaf-python-mqtt.py

Run script as system service

Create Systemd service

Create systemd service, assuming repo was cloned to /home/pi folder on a RaspberryPi, adjust paths if needed

$ sudo ln -s /home/pi/leaf-python-mqtt/leaf-python-mqtt.service /etc/systemd/system/leaf-python-mqtt.service

Set permissions:

sudo chmod 644 /etc/systemd/system/leaf-python-mqtt.service

Reload systemd then enable the service at startup:

$ sudo systemctl daemon-reload
$ sudo systemctl enable leaf-python-mqtt.service
$ sudo systemctl start leaf-python-mqtt.service

Check service status and view log snippet with:

sudo systemctl status leaf-python-mqtt.service

To view more lines of logs add nXX where XX is the number of lines e.g. to view 50 lines of logs

sudo systemctl status leaf-python-mqtt.service -n50

Start, stop and restart with:

sudo systemctl start leaf-python-mqtt.service
sudo systemctl stop leaf-python-mqtt.service
sudo systemctl restart leaf-python-mqtt.service

leaf-python-mqtt's People

Contributors

fab33 avatar filcole avatar glynhudson avatar steintore avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

leaf-python-mqtt's Issues

MQTT publishing hangs after a while

Not sure what is happening here, but running on an RPi with Jessie running the base leaf-python-mqtt works fine but after some hours (never measure fully) MQTT publication stops to a remote broker - an emonpi in this case.

The symptoms are that the process continues to log data acquisition from Nissan and publish to MQTT but the broker receives nothing. This is evidenced by local mosquitto_pub/sub working to the same remote broker from the command line and netstat showing a CLOSE_WAIT connection to the broker with one byte in the receive queue.

Not being a python expert but trying to read the paho docs I think there should be some more error checking somewhere and maybe an on_disconnect callback defined. But I am guessing.

Recent API error?

Hi,
We've been using this script quite successfully, but in the last week or two it has stopped working and gives and API error. I see filcole has a more recent pycarwings2, but we can't successfully use it with the examples, have you managed to run leaf-python-mqtt.py recently?
Thanks

Issues receiving values for 2015 leaf

Hi!

First off, great work in buidling a script that integrates with mqtt. Just the kind of home automation i enjoy! Now for the problem.

INFO:root:Startup leaf-python-MQTT: 2018-03-11 13:35:08
INFO:root:Loaded config file /home/username/leaf-python-mqtt/config.ini
INFO:root:updating data from API every 15min
INFO:root:Prepare Session
INFO:root:Login...
INFO:root:Start update time: 2018-03-11 13:35:08
INFO:root:Connected to MQTT host mqttserver with result code 0
INFO:root:Suscribing to leaf control topic: leaf/control
INFO:root:Publishing to leaf status topic: leaf/status
INFO:root:get_latest_battery_status
Traceback (most recent call last):
File "./leaf-python-mqtt.py", line 220, in
get_leaf_status()
File "./leaf-python-mqtt.py", line 161, in get_leaf_status
leaf_info = l.get_latest_battery_status()
File "/usr/local/lib/python2.7/dist-packages/pycarwings2/pycarwings2.py", line 372, in get_latest_battery_status
return CarwingsLatestBatteryStatusResponse(response)
File "/usr/local/lib/python2.7/dist-packages/pycarwings2/responses.py", line 514, in init
bs = recs["BatteryStatus"]
TypeError: list indices must be integers, not str

I have configured everything correctly it seems, as the work on getting values start (it didn't earlier as i did the same error as some others, using the mail adress instead of username for login), but it seems to me the output values we receive is strings and not ints.

Hope you could help shed some light on what might be causing this.

"404 not found" despite using updated pycarwings2

I suspect there may have been another API change recently, there was an update on some third party apps yesterday stating they were updated for the "new Nissan API".

I followed the install instructions and installed fresh today.

Error message here:

INFO:root:Startup leaf-python-MQTT: 2018-12-21 19:52:48
INFO:root:Loaded config file /home/ianr/leaf/leaf-python-mqtt/config.ini
INFO:root:updating data from API every 15min
INFO:root:Prepare Session
INFO:root:Login...
INFO:root:Connected to MQTT host openhab with result code 0
INFO:root:Start update time: 2018-12-21 19:52:48
INFO:root:Suscribing to leaf control topic: leaf/control
DEBUG:pycarwings2.pycarwings2:invoking carwings API: https://gdcportalgw.its-mo.com/api_v180117_NE/gdc/InitialApp.php
INFO:root:Publishing to leaf status topic: leaf/status
DEBUG:pycarwings2.pycarwings2:params: {
   "RegionCode": "NE",
   "custom_sessionid": "",
   "initial_app_strings": "geORNtsZe5I4lRGjG9GZiA",
   "lg": "en-US"
}
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): gdcportalgw.its-mo.com:443
DEBUG:urllib3.connectionpool:https://gdcportalgw.its-mo.com:443 "POST /api_v180117_NE/gdc/InitialApp.php HTTP/1.1" 404 231
DEBUG:pycarwings2.pycarwings2:Response HTTP Status Code: 404
DEBUG:pycarwings2.pycarwings2:Response HTTP Response Body: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /api_v180117_NE/gdc/InitialApp.php was not found on this server.</p>
</body></html>

ERROR:root:CarWings API error

It doesn't seem to work - DEBUG:pycarwings2.pycarwings2:Response HTTP Status Code: 404

Hi Folks
I'm getting a URL error when I try running this script on my emonpi. I've pasted the debug output below, having removed my Leaf user/pass, which we know works on the 'My Leaf' android app.

What am I doing wrong, please?!

Cheers
Tim
root@emonpi:/opt/leaf-mqtt# ./leaf-python-mqtt.py
INFO:root:Startup leaf-python-MQTT: 2020-07-11 18:43:33
INFO:root:Loaded config file /opt/leaf-mqtt/config.ini
INFO:root:updating data from API every 15min
DEBUG:root:login = user , password = pass
INFO:root:Prepare Session
INFO:root:Login...
INFO:root:Start update time: 2020-07-11 18:43:33
DEBUG:pycarwings2.pycarwings2:invoking carwings API: https://gdcportalgw.its-mo.com/api_v181217_NE/gdc/InitialApp.php
INFO:root:Connected to MQTT host localhost with result code 0
DEBUG:pycarwings2.pycarwings2:params: {
"RegionCode": "NE",
"custom_sessionid": "",
"initial_app_strings": "geORNtsZe5I4lRGjG9GZiA",
"lg": "en-US"
}
INFO:root:Suscribing to leaf control topic: emon/leaf/control
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): gdcportalgw.its-mo.com:443
INFO:root:Publishing to leaf status topic: emon/leaf/status
DEBUG:urllib3.connectionpool:https://gdcportalgw.its-mo.com:443 "POST /api_v181217_NE/gdc/InitialApp.php HTTP/1.1" 404 231
DEBUG:pycarwings2.pycarwings2:Response HTTP Status Code: 404
DEBUG:pycarwings2.pycarwings2:Response HTTP Response Body:

<title>404 Not Found</title>

Not Found

The requested URL /api_v181217_NE/gdc/InitialApp.php was not found on this server.

ERROR:root:CarWings API error
INFO:root:Schedule API update every 15min

Error when starting script

./leaf-python-mqtt.py File "./leaf-python-mqtt.py", line 191 else ^ IndentationError: unindent does not match any outer indentation level

Crash if status 404 returned by API

In get_leaf_status() if logging in fails because a 404 is returned then we crash! See traceback below.

Jan 25 14:52:28 hapi3 python[29483]: DEBUG:pycarwings2.pycarwings2:Response HTTP Status Code: 200
Jan 25 14:52:28 hapi3 python[29483]: DEBUG:pycarwings2.pycarwings2:Response HTTP Response Body: {"status":404}
Jan 25 14:52:28 hapi3 python[29483]: ERROR:root:CarWings API error
Jan 25 14:52:28 hapi3 python[29483]: INFO:root:get_latest_battery_status
Jan 25 14:52:28 hapi3 python[29483]: Traceback (most recent call last):
Jan 25 14:52:28 hapi3 python[29483]:   File "/srv/leafd/leaf-python-mqtt/leaf-python-mqtt.py", line 228, in <module>
Jan 25 14:52:28 hapi3 python[29483]:     schedule.run_pending()
Jan 25 14:52:28 hapi3 python[29483]:   File "/srv/leafd/venv/local/lib/python2.7/site-packages/schedule/__init__.py", line 493, in run_pending
Jan 25 14:52:28 hapi3 python[29483]:     default_scheduler.run_pending()
Jan 25 14:52:28 hapi3 python[29483]:   File "/srv/leafd/venv/local/lib/python2.7/site-packages/schedule/__init__.py", line 78, in run_pending
Jan 25 14:52:28 hapi3 python[29483]:     self._run_job(job)
Jan 25 14:52:28 hapi3 python[29483]:   File "/srv/leafd/venv/local/lib/python2.7/site-packages/schedule/__init__.py", line 131, in _run_job
Jan 25 14:52:28 hapi3 python[29483]:     ret = job.run()
Jan 25 14:52:28 hapi3 python[29483]:   File "/srv/leafd/venv/local/lib/python2.7/site-packages/schedule/__init__.py", line 411, in run
Jan 25 14:52:28 hapi3 python[29483]:     ret = self.job_func()
Jan 25 14:52:28 hapi3 python[29483]:   File "/srv/leafd/leaf-python-mqtt/leaf-python-mqtt.py", line 158, in get_leaf_status
Jan 25 14:52:28 hapi3 python[29483]:     leaf_info = l.get_latest_battery_status()
Jan 25 14:52:28 hapi3 python[29483]: UnboundLocalError: local variable 'l' referenced before assignment

Python 3.6

Thanks for the great work you did with this program. I wanted to make your version work under py3.6, so there were a couple of changes I noticed. I'm using the py3 fork of pycarwings2 by BenWoodford.

lower case on ConfigParser in line5:
from configparser import SafeConfigParser

The mqtt message to run get_leaf_update or climate_control was not working due to the change in bytes/strings. In line 56, should be:
logging.info(msg.topic+" "+msg.payload.decode('UTF-8'))

By the same token in line 59:
control_message = msg.payload.decode('UTF-8')

I don't know if these break your version for py2 as I didn't test.

Crash when receiving update 60s after starting heating...

Hello,

I've integrated your development with my OpenHab2 server and I'm now having a little problem.

When I send a request to starting heating int my Leaf, the heating starts fine in the car, but something is going wrong in pycarwings2 and leaf-python-mqtt.py crash with a "KeyError: 'cruisingRangeAcOff'" after its 60s wainting.

The whole trace is :

INFO:root:publishing to MQTT base status topic: leaf/status
INFO:root:leaf/control/leaf_update ON
INFO:root:control sub-topic: leaf_update
INFO:root:control message: ON
INFO:root:leaf/control/climate 1
INFO:root:control sub-topic: climate
INFO:root:control message: 1
INFO:root:Climate control command received: 1
INFO:root:Prepare Session climate control update
INFO:root:Login...
INFO:root:2018-01-25 23:37:33
INFO:root:Turning on climate control..wait 60s
Exception in thread Thread-1:
Traceback (most recent call last):
File "/volume1/@appstore/python/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/volume1/@appstore/python/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/volume1/@appstore/python/lib/python2.7/site-packages/paho/mqtt/client.py", line 2650, in _thread_main
self.loop_forever(retry_first_connection=True)
File "/volume1/@appstore/python/lib/python2.7/site-packages/paho/mqtt/client.py", line 1481, in loop_forever
rc = self.loop(timeout, max_packets)
File "/volume1/@appstore/python/lib/python2.7/site-packages/paho/mqtt/client.py", line 1003, in loop
rc = self.loop_read(max_packets)
File "/volume1/@appstore/python/lib/python2.7/site-packages/paho/mqtt/client.py", line 1284, in loop_read
rc = self._packet_read()
File "/volume1/@appstore/python/lib/python2.7/site-packages/paho/mqtt/client.py", line 1849, in _packet_read
rc = self._packet_handle()
File "/volume1/@appstore/python/lib/python2.7/site-packages/paho/mqtt/client.py", line 2305, in _packet_handle
return self._handle_publish()
File "/volume1/@appstore/python/lib/python2.7/site-packages/paho/mqtt/client.py", line 2500, in _handle_publish
self._handle_on_message(message)
File "/volume1/@appstore/python/lib/python2.7/site-packages/paho/mqtt/client.py", line 2647, in _handle_on_message
self.on_message(self, self._userdata, message)
File "./leaf-python-mqtt.py", line 68, in on_message
climate_control(1)
File "./leaf-python-mqtt.py", line 108, in climate_control
start_cc_result = l.get_start_climate_control_result(result_key)
File "/volume1/@appstore/python/lib/python2.7/site-packages/pycarwings2/pycarwings2.py", line 249, in get_start_climate_control_result
return CarwingsStartClimateControlResponse(response)
File "/volume1/@appstore/python/lib/python2.7/site-packages/pycarwings2/responses.py", line 319, in init
self._set_cruising_ranges(status)
File "/volume1/@appstore/python/lib/python2.7/site-packages/pycarwings2/responses.py", line 50, in _set_cruising_ranges
self.cruising_range_ac_off_km = float(status[off_key]) / 1000
KeyError: 'cruisingRangeAcOff'

After that, "leaf-python-mqtt.py" need to be restarted if I want to do anything else.

One thing worth mentioning : I'm in Canada and therefore my region is NCI.

Thank you!

Region hard-code in leaf-python-mqtt.py

Hello,

I'm in Canada and your solution was not working for me... After checking you code, I realize that the region was hard-coded to "NE" at two lines in the "leaf-python-mqtt.py" :

  • Line 99 : s = pycarwings2.Session(username, password , "NE")
  • Line 123 : s = pycarwings2.Session(username, password , "NE")

After replacing "NE" with variable "nissan_region_code", everything started to work for me.

Thank you for the code, great job!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.