Easy and easy IoT life using Micropython!

This post is

Python Advent Calendar 2019 This is the third day of posting.

Micropython is good

Aside from the Raspberry Pi The so-called ESP32 series can use Wifi, but like Arduino, it is a substitute that burns the program to ROM and executes it, basically it is a C language-like program using Arduino's IDE. I write.

···But

HTTP request is lazy www Even though it is IoT only by linking edge point data with SaaS Honestly, it makes you unmotivated when HTTP requests are sluggish.

Write like this with Arduino

Arduino Http Client sample sketch

HTTPPost


#include <ArduinoHttpClient.h>
#include <WiFi101.h>

#include "arduino_secrets.h"

///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// Wifi Settings ///////
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;


char serverAddress[] = "192.168.0.3";  // server address
int port = 8080;

WiFiClient wifi;
HttpClient client = HttpClient(wifi, serverAddress, port);
int status = WL_IDLE_STATUS;

void setup() {
  Serial.begin(9600);
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);                   // print the network name (SSID);

    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);
  }

  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
}

void loop() {
  Serial.println("making POST request");
  String postData = "name=Alice&age=12";

  client.beginRequest();
  client.post("/");
  client.sendHeader("Content-Type", "application/x-www-form-urlencoded");
  client.sendHeader("Content-Length", postData.length());
  client.sendHeader("X-Custom-Header", "custom-header-value");
  client.beginBody();
  client.print(postData);
  client.endRequest();

  // read the status code and body of the response
  int statusCode = client.responseStatusCode();
  String response = client.responseBody();

  Serial.print("Status code: ");
  Serial.println(statusCode);
  Serial.print("Response: ");
  Serial.println(response);

  Serial.println("Wait five seconds");
  delay(5000);
}

Even though I just POST, it's sloppy www Well, I hope I get used to it, but it's really bad ...

To use MicroPython ...

For the time being, we need a foundation.

Foundation

I think this area is good.

https://www.switch-science.com/catalog/5448/ https://www.switch-science.com/catalog/3210/

It's okay to use the cheap ESP32 series sold on Amazon. To be honest, there is a problem of technical suitability, and even if it is marked, there is also a problem of whether it is really genuine technical suitability, so buy this area from a solid place.

Please refer to this manual for the installation method.

Getting Started with MicroPython on ESP32

How to write

MicroPython is designed to run boot.py first and then main.py when it is powered on.

boot.py

It will be the first Python file to be called when power is turned on. Basically, it's a good idea to incorporate a process that connects to Wifi.

boot.py



import utime
import network
# ==== connecti to wifi access point ============================================
SSID_NAME = <SSID>
SSID_PASS = <WifiPassword>

def connect_wifi(ssid, passkey, timeout=10):
    wifi= network.WLAN(network.STA_IF)
    if wifi.isconnected() :
        print('already Connected.    connect skip')
        return wifi
    else :
        wifi.active(True)
        wifi.connect(ssid, passkey)
        while not wifi.isconnected() and timeout > 0:
            print('.')
            utime.sleep(1)
            timeout -= 1
    
    if wifi.isconnected():
        print('Connected')
        return wifi
    else:
        print('Connection failed!')
        return null

wifi = connect_wifi(SSID_NAME, SSID_PASS)
if not wifi :
    sys.exit(0)

main.py

It will be a Python file that will be executed when the execution of boot.py ends normally. If you have made Arduino etc., you can understand Basically, this Python file is based on ** infinite loop **.

main.py



from m5stack import lcd # m5stack Library
import machine
import time

lcd.setCursor(0, 0)
lcd.setColor(lcd.WHITE)
lcd.font(lcd.FONT_DejaVu24)
rtctime = machine.RTC()

def aaaaaa():
    global rtctime
    prm_year = '{:0=4}'.format(timedata[0])
    prm_month = '{:0=2}'.format(timedata[1])
    prm_day = '{:0=2}'.format(timedata[2])
    prm_hour = '{:0=2}'.format(timedata[3])
    prm_minute = '{:0=2}'.format(timedata[4])
    prm_second = '{:0=2}'.format(timedata[5])
    
    prm_datetime =  prm_year + "-" \
                +   prm_month + "-" \
                +   prm_day + "T" \
                +   prm_hour + ":" \
                +   prm_minute + ":" \
                +   prm_second + "Z"


    lcd.print(prm_datetime,10,10)

while True: #infinite loop
    aaaaaa()
    time.sleep(1)

important point

It does not have as much storage area and execution memory area (heap area) as a personal computer or Raspberry Pi. As you can see from this article, it's quite a few.

[mgo-tec electronic work: ESP32-WROOM-32 chip memory MAC address information acquisition method](https://www.mgo-tec.com/blog-entry-chip-info-esp-wroom-32-esp32 .html)

Please note that if you code loosely, the heap area will be used up in a blink of an eye, GC will occur frequently, and the Python file you created in the first place will not be included.

How do you make an http request?

I think Python uses the requests library, For MicroPython, use the urequests library. The functionality is almost the same as the requests library.

urequests



import ujson
import urequests

    def postpowerbi(self):
        pbheaders = {
            'Content-Type' :'application/json'
        }
        body = [
                {
                    "datetime" : self.datetime,
                    "temp" : float(self.temp),
                    "humi" : float(self.humi),
                    "pres" : float(self.pres)
                }
            ]
        body_json = ujson.dumps(body).encode("utf-8")
        res = urequests.post(
            self.posturl,
            data=body_json,
            headers=pbheaders
        )
        res.close()

What about other libraries? ??

Basically, I wish you could see this ...

github MicroPython Lib

What about IoT device libraries?

Adafruit, who makes many temperature sensors, also has a library for Python.

github Adafruit

By using this, you can easily control IoT devices.

Adafruit is expensive, but isn't the Chinese one sold on Amazon bad?

Although it is deprecated, there are some that can be used if the bases such as the sensors used are the same. However, there are traps, so at your own risk. You may need to modify some of the library. Please stop using it for your own products and do it within your hobby.

Summary

I wrote it loosely, but even Python makes it easy to create an original IoT device at a low enough price! Please give it a try!

Recommended Posts

Easy and easy IoT life using Micropython!
AWS IoT device life and death monitoring
Easy connection between Raspberry Pi and AWS IoT
Easy IoT to start with Raspberry Pi and MESH
[Python] Easy Google Translate app using Eel and Googletrans
This and that using reflect
Try using pytest-Overview and Samples-
Difference between MicroPython and CPython
Create your own IoT platform using raspberry pi and ESP32 (Part 1)