MQTT protocol sends GPS coordinates to the server

MQTT protocol sends GPS coordinates to the server

1. Configure GPS
Insert picture description here
Personally feel that USB GPS is better. For those students who feel difficult to find, I still have a Taobao link . The seller didn't pay for it, just for the convenience of the students.
The first step is to buy it and follow the above picture to connect it. I used four DuPont cables:
USB TXD connects to GPS module RXD, USB RXD connects to GPS module TXD, USB GND connects to GPS module GND, USB Connect the VCC of the GPS module to the VCC. After connecting, put the GPS antenna outside the window, otherwise there will be no signal; the USB is plugged into the Raspberry Pi.

The second part is to use the Raspberry Pi to read the GPS signal.
First look at this USB, command line input:

ls -l /dev/tty*

Picture Picture Picture Picture Picture Picture Picture Picture Picture Picture Picture Picture

Install minicom

sudo apt-get install minicom

After installation, use the minicom command to get the data on the serial port

minicom -b 9600 -o -D /dev/ttyUSB0

If it goes well, the following data will appear:

Picture Picture Picture Picture Picture Picture Picture Picture Picture Picture Picture Picture

The third part uses Python to read GPS data
in real time and input them in the terminal one by one

mkdir GPS
cd GPS
touch GPS_test.py
gedit GPS_test.py

Paste the following code in

import serial #导入serial模块

ser = serial.Serial("/dev/ttyUSB0",9600)#打开串口,存放到ser中,/dev/ttyUSB0是端口名,9600是波特率

while True:
    line = str(str(ser.readline())[2:])  # readline()是用于读取整行
    # 这里如果从头取的话,就会出现b‘,所以要从第三个字符进行读取
    if line.startswith('$GPGGA'):
        line = str(line).split(',')  # 将line以“,”为分隔符
        Longitude = float(line[4][:3]) + float(line[4][3:])/60
        # 读取第5个字符串信息,从0-2为经度,再加上后面的一串除60将分转化为度
        Latitude = float(line[2][:2]) + float(line[2][2:])/60
        # 纬度同理
        print("经度:",Longitude)
        print("维度:",Latitude)

Output result:

Insert picture description here

2. Configure MQTT
Next, configure MQTT. MQTT friends can go to Baidu Encyclopedia to see. A more vivid example of MQTT topics and messages is Weibo. If you follow CCTV News, the news sent by CCTV News will be pushed to you; if CCTV News also follows you, then you are following each other, and the messages you send will also be pushed to CCTV News.
Let's take a look at how to use python to send and receive messages using the MQTT protocol:
the package that needs to be used is paho-mqtt and
input in the Raspberry Pi terminal

pip install paho-mqtt

To install paho-mqtt

Type in the terminal

mkdir MQTT
cd MQTT
touch subscriber.py
gedit subscriber.py

Paste the code below

# subscriber.py
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    # 订阅,需要放在 on_connect 里
    # 如果与 broker 失去连接后重连,仍然会继续订阅 raspberry/topic 主题
    client.subscribe("raspberry/topic")

# 回调函数,当收到消息时,触发该函数
def on_message(client, userdata, msg):
    print(f"{msg.topic} {msg.payload}")
    
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

# 设置遗嘱消息,当树莓派断电,或者网络出现异常中断时,发送遗嘱消息给其他客户端
client.will_set('raspberry/status', "OFF")

# 创建连接,三个参数分别为 broker 地址,broker 端口号,保活时间
client.connect("broker.emqx.io", 1883, 60)

# 设置网络循环堵塞,在调用 disconnect() 或程序崩溃前,不会主动结束程序
client.loop_forever()

Operation result:
Picture Picture Picture Picture Picture Picture Picture Picture Picture Picture
code 0 means the connection is successful, other numbers are incorrect.

Go to the MQTTX official website to download the MQTTX client to raspberry/topicsend a message to the topic and test whether it can be received.

After downloading and installing, input according to the following figure:
Client ID is random.
Insert picture description here

Then click Connect in the upper right corner:
Insert picture description here
Insert picture description here
At this time, go back to the Raspberry Pi terminal and run

python3 subscriber.py

Then use the client to send a message and observe whether the terminal displays the message just released. If successful, it should look like this:

Insert picture description here

Let’s try sending a message with the Raspberry Pi: type
in the terminal

cd MQTT
touch publisher.py
gedit publisher.py

Paste the code below

import paho.mqtt.client as mqtt
import time

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    
client = mqtt.Client()
client.on_connect = on_connect
client.connect("broker.emqx.io", 1883, 60)

# 每间隔 2 秒钟向 raspberry/topic 发送一个消息,连续发送 10 次
for i in range(10):
    # 四个参数分别为:主题,发送内容,QoS, 是否保留消息
    client.publish('raspberry/topic', payload=i, qos=0, retain=False)
    print(f"send {i} to raspberry/topic")
    time.sleep(2)

client.loop_forever()

run

python3 publisher.py

Open another terminal and enter the MQTT folder

python3 publisher.py

Result: If
Insert picture description here
you want to view with the client
Insert picture description here
Insert picture description here
, you can see it after clicking Confirm
Insert picture description here

3. Use the MQTT protocol to send GPS to the server
Now generally use the json format to transmit data. The following code simply encapsulates the GPS coordinates and sends it to the server.

import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import serial  # 导入serial模块
import json
import time

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
start_time = time.time()
flag = 17
#jing = 105.753739
#wei = 37.474912
GPIO.setup(flag, GPIO.IN)
# GPIO.add_event_detect(flag, GPIO.RISING)

ser = serial.Serial("/dev/ttyUSB0", 9600)


def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    # 订阅,需要放在 on_connect 里
    # 如果与 broker 失去连接后重连,仍然会继续订阅 raspberry/topic 主题
    client.subscribe("raspberry/topic")


def on_message(client, userdata, msg):
    # print(f"{msg.topic} {msg.payload}")
    print("主题:" + msg.topic + " 消息:" + str(msg.payload.decode('utf-8')))
    print(f"receive message from raspberry/topic")


def on_subscribe(client, userdata, mid, granted_qos):
    print("On Subscribed: qos = %d" % granted_qos)


start_time = time.time()
client = mqtt.Client()
client.on_connect = on_connect
client.connect("broker.emqx.io", 1883, 60)
#client.connect("broker.emqx.io", 1883, 60)
client.on_message = on_message
client.will_set('raspberry/status', "OFF")

while True:

    client.on_message = on_message
    client.loop_start()
    line = str(str(ser.readline())[2:])  # readline()是用于读取整行
    # print(line)
    # 这里如果从头取的话,就会出现b‘,所以要从第三个字符进行读取

    if line.startswith('$GPGGA'):
        # 我这里用的GPGGA,有的是GNGGA
        # print('接收的数据:' + str(line))
        line = str(line).split(',')  # 将line以“,”为分隔符
        jing = float(line[4][:3]) + float(line[4][3:]) / 60
        # 读取第5个字符串信息,从0-2为经度,即经度为116,再加上后面的一串除60将分转化为度
        wei = float(line[2][:2]) + float(line[2][2:]) / 60
        # 纬度同理
        # print(jing)
        data1 = {
    
    
            "type": 1,  # 1表示轨迹
            "data": {
    
    
                "latitude": (wei),
                # 纬度
                "longitude": (jing)
                # 经度
            }
        }
        param1 = json.dumps(data1)
        client.publish("raspberry/topic", payload=param1, qos=0)
        print(f"send message to raspberry/topic")
        time.sleep(4)

    if GPIO.input(flag) == GPIO.LOW:
        data2 = {
    
    

            "type": 2,  # 2表示作业情况
            "data": {
    
    
                "worktime": ((time.time() - start_time) / 3600),  # 表示作业3小时
                "working_area": ((time.time() - start_time) * 1.12 * 6 * 0.0015)
                # 表示作业面积亩
            }
        }
        param2 = json.dumps(data2)
        # print("主题:"+msg.topic+" 消息:"+str(msg.payload.decode('utf-8')))

        print(f"data2")
        client.publish("raspberry/topic", payload=param2, qos=0)
        while True:
            print(f"OFF")
            time.sleep(10)
            
GPIO.cleanup()
client.loop_forever()

operation result:
Insert picture description here

Insert picture description here
The client received the message.
This time I will share my experience here. If there is anything wrong, you are welcome to correct me.

Guess you like

Origin blog.csdn.net/qq_38129331/article/details/108679889