#!/usr/bin/python3

###################################################
# ArtiLED Uptime Tool 1.00 (20-07-2026)           #
# Written by: Michel van Osenbruggen              #
# Copyright 2026 ArtiLED B.V. All Rights Reserved #
###################################################

#################################################
# Shows the LED controller's uptime next to    #
# the system's own, via ArtiNET Get Uptime     #
# (0x06). The comparison tells whether the     #
# controller and the Pi last booted together   #
# (shared power event) or independently.       #
#################################################

import re
import sys
import artiled

#Create Controller Object
name    = 'Local'
node    = '127.0.0.1'
port    = 1080
timeout = 2


def human(seconds):
    seconds = int(seconds)
    days, rest = divmod(seconds, 86400)
    hours, rest = divmod(rest, 3600)
    minutes, secs = divmod(rest, 60)
    parts = []
    if days:
        parts.append(str(days) + ' day' + ('s' if days != 1 else ''))
    if hours:
        parts.append(str(hours) + ' hour' + ('s' if hours != 1 else ''))
    if minutes:
        parts.append(str(minutes) + ' minute' + ('s' if minutes != 1 else ''))
    parts.append(str(secs) + ' second' + ('s' if secs != 1 else ''))
    return ', '.join(parts)


#System Uptime
with open('/proc/uptime') as file:
    system_uptime = int(float(file.readline().split()[0]))

#Controller Uptime via ArtiNET Get Uptime (0x06), reply is '(value)'
local = artiled.Controller(name, node, port, timeout)
reply = str(local.get_uptime())
match = re.search(r'(\d+)', reply)
if not match:
    print('ArtiLED > Error: no uptime reply from the LED controller (' + reply + ')')
    sys.exit(1)
controller_uptime = int(match.group(1))

print('ArtiLED > System Uptime         : ' + str(system_uptime) + ' s (' + human(system_uptime) + ')')
print('ArtiLED > Led Controller Uptime : ' + str(controller_uptime) + ' s (' + human(controller_uptime) + ')')

#Same boot or not? A shared power event leaves the two within seconds of each
#other; the controller boots faster than the Pi, so it reads slightly higher.
difference = controller_uptime - system_uptime
print('ArtiLED > Difference            : ' + str(difference) + ' s')
if abs(difference) <= 120:
    print('ArtiLED > Last boot             : together (shared power event)')
else:
    print('ArtiLED > Last boot             : independent')
