Permalink
Cannot retrieve contributors at this time
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?
MQTT-SAPTS-4005/Battery_Pub.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
50 lines (38 sloc)
1.38 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |