Live Location Tracking using Python - python

I am using an app called cedalo connect to get my phone's GPS data using an online mqtt server. I constantly get latitude and longitude information using this app.
I want to show it on a map using python. I wrote such a code but it kept giving me errors like (AttributeError: module 'folium' has no attribute 'MarkerCluster')
I honestly don't know what else to use.
Could you please tell me what I can do about it?
what I tried:
import json
import paho.mqtt.client as mqtt
import folium
import time
from folium.plugins import MarkerCluster
# Variable to hold the current latitude and longitude
latitude = 50.780036278929614
longitude = 6.10363592985153
# Callback function when a message is received
def on_message(client, userdata, message):
global latitude, longitude
# Convert the message payload from bytes to string
data = message.payload.decode()
# parse the json string
data = json.loads(data)
# Extract the latitude and longitude
if 'GPS' in data:
gps_data = data["GPS"]
latitude = gps_data["Latitude"]
longitude = gps_data["Longitude"]
# Create MQTT client
client = mqtt.Client()
# Attach callback function to the message event
client.on_message = on_message
# Connect to the MQTT broker
client.connect("broker.mqttdashboard.com", 1883)
# Subscribe to the desired topic
client.subscribe("gpsdata")
# Start the MQTT loop
client.loop_start()
# Initialize the map
# Initialize the map
m = folium.Map(location=[latitude, longitude], zoom_start=15)
mc = folium.MarkerCluster()
m.add_child(mc)
marker = None
while True:
# Check if the latitude and longitude have been updated
if latitude and longitude:
# Remove the previous marker
if marker:
mc.remove_child(marker)
# Update the marker on the map to the current location
marker = folium.Marker(location=[latitude, longitude])
mc.add_child(marker)
# Save the map
m.save("current_location.html")
# Wait for one second
time.sleep(1)
The result is an attribute error.

The MarkerCluster class is located in folium.plugins. So, instead of
mc = folium.MarkerCluster()
try
mc = MarkerCluster()
or
mc = folium.plugins.MarkerCluster()

Related

Getting position data from UBX protocol

I am working on a project which is use ublox .ubx protocol to getting position information. I'm using serial communication to connect my GPS module and getting position information to python sketch. I used Serial and pyubx2 libraries my sketch as follows,
from serial import Serial
from pyubx2 import UBXReader
stream = Serial('COM8', 38400)
while True:
ubr = UBXReader(stream)
(raw_data, parsed_data) = ubr.read()
print(parsed_data)
Then I have received information from GPS module as follows. It is continuously sending many of information in every second like as follows,
<UBX(NAV-SOL, iTOW=00:11:43, fTOW=-215069, week=0, gpsFix=0, gpsfixOK=0, diffSoln=0, wknSet=0, towSet=0, ecefX=637813700, ecefY=0, ecefZ=0, pAcc=649523840, ecefVX=0, ecefVY=0, ecefVZ=0, sAcc=2000, pDOP=99.99, reserved1=2, numSV=0, reserved2=215800)>
<UBX(NAV-PVT, iTOW=00:11:43, year=2015, month=10, day=18, hour=0, min=12, second=1, validDate=0, validTime=0, fullyResolved=0, validMag=0, tAcc=4294967295, nano=-215068, fixType=0, gnssFixOk=0, difSoln=0, psmState=0, headVehValid=0, carrSoln=0, confirmedAvai=0, confirmedDate=0, confirmedTime=0, numSV=0, lon=0.0, lat=0.0, height=0, hMSL=-17000, hAcc=4294967295, vAcc=3750027776, velN=0, velE=0, velD=0, gSpeed=0, headMot=0.0, sAcc=20000, headAcc=180.0, pDOP=99.99, invalidLlh=0, lastCorrectionAge=0, reserved0=2312952, headVeh=0.0, magDec=0.0, magAcc=0.0)>
I want to assign those position information (latitude, longitude, altitude etc.) into variables and hope to do some analysis part in further. So how can I derive positional information individually from this type of sentences.
Try something like this (press CTRL-C to terminate) ...
from serial import Serial
from pyubx2 import UBXReader
try:
stream = Serial('COM8', 38400)
while True:
ubr = UBXReader(stream)
(raw_data, parsed_data) = ubr.read()
# print(parsed_data)
if parsed_data.identity == "NAV-PVT":
lat, lon, alt = parsed_data.lat, parsed_data.lon, parsed_data.hMSL
print(f"lat = {lat}, lon = {lon}, alt = {alt/1000} m")
except KeyboardInterrupt:
print("Terminated by user")
For further assistance, refer to https://github.com/semuconsulting/pyubx2 (there are several example Python scripts in the /examples folder).

GPS NEO 6M V2 Raspberry pi 4 data missing

I am using gps neo 6m v2 and a raspberry pi to monitor vehicle health. I have also use obd to get the data of engine sensors, in this case I was facing problem on the gps which is data from the gps is missing for few minutes. If I started the travel and from one place to another, from the beginning until sometime I getting data and suddenly data is missing and return back normal. In the between data missing is the biggest issue for me. I could not find the solution why the data missing in the middle of the way i travel along. please give me a solution.
the python code used for get the GPS data from raspberry pi to influxdb and visualize in Grafana server.
from datetime import datetime
from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import SYNCHRONOUS
import serial
# Setup database
token = "<mytoken>"
org = "<myorg>"
bucket = "<mybucket>"
with InfluxDBClient(url="<influxurl>", token=token, org=org) as client:
write_api = client.write_api(write_options=SYNCHRONOUS)
# Setup dataload
json_dataload = []
ser = serial.Serial("/dev/ttyS0")
gpgga_info = "$GPGGA,"
GPGGA_buffer = 0
NMEA_buff = 0
def convert_to_degrees(raw_value):
decimal_value = raw_value / 100.00
degrees = int(decimal_value)
mm_mmmm = (decimal_value - int(decimal_value)) / 0.6
position = degrees + mm_mmmm
position = "%.4f" % position
return position
while True:
received_data = str(ser.readline()) # read NMEA string received
GPGGA_data_available = received_data.find(gpgga_info) # check for NMEA>
if (GPGGA_data_available > 0):
GPGGA_buffer = received_data.split("$GPGGA,", 1)[1] # store data com>
NMEA_buff = (GPGGA_buffer.split(','))
nmea_latitude = []
nmea_longitude = []
extract_latitude = NMEA_buff[1] # extract latitude from >
extract_longitude = NMEA_buff[3] # extract longitude from>
lat = float(extract_latitude)
lat = convert_to_degrees(lat)
longi = float(extract_longitude)
longi = convert_to_degrees(longi)
point = Point("latest GPS") \
.field("latitude", lat) \
.field("longitude", longi) \
.time(datetime.utcnow(), WritePrecision.NS)
json_dataload.append(point)
# Send our payload
write_api.write(bucket, org,json_dataload)

How can i create a live chart with the help of Live streaming data?

I'm receiving live streaming data from the kite every second, and now I want to create a Chart with the help of that data.
Any Chart can work, I don't need any specific chart type. but I don't understand how can I create a chart which is automatically changing every second.
I want that chart to change like the stock market chart changes every second.
I'm getting this type of values data in each second.
And This is my code-
from kiteconnect import KiteConnect
import time
from kiteconnect import KiteTicker
kws = KiteTicker(zerodha_api_key,acc_tkn)
tokens=[ 60702215, 60700167, 60701191]
# dict={9410818:'BANKNIFTY22MAR27000CE',9411074:'BANKNIFTY22MAR27000PE'}
def on_ticks(ws, ticks):
ticks = (ticks)
bid_price_1 = ticks[0]['depth']['buy'][0]['price']
ask_price_1 = ticks[1]['depth']['sell'][0]['price']
combination_1 = bid_price_1 - ask_price_1
print(combination_1)
def on_connect(ws, response):
ws.subscribe(tokens)
ws.set_mode(ws.MODE_FULL,tokens)
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.connect(threaded=True)
count=0
while True:
count+=1
if(count%2==0):
if kws.is_connected():
kws.set_mode(kws.MODE_FULL,tokens)
else:
if kws.is_connected():
kws.set_mode(kws.MODE_FULL,tokens)
time.sleep(1)

Ardupilot - Dronekit Setting the Current Location of the Vehicle

Hello everybody, hope you are all doing well.
I am doing in a project in which I receive GPS data (Longitude, and Latitude) from an Android device via an SQL server. What I am trying to do is to send this Longitude - Latitude data to my SITL vehicle in Ardupilot. I thought about using Dronekit Python API as such:
from dronekit import connect, VehicleMode
import time
import mysql.connector
import time
#--- Start the Software In The Loop (SITL)
import dronekit_sitl
#
sitl = dronekit_sitl.start_default() #(sitl.start)
#connection_string = sitl.connection_string()
mydb = mysql.connector.connect(
host="******",
user="******",
password="*****",
database="koordinat"
)
mycursor = mydb.cursor()
#--- Now that we have started the SITL and we have the connection string (basically the ip and udp port)...
print("Araca bağlanılıyor")
vehicle = connect('tcp:127.0.0.1:5762', wait_ready=False, baud = 115200)
vehicle.wait_ready(True, raise_exception=False)
#-- Read information from the autopilot:
#- Version and attributes
vehicle.wait_ready('autopilot_version')
print('Autopilot version: %s'%vehicle.version)
#- Does the firmware support the companion pc to set the attitude?
print('Supports set attitude from companion: %s'%vehicle.capabilities.set_attitude_target_local_ned)
vehicle.mode = VehicleMode("GUIDED")
vehicle.armed = True
while(True):
mycursor.execute("SELECT * FROM koordinat WHERE 1")
location = str(mycursor.fetchall())
location = location.split(",")
location[0] = location[0].replace("[", "")
location[0] = location[0].replace("(", "")
location[0] = location[0].replace("'", "")
location[1] = location[1].replace("[", "")
location[1] = location[1].replace(")", "")
location[1] = location[1].replace("'", "")
location[1] = location[1].replace(")", "")
# Converting the longitude and latitude to float, before assigning to the vehicle GPS data:
location[0] = float(location[0])
location[1] = float(location[1])
# Setting the location of the vehicle:
vehicle.location.global_frame.lat = location[0]
vehicle.location.global_frame.lon = location[1]
print('Konum:', str(vehicle.location.global_frame.lat)+str(","), str(vehicle.location.global_frame.lon)+str(","), str(vehicle.location.global_frame.alt))
#- When did we receive the last heartbeat
print('Son bilgi gelişi: %s'%vehicle.last_heartbeat)
time.sleep(1)
However, when I check from the SITL and Mission Planner (also from the print statement from my code) the location does not change; the simulator simply ignores those commands sent by the Dronekit. Is there a working method to accomplish what I am trying to do? I tried to change the sim_vehicle.py script which I use to start the simulation. But I was only able to change the starting/home location of the vehicle. I was not able to change the current location of the vehicle on SITL and Mission Planner.
This is incorrect. You're modifying the attribute of the vehicle object that's connected to the SITL, not sending any commands to the actual autopilot.
vehicle.location.global_frame.lat = location[0]
vehicle.location.global_frame.lon = location[1]
What you want to do is set the mode to GUIDED and use the simple_goto function in dronekit to make the drone move to lat/lon/alt coordinates.
Otherwise, you can also send this MAVLink command SET_POSITION_TARGET_GLOBAL_INT to guide it.

Rotate cube about fixed axis

So I have a code that takes in real time angle information from an IMU sensor in Raspberry Pi, which is transmitted to my computer using mqtt broker. The angle is based on the orientation of the IMU during upright position (i.e. fixed coordinate system). Now I want to animate the IMU by taking the difference between two corresponding sensor readings which would indicate the amount of rotation required in that particular axis. However, the animation I get is not displaying the orientation correctly. My question is, in the
obj.rotate(angle=a, axis=vec(x,y,z),origin=vector(x0,y0,z0))
function of vpython, how do I say such that the rotation is about the fixed coordinate system, instead of rotating around the IMU's axis? My code is below:
from vpython import *
import math
import paho.mqtt.client as mqtt
import time
scene.title = "VPython: Draw a rotating cube"
scene.range = 2
scene.autocenter = True
def on_connect(client, userdata, flags, rc):
global callback_on_connect
print("Connected with result code "+str(rc))
# Subscribing in on_connect() - if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("CoreElectronics/test")#these two are topics; thus the client here listens to these two topics
client.subscribe("CoreElectronics/topic")
callback_on_connect=1
# The callback for when a PUBLISH message is received from the server.
# ONLY WORKS IF YOU HAVE A MESSAGE FROM RASPBERRY PI SINCE IT IS A CALLBACK!
def on_message(client, userdata, msg):
global yaw
global pitch
global roll
global callback_on_message
callback_on_message=1
#print(msg.topic+" "+str(msg.payload))
#print(float(msg.payload))
#print(3)
f=msg.payload
angles = [float(i) for i in f.split()]
#print(3)
#type(angles)
yaw=angles[0]
pitch=angles[1]
roll=angles[2]
print(angles)
#x = [float(i) for i in f.split()]
#print(x[0])
#print(x[1])
# Do something else
print("Drag with right mousebutton to rotate view.")
print("Drag up+down with middle mousebutton to zoom.")
cube = box(pos=vec(0,0,0),length=1,height=0.1,width=1) # using defaults, see http://www.vpython.org/contents/docs/defaults.html
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
print("Connecting to server...")
client.connect("mqtt.eclipse.org", 1883, 60)
print("Reached loop function...")
client.loop_start()
yaw=''
pitch=''
roll=''
yaw2=0
pitch2=0
roll2=0
#callback_on_connect=0
callback_on_message=0;
while callback_on_message==0:
print("waiting for callback as a result of successful message receive", callback_on_message)
#now we are connected, can start taking in data
while True: # Animation-loop
try:
#print("animating")
#arrow(pos=vec(0,0,0),axis=vec(1,0,0))
#arrow(pos=vec(0,0,0),axis=vec(0,1,0))
#arrow(pos=vec(0,0,0),axis=vec(0,0,1))
cube.rotate(angle=radians(yaw-yaw2), axis=vec(1,0,0),origin=vector(0,0,0))
cube.rotate(angle=radians(pitch-pitch2), axis=vec(0,1,0),origin=vector(0,0,0))
cube.rotate(angle=radians(roll-roll2), axis=vec(0,0,1),origin=vector(0,0,0))
yaw2=yaw
pitch2=pitch
roll2=roll
except KeyboardInterrupt:
client.loop_stop()
#cube.rotate( angle=yaw, axis=vec(1,0,0) )
#cube.rotate( angle=pitch, axis=vec(0,1,0) )
#cube.rotate( angle=roll, axis=vec(0,0,1) )

Categories