#!/usr/bin/env python

#Communicate with end devices via LoRa.
#Communicate with server via MQTT(hbmqtt) and HTTP POST.
#Save data in the sqlite database.
#Parse JSON from MQTT and LoRa protocol.

#Communication module: LoRa.
#Communication method with device via LoRa.
#Uart port drive LoRa module.
#Parse JSON between device and gateway via LoRa channel.
#LoRa module: E32-TTL-100
#Pin specification:
#M0    <--> GPIO(OUT)     #mode setting  connct to GND is OK!(Low)
#M1    <--> GPIO(OUT)     #mode setting  connct to GND is OK!(Low)
#RXD   <--> 8(TXD)        #ttyS0
#TXD   <--> 10(RXD)       #ttyS0
#AUX   <--> GPIO/INT(IN)  #module status detecting
#VCC
#GND

#You need to install pyserial manually, install command is below:
#pip install pyserial

import serial
import time
import json
#ser  = serial.Serial("/dev/ttyS0", 9600)
ser  = serial.Serial("/dev/ttyS0", 9600, timeout=0.2)
def main():
    while True:
        #Waiting for LoRa module message from uart port.
        count = ser.inWaiting()
        if count != 0:
            recv = pyserial_test.readline() #readline() need to set timeout, otherwise results block
            ser.flushInput()
            print(recv)
            json_lora = json.loads(recv)
            #Parse JSON
            if json_lora.get("ID") == 1 : #Device ID-1 existed in gateway database
              response = '{"ID":1, "CMD":Online, "TYPE":"Light", "VALUE":"On"}'
              ser.write(response)
            else:
              print('init_device')
              #init_device()  #Create sqlite table for device 1.
        time.sleep(0.1)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        if pyserial_test != None:
            pyserial_test.close()


@@ -1040,29 +1040,19 @@
  recv = 
-py
 ser
-ial_test
 .readlin
@@ -1204,71 +1204,287 @@
 ads(
-recv)%0A            #Parse JSON%0A            if json_lora.get(%22ID%22
+'%7B%22ID%22:%221%22, %22CMD%22:%22Online%22, %22TYPE%22:%22N%22, %22VALUE%22:%22N%22%7D')%0A            #Parse JSON%0A            #print(json_lora.get(%22ID%22))%0A            #print(json_lora%5B%22ID%22%5D)%0A            #if json_lora.get(%22ID%22) == '1' : #Device ID-1 existed in gateway database%0A            if int(json_lora.get(%22ID%22)
 ) ==
@@ -1565,17 +1565,19 @@
 ID%22:
-1
+%221%22
 , %22CMD%22:
 Onli
@@ -1572,22 +1572,24 @@
 , %22CMD%22:
+%22
 Online
+%22
 , %22TYPE%22
@@ -1882,29 +1882,19 @@
      if 
-py
 ser
-ial_test
  != None
@@ -1911,21 +1911,11 @@
     
-py
 ser
-ial_test
 .clo
@@ -1919,9 +1919,8 @@
 close()%0A
-%0A

Update main.py