시작은 미약하였으나 , 그 끝은 창대하리라

[Python] MQTT를 이용한 GPS 값 전송 (raspberry pi 이용) 본문

프로그래밍/MQTT

[Python] MQTT를 이용한 GPS 값 전송 (raspberry pi 이용)

애플파ol 2022. 9. 5. 17:45

들어가기전에 앞서  - >  인공위성이 잡혀야하고 좌표값을 계산하는데에 맑은날 야외에서 30분정도의 시간이 필요합니다.(라즈베리파이 리부트하지마세요..)

(이것 때문에...고생했던...으아니...)

(내가 예전에 어디서 들은건데 gps값 찾을려면 최소 3개 이상의 인공위성이 잡혀야한다고...)

 

1. Publisher Code

import serial,time,pynmea2
import paho.mqtt.client as mqtt
import json

port = '/dev/ttyACM0'
baud = 9600
ID="MFBE29"


serialPort = serial.Serial(port, baudrate = baud, timeout = 0.5)

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("connected OK")
    else:
        print("Bad connection Returned code=", rc)


def on_disconnect(client, userdata, flags, rc=0):
    print(str(rc))


def on_publish(client, userdata, mid):
    print("In on_pub callback mid= ", mid)


client = mqtt.Client()

client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_publish = on_publish
   
client.connect('111.111.111.119', 20518)   





while True:
    
    str = ''
    try:
        str = serialPort.readline().decode().strip()
    except Exception as e:
        print(e)
    #print(str)
    
    if str.find('GGA') > 0:
        try:
            msg = pynmea2.parse(str)
            Lat=round(msg.latitude,6)
            Lon=round(msg.longitude,6)
            Alt=msg.altitude
            Sats=msg.num_sats
            
            print('Lat:',round(msg.latitude,6),'Lon:',round(msg.longitude,6),'Alt:',msg.altitude,'Sats:',msg.num_sats)
            
            data=ID+" "+"%.6f "%Lat+"%.6f " %Lon  +"%C "%Alt+"%f "%Sats
            
            client.publish('gps', data,1)
        except Exception as e:
            print(e)
    time.sleep(0.2)
    
client.disconnect()

port번호를 확인 후 입력해주고 이렇게 코드를 짜면된다.

 

Lat =위도

Lon =경도

Alt =고도

Sats = gps값 산출하는데 잡은 위성수.

 

 

 

2. Subscriber Code

 

# 자이로 수신 코드


import paho.mqtt.client as mqtt
import psycopg2 as db  # DB용 모듈
from datetime import datetime   # 시간 함수
import time


def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("connected OK")
    else:
        print("Bad connection Returned code=", rc)

def on_disconnect(client, userdata, flags, rc=0):
    print(str(rc))

def on_subscribe(client, userdata, mid, granted_qos):
    print("subscribed: " + str(mid) + " " + str(granted_qos))

def on_message(client, userdata, msg):
    print(str(msg.payload.decode("utf-8")))



# 새로운 클라이언트 생성
client = mqtt.Client()

# 콜백 함수 설정 on_connect(브로커에 접속), on_disconnect(브로커에 접속중료), on_subscribe(topic 구독),
# on_message(발행된 메세지가 들어왔을 때)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_subscribe = on_subscribe
client.on_message = on_message

# address : localhost, port:20518 에 연결
client.connect('localhost', 20518)

client.subscribe('gps', 1)
    
#print(data)
client.loop_forever()

아래와 같이 값이 도착하는것을 알 수 있다.

 

만약 gps 출력값이 안나오고 바이너리 형태로 나온다면 nmae모드로 바꿔서 해야한다.

아래링크 참고.

https://raspberrypi.stackexchange.com/questions/137318/reading-data-from-gps-module-using-python-on-raspberry-pi

 

Reading data from GPS module using Python on Raspberry PI

I am using a NEO-8M Satellite Positioning Module on a Raspberry PI. I am trying to read data off the device using python. I am new to the Raspberry PI and Python. I can read data from the NEO-8M GPS

raspberrypi.stackexchange.com

 

 

 

코드가 이해가 안간다면 아래의 링크를 참고하면 자세히 쓰여있다 (DB저장법도)

자이로 센서 전송 코드-> https://put-idea.tistory.com/43?category=1010122

 

[Python] MQTT를 이용한 자이로센서 값 전송 (raspberry pi 이용)

(들어가기전에-> 1. 자이로센서는 MPU6050 사용하였습니다 ) (한국인이 좋아하는 결론부터 말하기) 자이로센서 값(데이터)를 전송하는 코드. ''' Read Gyro and Accelerometer by Interfacing Raspberry Pi with M..

put-idea.tistory.com

이미지 전송 코드 ->https://put-idea.tistory.com/46?category=1010122

 

 

Comments