Get Fitnesstracker Name from Device Alias in GB

This commit is contained in:
Oliver 2025-07-17 16:47:06 +00:00
parent 5ebd34f8ef
commit 3228f76200

23
main.py
View File

@ -19,8 +19,7 @@ class GadgetbridgeMQTTPublisher:
def __init__(self): def __init__(self):
self.setup_logging() self.setup_logging()
self.db_path = os.getenv("GADGETBRIDGE_DB_PATH", "/data/Gadgetbridge.db") self.db_path = os.getenv("GADGETBRIDGE_DB_PATH", "/data/Gadgetbridge.db")
raw_name = os.getenv("DEVICE_NAME", "fitness_tracker") self.device_name = self.get_device_alias()
self.device_name = re.sub(r"\W+", "_", raw_name).lower()
self.load_config() self.load_config()
self.mqtt_client = None self.mqtt_client = None
self.publish_interval = int(os.getenv("PUBLISH_INTERVAL_SECONDS", "300")) self.publish_interval = int(os.getenv("PUBLISH_INTERVAL_SECONDS", "300"))
@ -354,6 +353,26 @@ class GadgetbridgeMQTTPublisher:
except Exception as e: except Exception as e:
self.logger.error(f"Failed to connect to MQTT broker: {e}") self.logger.error(f"Failed to connect to MQTT broker: {e}")
def get_device_alias(self) -> str:
"""Fetch ALIAS from DEVICE table for device_name"""
if not os.path.exists(self.db_path):
self.logger.error(f"Database file not found: {self.db_path}")
return "fitness_tracker"
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("SELECT ALIAS FROM DEVICE LIMIT 1")
row = cursor.fetchone()
conn.close()
if row and row[0]:
# Sanitize alias for MQTT topics
return re.sub(r"\W+", "_", row[0]).lower()
else:
return "fitness_tracker"
except Exception as e:
self.logger.error(f"Error fetching device alias: {e}")
return "fitness_tracker"
# --- Main Entry Point --- # --- Main Entry Point ---
if __name__ == "__main__": if __name__ == "__main__":