Skip to content
Permalink
3f773c09fb
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
50 lines (38 sloc) 1.38 KB
import paho.mqtt.client as mqtt
import json
from datetime import datetime
import time
# Function to extract battery percentage from OwnTracks data
def get_battery_percentage(data):
if 'batt' in data:
return data['batt']
else:
return None
# MQTT callback function for on_connect
def on_connect(client, userdata, flags, rc):
if rc == 0:
client.connected_flag = True
print("Connected successfully! Returned code:", rc)
else:
print("Bad connection. Returned code:", rc)
# MQTT callback function for on_message
def on_message(client, userdata, msg):
try:
data = json.loads(msg.payload.decode("utf8"))
current_time = datetime.now().strftime("%H:%M:%S")
battery_percentage = get_battery_percentage(data)
if battery_percentage is not None:
client.publish("project/battery/percentage", json.dumps([battery_percentage, str(current_time)]))
print("published battery percentage:", battery_percentage)
except Exception as e:
print("Error message:", e)
# MQTT client setup
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
# Connect to the MQTT broker
client.connect("broker.hivemq.com", 1883)
# Subscribe to the OwnTracks topic
client.subscribe("owntracks/HS/#")
# Loop to continuously process MQTT messages
client.loop_forever()