ESP8266 + DHT22 + Homie -> Home-Assistant

So now that I had a Home-Assistant (HA) setup working, an esp8266 booting and that I can write software for, it was time to start making the two talk to each other and make something that can become unseful based on all this.

The choice went to the simplest element I had at hand, a DHT22 temperature and humidity sensor.

There were 5 steps to do this:

  • wire the dht22 on a test setup
  • find how to use it in a Homie firmware, and flash it
  • configure the device
  • configure HA for MQTT, which led me to rewrite the whole configuration
  • test it

So let's get to this step by step

Wiring the DHT22

It can be pretty simple, without pullup resistors and capacitor, I found this on instructable

dht22
wiring

I simply put this to another GPIO on my esp12f, but that's pretty much it. The result on the breadboard looks like this:

dht22 breadboard

That's about it, for testing of course, for a final sensors, I'll have to make it cleaner than that...

Homie firmware

I started looking up for code on how to use homie with the dht22, there are libs to make use of it, running:

platformio lib search dht

Showed me the DHT sensor library that is esspressif compatible, I simply installed it via:

platformio lib install 19

After that I looked online at examples to use it, and actually found this code which does exactly what I expected. At first I started writting each lines trying to include only the needed one. But I think this is really close to the bare minimum to get something fully working, so I simply renamed it to raton-dht and switch the version to 0.0.1.

Jumping a little off-topic, the version number has an interest, because Homie support OTA, using the pretty cool homie-ota, which includes a listing of firmware and an inventory of devices, which is pretty awesome for handling yor homie devices and update them if need be. I haven't tried it yet myself, but I definitely will once I get real devices up and running in the house. This really looks like a must-have to me. Once again, thanks jpmens!

Back on tracks, not having the OTA setup yes, I simply switched my GPIO0 to low and ran:

platformio run -t upload

And the next boot the dht sensors firmware was sitting in configuration mode.

Homie configuration

In the previous post, I didn't explain how to configure the homie devices, I actually did not discover it at this step, I played with this on the previous useless firmware to understand how it works.

First it is worth noting that the homie-esp8266 documentation has been moved from github to readme.io, there on the http json api page, you can find the 3 options that you can use to configure your device in configuration mode:

  • the Web UI
  • the android app which apparently is a a webview directly to the webui (at least that's my guess)
  • a curl example, but you'll need to know what the config.json looks like like described in the dedicated page

In any case, you'll need to be connected to the AP the homie device will create when in configuration mode, for me, working on a workstation, and not having my laptop at hand (and feeling too lazy to grab it, plug it as it isn't charged right now, configure another wireless device via wpa_supplicant), that only left me with my android phone... But there is a catch: android checks that it can reach outside to actually let you use your wifi connection.

I found here that on a rooted device you can run:

settings put global captive_portal_detection_enabled 0

This did the trick for me, so I ran that, connected to the Homie-XXXXX AP, and fired the android app, which found the device, and allow me to configure it, the configuration is pretty straightforward and short, once this is done, you can finally reboot the homie device in normal mode, where it connects to your AP/router and start trying to talk to the mqtt broker. Now on to the HA setup.

Home-Assistant MQTT configuration

As said in the previous post, I was planning on using the embedded MQTT broker in HA. According to the MQTT component page, to enable MQTT support in HA, we have to add

mqtt:

To the configuration file, other parameters are for specifying the broker, to use the embedded one, without further configuration, that's it. Restarting HA with that enables the MQTT broker.

Next we need to configure the sensors, but when I started to look to add this I realized how messy my HA configuration had become, with so few things it looked already pretty cluttered with useless things, comments that are only usefull when beginning to use it. So i decided to go for a huge cleanup and rewrite.

First step, version control, I planned on splitting it in multiple files, and this won't be any easy to handle and maintain if not in git, so I created a ha-cfg github repo

I went from this to that

It took some fiddling to understand the !include which is not totally obvious to use, but I'm pretty happy with the final result.

Now in my sensors.yaml I simply added

# temperature test
- platform: mqtt
  state_topic: devices/01397be0/temperature/degrees
  name: "Test temperature"
  qos: 0
  unit_of_measurement: "°C"

# humidity test
- platform: mqtt
  state_topic: devices/01397be0/humidity/relative
  name: "Test humidity"
  qos: 0
  unit_of_measurement: "%"

And I was all set.

Testing

After that and restarting HA with the new configuration, I booted the esp again and could see:

** Booting into normal mode **
{} Stored configuration:
   Hardware device ID: 01397be0
   Device ID: 01397be0
   Boot mode: normal
   Name: dht#1
   Wi-Fi
     SSID: SFR-5458
     Password not shown
   MQTT
     Host: 192.168.0.6
     Port: 1883
     Base topic: devices/
     Auth? no
     SSL? no
   OTA
     Enabled? yes
     Host: 192.168.0.17
     Port: 80
     Path: /ota
     SSL? no
 Attempting to connect to Wi-Fi...
 Wi-Fi connected
Triggering HOMIE_WIFI_CONNECTED event...
 Attempting to connect to MQTT...
Connected
Sending initial information...  OK
Subscribing to topics...  OK
 MQTT ready
Triggering HOMIE_MQTT_CONNECTED event...
Calling setup function...
Sending Wi-Fi signal quality (100%)...  OK
Sending uptime (8s)...  OK

And on HA web-ui I know have test humidity and test temperature sensors showing up on the top row.

ha-ui

And that's it!


21 août 2016 12:39:25 -- tags [ esp8266 , dht22 , home-assistant , homie ]


22 juin 2017 19:43:22 - JohnetteX

I see your page needs some fresh content. Writing manually takes a lot of time, but there is tool for this boring task, search in google: murgrabia's tools

20 août 2017 17:46:42 - car insurance quotes

auto insurance quotes cheapest car insurance cheap insurance for cars cheap car insurance online

9 septembre 2017 15:01:14 - nurpnzrix

payday loans online same day <a href="http://paydayloans2017.com"> payday loans with no bank account</a> &lt;a href=&quot;http://paydayloans2017.com&quot;&gt; payday loans&lt;/a&gt; http://paydayloans2017.com - online payday loans payday loans online direct lenders only

1 février 2018 13:48:59 - WinnerAmeks

If you’re interested in winning millions, then I’m here to help! At <a href=skyliteboom.com>Casino</a> you can play over 450 world-class games and I’m giving you an exclusive Welcome Bonus to get you stuck into winning. Use it today to increase your chances of hitting our jackpots. All you have to do is <a href=skyliteboom.com>sign up today</a> and watch the rewards come rolling in. skyliteboom.com <a href=skyliteboom.com>Prepare to hit the big time</a> <a href=skyliteboom.com>Hacer giros para ganar millones</a> <a href=skyliteboom.com>Holen Sie sich spinnen, um Millionen zu gewinnen</a> <IMG>http://i63.tinypic.com/ofdmds.jpg</IMG>

12 mars 2018 22:03:23 - Josephmub

Thanks! I enjoy this. which is better levitra or viagra or cialis <a href="http://cialisfidel.com/">buy cialis online</a> what is cialis pills for <a href=http://cialisfidel.com/>generic for cialis</a>

5 avril 2018 14:31:09 - Guestbroni

guest test post <a href=" http://temresults2018.com/ ">bbcode</a> <a href="http://temresults2018.com/">html</a> http://temresults2018.com/ simple

17 mai 2018 12:55:09 - AnthonyThype

<a href="http://canadianonlinepharmacyhd.com/">canadian pharcharmy online</a> http://canadianonlinepharmacyhd.com/ <a href=http://canadianonlinepharmacyhd.com/>best online international pharmacies</a>

22 mai 2018 18:31:44 - reputable mexican pharmacies online

<a href="http://canadianonlinepharmacyhd.com/">online pharmacy</a> http://canadianonlinepharmacyhd.com/ <a href=http://canadianonlinepharmacyhd.com/>no prescription pharmacy canada</a>

4 juin 2018 13:15:04 - canadian pharmacies online

<a href="http://canadianonlinepharmacyhd.com/">canadian pharmacy</a> http://canadianonlinepharmacyhd.com/ <a href=http://canadianonlinepharmacyhd.com/>legitimate canadian pharmacies</a>

10 juin 2018 04:13:29 - canadian pharmacy

<a href="http://canadianonlinexyz.com/">canadian pharmacies shipping to usa</a> http://canadianonlinexyz.com/ <a href=http://canadianonlinexyz.com/>approved canadian online pharmacies</a>

13 juin 2018 07:17:01 - best online pharmacy

<a href="http://canadianonlinexyz.com/">prescriptions from canada without</a> http://canadianonlinexyz.com/ <a href=http://canadianonlinexyz.com/>rx online no prior prescription</a>

25 juin 2018 16:48:01 - Webseokl

<img src="http://vvp33.ru/upload/blogs/bfedea6816a48dbfd13f5b98445ffd9e.jpg"> <a href=https://webcrasty.ru/><img src="http://psytraining.org/nevesta/wp-content/uploads/2015/07/podrobnee-box.png"></a> Понятно, что вручную их не вариант каждый раз проверять. В данном материале я рассмотрю несколько сервисов и программ, которые решают этот вопрос. Блог SEO Jedi. Продвижение сайта в тематике «Окна ПВХ» Всем привет! Подбор площадок <b><u><a href=https://webcrasty.ru/>раскрутка сайта на яндекс</a>. </b></u> Сегодня хочу рассказать о создании и дальнейшем продвижении сайта по продаже окон ПВХ. Конкуренция у этих товарищей жесточайшая, поэтому и подходы к раскрутке и рекламе должны отличаться от лидеров мнений, чтобы хоть какая-то была возможность появляться в органическом поиске, а не только вбухивать умопомрачительные бюджеты в контекст. Начну историю с истории создания сайта. В процессе расскажу, какими сервисами пользуюсь при работе по созданию и продвижению сайтов. (more…) Качественные ссылки для Google и Yandex. Всем привет! Это один из самых важных моментов, который будет влиять на дальнейшее продвижения ресурса <a href=https://webcrasty.ru/>продвижение синоним</a>. Обратные ссылки — это один из самых больших и устойчивых факторов ранжирования поиска. Ссылки были важны с самого начала существования поисковых систем, и я могу гарантировать, что они будут важны до тех пор, пока существуют поисковые системы. Ссылки являются основой SEO, но за последние годы они сильно изменились. запросы: <u><b>продвижение сайта с нуля, </b></u> раскрутка и оптимизация сайта, раскрутить интернет магазин самому, продвижение сайта в топ яндекса, seo продвижение сайта обучение, продвижение сайта google adwords, продвижение сайтов, <b><u>раскрутка сайта что это такое, </b></u> раскрутка сайта google, продвижение компании в сети интернет диплом, <u><b>продвижения на английском, </b></u> продвижение сайта на яндексе цена, <img src="https://image.ibb.co/jb7P0J/image.png"> http://lhl-77.ru/community/index.php?topic=657.new#new https://www.icscc.com/forums/member.php?3170-WebseoKr http://alex-cinemas.com/takatsuki/blog/log/eid69.html?

21 juillet 2018 20:24:18 - online pharmacy no prescription

<a href="http://canadianonlinexyz.com/">canadian pharmary without prescription</a> http://canadianonlinexyz.com/ <a href=http://canadianonlinexyz.com/>legitimate canadian pharmacies</a>

7 août 2018 18:35:56 - canadian mail order pharmacies to usa

<a href="http://canadianonlinexyz.com/">canadian pharmacies shipping to usa</a> http://canadianonlinexyz.com/ <a href=http://canadianonlinexyz.com/>safe canadian online pharmacies</a>