2020年8月29日 星期六

WiFi模組通訊實作Part2 – Ideaschain雲端平臺

WiFi模組通訊實作Part2 – Ideaschain雲端平臺

 範例說明

利用epy上的ADC量測Light感測器,epy透過UART介面與ESP01 WiFi模組連接。將資料傳送到https://iiot.ideaschain.com.tw/的雲端。

Ideaschain國產免費的雲端平臺,由財團法人資訊工業策進會數位服務創新研究所由開發。

 

發送資料格式:

POST /api/v1/DEVICE_KEY/telemetry HTTP/1.1

Content-Type: application/json

Content-Length: param_lenth

Host: iiot.ideaschain.com.tw

param_data

程式列表

"""

 ePy_ESP01_ideaschain.py

 

 EPY           ESP01

 -----------------

 3V3           VCC

 P8(UART1_TxD) RxD

 P9(UART1_RxD) TxD

 GND           GND

 

"""

 

from machine import KEY  #獲取按鍵KEY

from machine import ADC

from machine import PIN

from machine import UART

from machine import LED

import utime

 

SSID = "MYAP"            # 填入要連線的WiFi熱點名稱

PASSWORD = "19760106"    # Wi-Fi熱點密碼

HOST = "ideaschain.com.tw"       # 伺服器網址,不可動

PORT = 80

API_URL = "iiot.ideaschain.com.tw"   # 連線對象URL,不可動

DEVICE_KEY = " xxxxxxxxxxxxxxxxxxxx"  # 資料平台裝置的存取權限碼

key1 = "EPY_Light"

str1 = ""

DEBUG = True

ledR = None

 

"""

* Name: sendData

* Description: this Function regulates how the AT Commands will ge sent to the ESP8266.

*

* Params: command - the AT Command to send

*                 - timeout - the time to wait for a response

*                 - debug - print to Serial window?(true = yes, false = no)

*

* Returns: The response from the esp8266 (if there is a reponse)

"""

def sendData(command,timeout,debug):

  response = ""

  uar_1.write(command)

  utime.sleep_ms(timeout)

  response = uar_1.read() # 從串口讀取資料

  if(debug):

    #if the "debug" variable value is TRUE, print the response on the Serial monitor.

    cmd = response.decode('utf-8');

    print("received:",cmd) # 列印接收到的資料

  return response  #return the String response.

 

"""

* Name: InitWifiModule

* Description: this Function gives the commands that we need to send to the sendData() function to send it.

*

* Params: Nothing.

*

* Returns: Nothing (void).

"""

def InitWifiModule():

  print("connecting to wifi")

  sendData("AT\r\n",200,DEBUG)

 

  str1 = sendData("AT+RST\r\n",1000,False)

  if(DEBUG):

    print("received:",str1) # 列印接收到的資料

    # print("received:{}".format(str1)) # 列印接收到的資料

 

  sendData("AT+GMR\r\n",1000,DEBUG)

 

  CWJAP_CMD="AT+CWJAP=\"" + SSID + "\",\"" + PASSWORD + "\"\r\n"

  sendData(CWJAP_CMD,25000,DEBUG)

  utime.sleep_ms(3000)

 

  sendData("AT+CWMODE=1\r\n", 1500, DEBUG)  #set the ESP8266 WiFi mode to station mode.

  utime.sleep_ms(1000)

 

  sendData("AT+CIFSR\r\n", 1500, DEBUG)  #Show IP Address, and the MAC Address.

  utime.sleep_ms(1000)

 

# Start Function

if __name__ == '__main__':

  ledR = LED(LED.LED1)

  light = ADC(4)

  uar_1=UART(1,115200)

  key_c = KEY(KEY.KEYC)    #創建按鍵C

 

  InitWifiModule()

  print("--- Start ---")

 

  light_val=0

 

  try:

    while True:

      light_val = light.read()

 

      ledR.on()

      CIPSTART_CMD="AT+CIPSTART=\"TCP\",\"" + HOST + "\"," + str(PORT) + "\r\n"

      sendData(CIPSTART_CMD,15000,DEBUG)

 

      #  上傳訊息內容格式,其中key1為資料名稱(如溫度、濕度...)value1為資料內容(2866.5...)

      param_data = "{\r\n "+ key1 + ": " + str(light_val) +"\r\n}"

      param_lenth = str(len(param_data))    # 計算訊息的字串總長度

 

      # 定義發送至伺服器的訊息內容

      request_str = "POST /api/v1/" + DEVICE_KEY + "/telemetry HTTP/1.1\r\n" \

                  + "Content-Type: application/json\r\n" \

                  + "Content-Length: " + param_lenth + "\r\n" \

                  + "Host: " + API_URL + "\r\n\r\n" \

                  + param_data + "\r\n\r\n" \

                  + "Connection: close\r\n\r\n"

      request_lenth = str(len(request_str))    # 計算訊息的字串總長度

      if(DEBUG):

        print(request_str)            # 顯示此訊息內容進行debug

 

      CIPSEND_CMD="AT+CIPSEND=" + request_lenth + "\r\n"

      if(DEBUG):

        print(request_str);   # 顯示此訊息內容進行debug

        print(CIPSEND_CMD);  # 顯示此訊息內容進行debug

 

      data = sendData(CIPSEND_CMD, 1000, DEBUG)

      if 'ERROR' in data:   # 使用in運算子檢查

        print('find \"ERROR\"')

      if '>' in data:   # 使用in運算子檢查

        print('find \">\"')

      else:

        print('not find \">\"')

      # while (data.find(">")<0):

        # utime.sleep_ms(100)

        # if(uar_1.any()): # 當串口有可讀數據時

          # data = uar_1.read()

      sendData(request_str, 1000, DEBUG)

      ledR.off()

      utime.sleep_ms(5000)

 

      if key_c.value() == 0:      #如果按鍵C被按下

        break

 

  finally:

    pass

 

light.deinit()

uar_1.deinit()

key_c.deinit()

 

執行結果