IoT mit ESP8266 und Blynk
Blynk ist eine Cloud Platform um IoT Anwendungen zu benutzen und zu verbinden, es gibt dazu eine eigene APP mit der die IoT Sensoren/Actoren gesteuert werden können.
Klingt nicht schlecht, also hab ich das mal ausprobiert.
Voraussetzungen
- ESP8266
- DHT 22 Temperatur & Luftfeutigkeitssensor
- Ein paar Kabel
- Mycropython Firmware
- Blynk Python Binding
- Blynk App am Smartphone
Projekt Struktur Root Ordner
drwxrwxr-x 4 mesznera mesznera 4096 Jan 3 13:50 blynk-library-python
drwxrwxr-x 2 mesznera mesznera 4096 Jan 4 07:52 ESP8266
-rwxr-xr-x 1 mesznera mesznera 970 Jan 4 08:13 flash.sh
-rw-rw-r-- 1 mesznera mesznera 3865 Jan 4 11:59 main.py
Im Subdirectory ESP8266 ist die Mycropython Firmware von
http://micropython.org/download/esp8266/
esp8266-20200911-v1.13.bin
Im Subdirectory blynk-library-python
das GIT Repository von
https://github.com/vshymanskyy/blynk-library-python.git
flash.sh
Hier das Shell Script das ich unter Ubuntu verwende um den ESP8266 zu flashen.
#!/bin/bash
#
#
# either ESP8266 or ESP32
# corresponding subdirectory with firmware
BOARD=ESP8266
# USB port to communicate
PORT=/dev/ttyUSB0
# port speed
BAUD=460800
if [ $BOARD == "ESP8266" ]; then
# for ESP8266
esptool.py --port $PORT erase_flash
esptool.py --port $PORT --baud $BAUD write_flash --flash_size=detect --verify -fm dio 0x0 $BOARD/esp8266-20200911-v1.13.bin
fi;
if [ $BOARD == "ESP32" ]; then
# for ESP32
esptool.py --chip esp32 --port $PORT erase_flash
esptool.py --chip esp32 --port $PORT --baud $BAUD write_flash -z 0x1000 $BOARD/esp32-idf4-20200902-v1.13.bin
fi
echo "sleeping for 10s to wait for reset"
sleep 10
# screen communication speed
BAUD=115200
ampy -b $BAUD -p $PORT mkdir /lib
ampy -b $BAUD -p $PORT put blynk-library-python/BlynkLib.py /lib/BlynkLib.py
# ampy -b $BAUD -p $PORT put blynk-library-python/examples/hardware/ESP8266_ESP32.py main.py
ampy -b $BAUD -p $PORT put main.py main.py
screen $PORT $BAUD
main.py
Hier ein kleines Beispiel das Daten eines DHT22 ausliest
Das Script ist nicht optimiert, aber es geht mir nur um die Funktion um blynk auszuprobieren.
Damit das funktioniert muss man noch folgendes im Programm anpassen
- WLAN SSID
- WLAN PSK
- Blynk API Key - den bekommt man, wenn man ein Projekt eröffnet.
"""
Blynk is a platform with iOS and Android apps to control
Arduino, Raspberry Pi and the likes over the Internet.
You can easily build graphic interfaces for all your
projects by simply dragging and dropping widgets.
Downloads, docs, tutorials: http://www.blynk.cc
Sketch generator: http://examples.blynk.cc
Blynk community: http://community.blynk.cc
Social networks: http://www.fb.com/blynkapp
http://twitter.com/blynk_app
This example shows how to initialize your ESP8266/ESP32 board
and connect it to Blynk.
Don't forget to change WIFI_SSID, WIFI_PASS and BLYNK_AUTH ;)
"""
import dht
import machine
import network
import time
# non std modules
import BlynkLib
#
# some constants, should be in settings.py
#
#
DEBUG = True
# depends on your own infrastructure
WIFI_SSID = 'sagichnicht'
WIFI_PASS = 'sagichauchnicht'
# you get this by creating some project
BLYNK_AUTH = 'das sag ich auch nicht'
# connecting dht22
# PIN DHT is connected to
DHT_PIN = 5 # dont use 1, this does not work
DHT = dht.DHT22(machine.Pin(DHT_PIN))
DHT_INTERVAL = 300 # 5 mins
DHT.measure()
DHT_TS = time.time()
print(DHT_TS)
print(DHT.temperature())
print(DHT.humidity())
def read_dht():
"""
reading DHT
only measuring, if last measurement is more than DHT_INTERVAL old
"""
global DHT_INTERVAL
global DHT_TS
if (time.time() - DHT_TS) > DHT_INTERVAL:
print("Doing re-measurement")
DHT.measure()
DHT_TS = time.time()
print("Timestamp :", DHT_TS)
print("Temperature :", DHT.temperature())
print("Humidity :", DHT.humidity())
def disable_ap():
"""
per default micropython will enable an AP SSID
this short function will disable AP Mode on startup
for more information go to
http://docs.micropython.org/en/v1.8.7/esp8266/esp8266/tutorial/network_basics.html
"""
ap_if = network.WLAN(network.AP_IF)
ap_if.active(False)
#
# initializing network, main
#
# blynk must be created in prior of every decorator use
print("disabling WIFI AP mode")
disable_ap()
print("Connecting to WiFi...")
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID, WIFI_PASS)
while not wifi.isconnected():
pass
print('IP:', wifi.ifconfig()[0])
print("Connecting to Blynk...")
blynk = BlynkLib.Blynk(BLYNK_AUTH)
@blynk.on("connected")
def blynk_connected(ping):
"""
called if connection to blynk is established
"""
print('Blynk ready. Ping:', ping, 'ms')
# Register Virtual Pins
@blynk.VIRTUAL_WRITE(1)
def my_write_handler(value):
"""
write something to this virtual pin
"""
print("blynk rwriting virtual pin 1")
print('Current V1 value: {}'.format(value))
@blynk.VIRTUAL_READ(2)
def my_read_handler():
"""
read something from virtual pin
this version only returns actual uptime
"""
print("blynk reading virtual pin 2")
blynk.virtual_write(2, int(time.time()))
@blynk.VIRTUAL_READ(3)
def my_read_handler():
"""
read something from virtual pin
"""
print("blynk reading virtual pin 3")
read_dht()
blynk.virtual_write(3, DHT.temperature())
@blynk.VIRTUAL_READ(4)
def my_read_handler():
"""
read something from virtual pin
"""
print("blynk reading virtual pin 4")
read_dht()
blynk.virtual_write(4, DHT.humidity())
def runLoop():
while True:
blynk.run()
machine.idle()
########## main starts here ###################
# Run blynk in the main thread:
runLoop()
# Or, run blynk in a separate thread (unavailable for esp8266):
#import _thread
#_thread.stack_size(5*1024)
#_thread.start_new_thread(runLoop, ())
# Note:
# Threads are currently unavailable on some devices like esp8266
# ESP32_psRAM_LoBo has a bit different thread API:
# _thread.start_new_thread("Blynk", runLoop, ())
Was zu bemerken ist:
- Blynk arbeitet mit Decoratoren
- Nur über HTTP Requests
- Viel Idle geht sich da wohl nicht aus
Elektronik
Den DHT 22 verbindet man wie folgt
- DHT + -> 3.3V
- DHT - -> GND
- DHT OUT -> D1
Doing
- Also den ESP8266 mit USB an den Computer
- Der ESP sollte unter Ubuntu als ttyUSB0 erkannt werden
- flash.sh laufen lassen, damit wird die Mycropython Firmware installiert
- Dann wird main.py und die Blynk Library kopiert
- zuletzt ein screen auf /dev/ttyUSB0
kernel (demsg) Meldungen beim anschließen des ESP8266
[126329.405898] IPv6: ADDRCONF(NETDEV_CHANGE): wlp4s0: link becomes ready
[128272.669418] usb 3-1: new full-speed USB device number 31 using xhci_hcd
[128272.822764] usb 3-1: New USB device found, idVendor=1a86, idProduct=7523, bcdDevice= 2.63
[128272.822770] usb 3-1: New USB device strings: Mfr=0, Product=2, SerialNumber=0
[128272.822773] usb 3-1: Product: USB2.0-Serial
[128272.824070] ch341 3-1:1.0: ch341-uart converter detected
[128272.824646] usb 3-1: ch341-uart converter now attached to ttyUSB0
Outut beim flashen
esptool.py v2.8
Serial port /dev/ttyUSB0
Connecting....
Detecting chip type... ESP8266
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: 50:02:91:4e:f1:45
Uploading stub...
Running stub...
Stub running...
Erasing flash (this may take a while)...
Chip erase completed successfully in 7.2s
Hard resetting via RTS pin...
esptool.py v2.8
Serial port /dev/ttyUSB0
Connecting....
Detecting chip type... ESP8266
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: 50:02:91:4e:f1:45
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 460800
Changed.
Configuring flash size...
Auto-detected Flash size: 4MB
Flash params set to 0x0240
Compressed 638928 bytes to 419659...
Wrote 638928 bytes (419659 compressed) at 0x00000000 in 9.6 seconds (effective 533.9 kbit/s)...
Hash of data verified.
Leaving...
Verifying just-written flash...
(This option is deprecated, flash contents are now always read back after flashing.)
Flash params set to 0x0240
Verifying 0x9bfd0 (638928) bytes @ 0x00000000 in flash against ESP8266/esp8266-20200911-v1.13.bin...
-- verify OK (digest matched)
Hard resetting via RTS pin...
sleeping for 10s to wait for reset
[detached from 65532.pts-1.ws00007999]
Am Ende habe ich screen mit Ctrl+A, Ctrl+D detached
Screen Cheat Sheet
CTRL + A, CTRL + D -> Detach
Blynk
Also die Blynk App hab ich schon installiert, dann ein Projekt eröffnet. Damit bekommt man den benötigten API Key zugeschickt.
Und so sieht das Ganze dann in der APP aus
Fazit
Eigentlich funktioniert Blynk recht einfach, man erhält eine gute APP auf allen Smartphones und muß keinen Server oder sonstiges einrichten um die Daten aufzubereiten. Für den privaten Einsatz ist die Nutzung kostenlos.
Wenn man allerdings viele Sensoren einbinden möchte, dann stößt man gleich ans Limit und muß bei blynk auch bezahlen.
Für eine kommerzielle Entwicklung ist blynk sicher eine Überlegung wert, man erspart sich den ganzen Server Part und bekommt eine APP geliefert mit der sich die IoT Devices steuern lassen. Man kann sich also um die Devices selbst kümmern.
Wenn man aber das im privaten Umfeld mit mehreren Devices, ich denk mal mehr als 10, nutzen möchte kommt man mit der gratis Version von blynk nicht mehr weit.