主处理器:树莓派4B
服务器:阿里云轻量级服务器
MQTT代理服务器:
apollo 具体搭建链接:https://blog.csdn.net/ddxxii/article/details/80890293?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522158757431019725211921004%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=158757431019725211921004&biz_id=0&utm_source=distribute.pc_search_result.none-task-blog-2allfirst_rank_v2~rank_v25-1
使用模块:微雪电子SIM7020C
这款为NB-IoT模块,但官方文档和微雪示例十分不友好,踩了很多坑
mqtt-apollo操作界面:Eclipse paho
具体AT指令
以上为微雪示例,在我的案例中,需要更改第二条,第四条
AT+CMQCON=0,3,“myclient”,6000,0,0,“admin”,“password” 需要加入admin和password,不加的话无法连接。
AT+CMQPUB=0,“test”,0,0,0,3,“111”
这一条需要注意字符长度和前面设置的长度要一致才能发送,官方文档有说明
在编程时,可以先判断数据长度,之后再发送,这个可以实现数据的连续发送。
具体程序如下:
import struct, os
import serial
import time
import re
import sys
longitude = "35.923212"
a = len(longitude)
print(a)
ser = serial.Serial("/dev/ttyUSB0",115200,timeout = 1)
def reboot():
print("Waiting for module\n")
time.sleep(1)
comdata = ""
ser.write(("AT\r\n").encode('utf-8'))
while (comdata.find("OK")== -1):
time.sleep(0.1)
while (ser.inWaiting()>0):
comdata = ser.read(ser.inWaiting())
comdata = comdata.decode("ascii")
comdata = comdata.strip()
print(comdata)
if (comdata.find("ERROR")==-1):
continue
print("Sim7020c Start Succeed! \n")
return
def connect_mqtt():
print("connect new MQTT")
time.sleep(1)
comdata = ""
ser.write("AT+CMQDISCON=0\r\n".encode('utf-8'))
time.sleep(1)
ser.write('AT+CMQNEW="182.92.56.252","61613",12000,100\r\n'.encode('utf-8'))
while (comdata.find("OK")==-1):
time.sleep(0.1)
while (ser.inWaiting()>0):
comdata = ser.read(ser.inWaiting())
comdata = comdata.decode("ascii")
comdata = comdata.strip()
print(comdata)
def send_mqtt():
comdata = ""
ser.write('AT+CMQCON=0,3,"myclient",6000,0,0,"admin","password"\r\n'.encode('utf-8'))
while (comdata.find("OK")==-1):
time.sleep(0.1)
while (ser.inWaiting()>0):
comdata = ser.read(ser.inWaiting())
comdata = comdata.decode("ascii")
comdata = comdata.strip()
print(comdata)
def send_topic():
comdata = ""
ser.write('AT+CMQPUB=0,"test",1,0,0,"{}","{}"\r\n'.format(a,longitude).encode('utf-8'))
time.sleep(1)
while (comdata.find("OK")==-1):
time.sleep(0.1)
while (ser.inWaiting()>0):
comdata = ser.read(ser.inWaiting())
comdata = comdata.decode("ascii")
comdata = comdata.strip()
print(comdata)
reboot()
connect_mqtt()
time.sleep(0.5)
send_mqtt()
time.sleep(0.5)
send_topic()
至此,使用树莓派4B连接NB-IoT模块(SIM7020C)与MQTT服务器通信实现数据上传云端全部完成。
波特率在变,要改波特率!