[PYTHON] [MQTT] I tried talking with the device using AWS IoT Core and Soracom Beam

Introduction

The reason for implementing this architecture is that there is already a mechanism to notify the device using SMS, but it is difficult to investigate because communication is not stable and services of other companies are used. There was a problem. Therefore, the aim is to stabilize it by making it manageable using MQTT.

Requirements

--Based on the message published from IoT Core, execute the process on the device side --Use Soracom Beam for security

Technology used

--AWS IoT Core (hereafter IoT Core) --SORACOM Beam (hereinafter Beam)

Contents

--Mainly about the source code (AWS SDK) on the device side --Notes on implementation details

Advance preparation

  1. IoT Core and Beam settings

First of all, set up IoT Core and Beam.

Please refer to the SORACOM guide as it is very easy to understand. If you follow the procedure, you will not make a mistake.

https://dev.soracom.io/jp/docs/aws_iot_guide_console/

When completed, you will be able to communicate with the device side via IoT Core.

  1. SIM settings Get the imsi from the SIM in the python code and use it as the topic name. To do this, you need to turn on "Meta data service settings".

Please refer to the following for the setting method https://dev.soracom.io/jp/start/metadata/

Implementation! !!

  1. Run the following python inside the IoT device
  2. Publish message from IoT Core test
  3. If it is output to the console or can be restarted, it is successful.

mqtt_sub.py


# -*- coding: utf-8 -*-
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import time
import json
import subprocess
import requests

SORACOM_METADATA_URL = 'http://metadata.soracom.io/v1/subscriber'

def get_imsi(self):
    """get IMSI from SORACOM API"""
    subscriber = json.loads(requests.get(SORACOM_METADATA_URL).text)
    return subscriber["imsi"]

#It will be executed when MQTT arrives
def customCallback(client, userdata, message):
    message = json.loads(message.payload)["message"]
    if message == "REBOOT":
        reboot = "sudo reboot"
        subprocess.call(reboot, shell=True)
    else:
        print(message)
        pass


def main():
    try:
        #The identifier of the client. Anything is fine this time.
        mqttClient = AWSIoTMQTTClient('aws_iot_sub')

        #Communication host settings. Setting the beam endpoint.
        mqttClient.configureEndpoint('beam.soracom.io', 1883)

        #This is the setting when you go offline.
        # configureOfflinePublishQueueing(queueSize, dropBehavior=DROP_NEWEST)
        # queueSize:1 or more...queue size is set to the argument value
        # queueSize: 0 ...queue invalid
        # queueSize: -1 ...Unlimited queue size
        # dropBehavior:Setting when queue becomes full DROP if not set_NEWEST
        mqttClient.configureOfflinePublishQueueing(0)

        #Execution frequency
        mqttClient.configureDrainingFrequency(2)  # Hz

        #client timeout time
        mqttClient.configureConnectDisconnectTimeout(10)  # sec

        #Timeout time for QoS 1
        mqttClient.configureMQTTOperationTimeout(5)  # sec

        #Connection with IoT Core
        #You can also set keepalive. The default is 600 seconds
        mqttClient.connect()

        imsi = get_imsi()

    except Exception as err:
        print(err)

    #If the radio wave is bad, subscribe will be an Exception and python will drop, so try/Loop with except
    #The reason why err of except is not output is because the message is not thrown by Exception of subcribe, so even if it is output, it will be empty.
    #The topic name should be imsi so that only the environment in which it is running can be subscribed.
    while True:
        try:
            mqttClient.subscribe(str(imsi), 1, customCallback)
            time.sleep(1)
        except Exception as err:
            pass

if __name__ == "__main__":
    main()

Summary

This time, I introduced only restarting, but it is possible to execute various processes by executing sh. The article posted on the 5th day of advent Calendar 2019, which this article has registered, was interesting, so I think it will be helpful. I wanna try...

I used the AWSIoTPython SDK, but I was able to communicate with Beam using paho as well. With this requirement, the merit of using the SDK is small, and I think that the SDK will be more useful when operating shadows instead of using IoT Core as a broker. However, since paho is running internally, we adopted the SDK that is specialized for AWS.

If you know if there is another good way, please let me know.

Recommended Posts

[MQTT] I tried talking with the device using AWS IoT Core and Soracom Beam
[Introduction to AWS] I tried porting the conversation app and playing with text2speech @ AWS ♪
I tried AWS Iot
I tried using AWS Chalice
I tried using the DS18B20 temperature sensor with Raspberry Pi
[AWS / Tello] I tried operating the drone with my voice Part2
I tried to unlock the entrance 2 lock sesame with a single push of the AWS IoT button
I tried using PyEZ and JSNAPy. Part 4: Automate ISP setup with PyEZ and JSNAPy
[AWS / Tello] I tried operating the drone with my voice Part1
I tried using the checkio API
I tried to express sadness and joy with the stable marriage problem.
I tried to convert datetime <-> string with tzinfo using strftime () and strptime ()
I tried to learn the angle from sin and cos with chainer
I tried using "Streamlit" which can do the Web only with Python
I tried to extract and illustrate the stage of the story using COTOHA
I tried updating Google Calendar with CSV appointments using Python and Google APIs
I tried to control the network bandwidth and delay with the tc command
I tried using Amazon SQS with django-celery
I tried using Selenium with Headless chrome
AWS IoT device life and death monitoring
I tried playing with the image with Pillow
I tried using the BigQuery Storage API
I tried to notify the update of "Hamelin" using "Beautiful Soup" and "IFTTT"
I tried Hello World with 64bit OS + C language without using the library
I tried to create an environment to check regularly using Selenium with AWS Fargate
The story of making soracom_exporter (I tried to monitor SORACOM Air with Prometheus)
I tried using PyEZ and JSNAPy. Part 1: Overview
I tried "smoothing" the image with Python + OpenCV
I tried using AWS Rekognition's Detect Labels API
I tried using scrapy for the first time
vprof --I tried using the profiler for Python
I tried web scraping using python and selenium
I tried "differentiating" the image with Python + OpenCV
I tried to save the data with discord
I tried using PyCaret at the fastest speed
I tried using the Google Cloud Vision API
I tried Jacobian and partial differential with python
I tried function synthesis and curry with python
I tried "binarizing" the image with Python + OpenCV
I tried using the Datetime module by Python
I tried connecting AWS Lambda with other services
I tried using the image filter of OpenCV
I tried DBM with Pylearn 2 using artificial data
I tried using the functional programming library toolz
I tried using a database (sqlite3) with kivy
I tried playing with the calculator on tkinter
I tried to notify the update of "Become a novelist" using "IFTTT" and "Become a novelist API"
I tried to score the syntax that was too humorous and humorous using the COTOHA API.
I tried to compare the processing speed with dplyr of R and pandas of Python
I tried to learn the sin function with chainer
I tried to read and save automatically with VOICEROID2 2
I tried to implement and learn DCGAN with PyTorch
I tried running the app on the IoT platform "Rimotte"
[AWS IoT] Register things in AWS IoT using the AWS IoT Python SDK
I tried Amazon Comprehend sentiment analysis with AWS CLI.
I tried to touch the CSV file with Python
I tried to solve the soma cube with python
[Linux] I tried using the genetic statistics software PLINK
I tried clustering ECG data using the K-Shape method
I tried to get an AMI using AWS Lambda
I tried to approximate the sin function using chainer