(Failed attemped) How to get Maixduino connected to AWS IoT
Tags: maixduino, aws, iot, ssl
Published: 2020-12-22 10:26:41

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

## Steps

### AWS IoT Preparation

1. Create Resource
    - https://docs.aws.amazon.com/iot/latest/developerguide/create-iot-resources.html
1. Display MQTT message
    - https://docs.aws.amazon.com/iot/latest/developerguide/view-mqtt-messages.html

### Preparing Maixduino

1. Smoke test
    - Carry out the setup procedure
    - https://maixpy.sipeed.com/en/get_started/power_on.html
1. Upgrade firmware
    - ussl support was merged into master in 2020/1
        - https://github.com/sipeed/MaixPy/issues/105
    - Build master and flash
        - https://github.com/sipeed/MaixPy/blob/develop/build.md
        - In the middle of the procedure, enable the ussl module with the following command
            - $ python3 project.py menuconfig
1. Place a script to enable WiFi
    - https://github.com/sipeed/MaixPy_scripts/blob/master/network/network_esp32.py
1. Send MQTT message over SSL
    - ref. https://qiita.com/sat0ken/items/ac18b0d14e58e0eae124
    - (Caution) The signature of ussl.wrap_socket is different from the one of micropython official
        - Probably not compatible with root certificates (where is the source code?)
        - https://github.com/micropython/micropython/issues/2781
        - https://docs.micropython.org/en/latest/library/ussl.html
    - -> Run-time error
        - Is it possible without root certificate..?
            - https://docs.aws.amazon.com/iot/latest/developerguide/protocols.html

```python
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()
```