228 lines
6.1 KiB
Python
228 lines
6.1 KiB
Python
#!/usr/bin/env python3
|
|
|
|
"""
|
|
Gadgetbridge MQTT Setup Script for Termux
|
|
Configures MQTT connection and creates autostart script
|
|
"""
|
|
|
|
import os
|
|
import json
|
|
import sys
|
|
|
|
CONFIG_DIR = os.path.expanduser("~/.config/gadgetbridge_mqtt")
|
|
CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")
|
|
SCRIPTS_DIR = os.path.expanduser("~/scripts")
|
|
BOOT_DIR = os.path.expanduser("~/.termux/boot")
|
|
|
|
DEFAULT_EXPORT_DIR = "/storage/emulated/0/Documents/GB_Export"
|
|
DEFAULT_INTERVAL = 300
|
|
|
|
|
|
def print_banner():
|
|
print("\n" + "=" * 50)
|
|
print(" Gadgetbridge MQTT Setup for Termux")
|
|
print("=" * 50 + "\n")
|
|
|
|
|
|
def get_input(prompt, default=None, required=True):
|
|
"""Get user input with optional default value"""
|
|
if default:
|
|
prompt = f"{prompt} [{default}]: "
|
|
else:
|
|
prompt = f"{prompt}: "
|
|
|
|
value = input(prompt).strip()
|
|
|
|
if not value and default:
|
|
return default
|
|
if not value and required:
|
|
print("This field is required!")
|
|
return get_input(prompt.replace(f" [{default}]", "").replace(": ", ""), default, required)
|
|
|
|
return value
|
|
|
|
|
|
def setup_mqtt():
|
|
"""Configure MQTT settings"""
|
|
print("=== MQTT Configuration ===\n")
|
|
|
|
config = {}
|
|
|
|
config["mqtt_broker"] = get_input("MQTT Broker IP/hostname")
|
|
config["mqtt_port"] = int(get_input("MQTT Port", "1883"))
|
|
config["mqtt_username"] = get_input("MQTT Username (leave empty if none)", "", required=False)
|
|
config["mqtt_password"] = get_input("MQTT Password (leave empty if none)", "", required=False)
|
|
|
|
print("\n=== Gadgetbridge Settings ===\n")
|
|
|
|
config["export_dir"] = get_input("Gadgetbridge Export Directory", DEFAULT_EXPORT_DIR)
|
|
config["publish_interval"] = int(get_input("Publish Interval (seconds)", str(DEFAULT_INTERVAL)))
|
|
|
|
return config
|
|
|
|
|
|
def save_config(config):
|
|
"""Save configuration to file"""
|
|
os.makedirs(CONFIG_DIR, exist_ok=True)
|
|
|
|
with open(CONFIG_FILE, "w") as f:
|
|
json.dump(config, f, indent=2)
|
|
|
|
print(f"\n✓ Config saved to: {CONFIG_FILE}")
|
|
|
|
|
|
def setup_directories():
|
|
"""Create necessary directories"""
|
|
os.makedirs(SCRIPTS_DIR, exist_ok=True)
|
|
os.makedirs(BOOT_DIR, exist_ok=True)
|
|
print("✓ Directories created")
|
|
|
|
|
|
def download_main_script():
|
|
"""Download or copy main.py to scripts directory"""
|
|
main_script = os.path.join(SCRIPTS_DIR, "gadgetbridge_mqtt.py")
|
|
|
|
# Check if we're running from the repo
|
|
script_dir = os.path.dirname(os.path.abspath(__file__))
|
|
local_main = os.path.join(script_dir, "main.py")
|
|
|
|
if os.path.exists(local_main):
|
|
# Copy from local
|
|
with open(local_main, "r") as src:
|
|
content = src.read()
|
|
with open(main_script, "w") as dst:
|
|
dst.write(content)
|
|
print(f"✓ Copied main script to: {main_script}")
|
|
else:
|
|
# Download from repo
|
|
try:
|
|
import urllib.request
|
|
url = "https://git.olli.info/Oliver/GadgetbridgeMqtt/raw/branch/main/main.py"
|
|
urllib.request.urlretrieve(url, main_script)
|
|
print(f"✓ Downloaded main script to: {main_script}")
|
|
except Exception as e:
|
|
print(f"✗ Failed to download main script: {e}")
|
|
print(" Please manually copy main.py to ~/scripts/gadgetbridge_mqtt.py")
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
def create_autostart():
|
|
"""Create Termux:Boot autostart script"""
|
|
boot_script = os.path.join(BOOT_DIR, "start_gb_mqtt")
|
|
|
|
content = """#!/data/data/com.termux/files/usr/bin/sh
|
|
# Gadgetbridge MQTT Autostart Script
|
|
|
|
# Prevent device from sleeping
|
|
termux-wake-lock
|
|
|
|
# Wait for system to fully boot
|
|
sleep 30
|
|
|
|
# Start the MQTT publisher in background
|
|
cd ~
|
|
python ~/scripts/gadgetbridge_mqtt.py >> ~/gb_mqtt.log 2>&1 &
|
|
"""
|
|
|
|
with open(boot_script, "w") as f:
|
|
f.write(content)
|
|
|
|
os.chmod(boot_script, 0o755)
|
|
print(f"✓ Autostart script created: {boot_script}")
|
|
|
|
|
|
def install_dependencies():
|
|
"""Install required Python packages"""
|
|
print("\n=== Installing Dependencies ===\n")
|
|
|
|
try:
|
|
os.system("pip install paho-mqtt")
|
|
print("✓ paho-mqtt installed")
|
|
except Exception as e:
|
|
print(f"✗ Failed to install paho-mqtt: {e}")
|
|
print(" Run manually: pip install paho-mqtt")
|
|
|
|
|
|
def print_gadgetbridge_instructions(export_dir):
|
|
"""Print Gadgetbridge configuration instructions"""
|
|
print("\n" + "=" * 50)
|
|
print(" Gadgetbridge Configuration")
|
|
print("=" * 50)
|
|
print(f"""
|
|
1. Open Gadgetbridge app
|
|
|
|
2. Go to Settings → Auto Export
|
|
- Enable "Auto Export"
|
|
- Set Location to: {export_dir}
|
|
- Set interval as desired (or leave for manual trigger)
|
|
|
|
3. The script will automatically trigger:
|
|
- ACTIVITY_SYNC (fetch data from band)
|
|
- TRIGGER_EXPORT (export database)
|
|
|
|
4. Grant Termux permissions:
|
|
- Run: termux-setup-storage
|
|
- Allow storage access when prompted
|
|
""")
|
|
|
|
|
|
def print_final_instructions():
|
|
"""Print final setup instructions"""
|
|
print("\n" + "=" * 50)
|
|
print(" Setup Complete!")
|
|
print("=" * 50)
|
|
print("""
|
|
To start manually:
|
|
python ~/scripts/gadgetbridge_mqtt.py
|
|
|
|
To view logs:
|
|
tail -f ~/gb_mqtt.log
|
|
|
|
The script will auto-start on boot via Termux:Boot.
|
|
|
|
Make sure to:
|
|
1. Open Termux:Boot app once to enable autostart
|
|
2. Configure Gadgetbridge export location (see above)
|
|
3. Reboot phone to test autostart
|
|
""")
|
|
|
|
|
|
def main():
|
|
print_banner()
|
|
|
|
# Check if config exists
|
|
if os.path.exists(CONFIG_FILE):
|
|
print(f"Existing config found: {CONFIG_FILE}")
|
|
overwrite = input("Overwrite? (y/N): ").strip().lower()
|
|
if overwrite != "y":
|
|
print("Setup cancelled.")
|
|
sys.exit(0)
|
|
|
|
# Setup MQTT
|
|
config = setup_mqtt()
|
|
|
|
# Save config
|
|
save_config(config)
|
|
|
|
# Setup directories
|
|
setup_directories()
|
|
|
|
# Install dependencies
|
|
install_dependencies()
|
|
|
|
# Download/copy main script
|
|
download_main_script()
|
|
|
|
# Create autostart
|
|
create_autostart()
|
|
|
|
# Print instructions
|
|
print_gadgetbridge_instructions(config["export_dir"])
|
|
print_final_instructions()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|