DEV Community

Lunran
Lunran

Posted on

(Failed attemped) How to get Maixduino connected to AWS IoT

(Failed attemped) How to get Maixduino connected to AWS IoT

Steps

AWS IoT Preparation

  1. Create Resource
  2. Display MQTT message

Preparing Maixduino

  1. Smoke test
  2. Upgrade firmware
  3. Place a script to enable WiFi
  4. Send MQTT message over SSL
import socket
import ussl as ssl
import json
from network_esp32 import wifi

SSID = "(set yours)"
PASW = "(set yours)"

KEY_PATH = '(set yours)'
CERT_PATH = '(set yours)'
END_POINT = '(set yours)'

def enable_esp32():

    if wifi.isconnected() == False:
        for i in range(5):
            try:
                # Running within 3 seconds of power-up can cause an SD load error
                # wifi.reset(is_hard=False)
                wifi.reset(is_hard=True)
                print('try AT connect wifi...')
                wifi.connect(SSID, PASW)
                if wifi.isconnected():
                    break
            except Exception as e:
                print(e)
    print('network state:', wifi.isconnected(), wifi.ifconfig())

def send():

    s = socket.socket()

    ai = socket.getaddrinfo(END_POINT, 8883)
    print("Address infos:", ai)
    addr = ai[0][-1]

    with open(KEY_PATH, 'rb') as f1:
        key = f1.read()
    with open(CERT_PATH, 'rb') as f2:
        cert = f2.read()
    s = ssl.wrap_socket(s, key=key, cert=cert)

    s.connect(addr)
    print('Connected to Server')
    temp = 100
    json_data = {'state':{'reported':{'Temperature': temp}}}
    send_data=json.dumps(json_data)

    s.write(b"POST /things/ESP32/shadow HTTP/1.1\r\n")
    s.write(b"Host: " + END_POINT + "\r\n")
    s.write(b"Content-Length: %d\r\n" % len(send_data))
    s.write(b"Connection: close\r\n")
    s.write(b"\r\n")
    s.write(send_data)
    print('Send Data to Server')

    recv_data = s.recv(4096)
    print(str(recv_data, 'utf8'))
    s.close()

if __name__ == '__main__':
    enable_esp32()
    send()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)