Skip to content

Commit e0c415b

Browse files
committed
Add blog post from home-assistant#664
1 parent 9a39102 commit e0c415b

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
---
2+
layout: post
3+
title: "ESP8266 and MicroPython - Part 2"
4+
description: "Export, process, and visualize data stored by Home Assistant."
5+
date: 2016-08-31 06:17:25 +0200
6+
date_formatted: "August 31, 2016"
7+
author: Fabian Affolter
8+
comments: true
9+
categories: How-To MQTT ESP8266 Micropython
10+
og_image: /images/blog/2016-07-micropython/social.png
11+
---
12+
13+
<img src='/images/blog/2016-07-micropython/micropython.png' style='clear: right; border:none; box-shadow: none; float: right; margin-bottom: 12px;' width='200' />
14+
So, part 1 of [ESP8266 and MicroPython](/blog/2016/07/28/esp8266-and-micropython-part1/) was pretty lame, right? Instead of getting information out of Home Assistant we are going a step forward and create our own sensor which is sending details about its state to a Home Assistant instance.
15+
16+
<!--more-->
17+
18+
Beside [HTTP POST](https://en.wikipedia.org/wiki/POST_(HTTP)) requests, MQTT is the quickest way (from the author's point of view) to publish information with DIY devices.
19+
20+
You have to make a decision: Do you want to pull or to poll? For slowly changing values like temperature it's perfectly fine to wait a couple of seconds to retrieve the value. If it's a motion detector the state change should be available instantly. This means the sensor must take initiative.
21+
22+
An example for pulling is [aREST](/components/sensor.arest/). This is a great way to work with the ESP8266 based units and the Ardunio IDE.
23+
24+
### {% linkable_title MQTT %}
25+
26+
You can find a simple examples for publishing and subscribing with MQTT in the [MicroPython](https://github.com/micropython/micropython-lib) library overview in the section for [umqtt](https://github.com/micropython/micropython-lib/tree/master/umqtt.simple).
27+
28+
The example below is adopted from the work of [@davea](https://github.com/davea) as we don't want to re-invent the wheel. The configuration feature is crafty and simplyfies the code with the usage of a file called `/config.json` which stores the configuration details. The ESP8266 device will send the value of a pin every 5 seconds.
29+
30+
31+
```python
32+
import machine
33+
import time
34+
import ubinascii
35+
import webrepl
36+
37+
from umqtt.simple import MQTTClient
38+
39+
# These defaults are overwritten with the contents of /config.json by load_config()
40+
CONFIG = {
41+
"broker": "192.168.1.19",
42+
"sensor_pin": 0,
43+
"client_id": b"esp8266_" + ubinascii.hexlify(machine.unique_id()),
44+
"topic": b"home",
45+
}
46+
47+
client = None
48+
sensor_pin = None
49+
50+
def setup_pins():
51+
global sensor_pin
52+
sensor_pin = machine.ADC(CONFIG['sensor_pin'])
53+
54+
def load_config():
55+
import ujson as json
56+
try:
57+
with open("/config.json") as f:
58+
config = json.loads(f.read())
59+
except (OSError, ValueError):
60+
print("Couldn't load /config.json")
61+
save_config()
62+
else:
63+
CONFIG.update(config)
64+
print("Loaded config from /config.json")
65+
66+
def save_config():
67+
import ujson as json
68+
try:
69+
with open("/config.json", "w") as f:
70+
f.write(json.dumps(CONFIG))
71+
except OSError:
72+
print("Couldn't save /config.json")
73+
74+
def main():
75+
client = MQTTClient(CONFIG['client_id'], CONFIG['broker'])
76+
client.connect()
77+
print("Connected to {}".format(CONFIG['broker']))
78+
while True:
79+
data = sensor_pin.read()
80+
client.publish('{}/{}'.format(CONFIG['topic'],
81+
CONFIG['client_id']),
82+
bytes(str(data), 'utf-8'))
83+
print('Sensor state: {}'.format(data))
84+
time.sleep(5)
85+
86+
if __name__ == '__main__':
87+
load_config()
88+
setup_pins()
89+
main()
90+
```
91+
92+
Subscribe to the topic `home/#` or create a [MQTT sensor](/components/sensor.mqtt/) to check if the sensor values are published.
93+
94+
```bash
95+
$ mosquitto_sub -h 192.168.1.19 -v -t "home/#"
96+
```
97+
98+
```yaml
99+
sensor:
100+
- platform: mqtt
101+
state_topic: "home/esp8266_[last part of the MAC address]"
102+
name: "MicroPython"
103+
```
104+
105+
[@davea](https://github.com/davea) created [sonoff-mqtt](https://github.com/davea/sonoff-mqtt). This code will work on ESP8622 based devices too and shows how to use a button to control a relay.
106+

0 commit comments

Comments
 (0)