# LVGL v9 demo in MicroPython - Predictive Smart Home Panel
# Screen size 420x320
#
# A console that doesn't just control lights and climate: it learns routines,
# predicts what comes next, and adapts the home to presence, habits and context.
#
#  - Simulated clock (accelerated) with two occupants who leave / come home
#  - Learned routines with a confidence score; >= 70 % runs automatically
#    when "Auto-adapt" is on, otherwise the panel asks you first
#  - Apply / +15m / Skip on a prediction raises or lowers its confidence
#  - Changing a light or the set point shortly after a routine ran teaches
#    the routine your preferred value
#  - Context rules: empty house -> lights off + Away; arrival after dark ->
#    entry lights; routines that need "nobody home" wait for the last person
#  - Occupancy-by-hour heat map learned from presence
#
# Pages (left bar): Overview, Lights, Climate, Habits

import display_driver
import lvgl as lv
import random
import math

W, H = 420, 320

# ------------------------------------------------------------------ palette
C_BG = 0x0E1320
C_BAR = 0x151C2C
C_CARD = 0x1B2438
C_CARD2 = 0x26324D
C_TXT = 0xE8EDF5
C_DIM = 0x8A96AD
C_ACC = 0x4FC3F7
C_WARM = 0xFFB74D
C_OK = 0x81C784
C_BAD = 0xE57373
C_VIO = 0xB39DDB


def col(h):
    return lv.color_hex(h)


def font(*names):
    for n in names:
        f = getattr(lv, n, None)
        if f is not None:
            return f
    return None


F_S = font('font_montserrat_12', 'font_montserrat_14')
F_M = font('font_montserrat_14')
F_L = font('font_montserrat_20', 'font_montserrat_18', 'font_montserrat_16',
           'font_montserrat_14')
F_XL = font('font_montserrat_36', 'font_montserrat_32', 'font_montserrat_28',
            'font_montserrat_24', 'font_montserrat_20', 'font_montserrat_16',
            'font_montserrat_14')


def mix(a, b, t):
    t = max(0.0, min(1.0, t))
    out = 0
    for sh in (16, 8, 0):
        ca = (a >> sh) & 255
        cb = (b >> sh) & 255
        out |= int(ca + (cb - ca) * t) << sh
    return out


# ------------------------------------------------------------------ widgets
def no_scroll(o):
    o.remove_flag(lv.obj.FLAG.SCROLLABLE)


def box(parent, x, y, w, h, bg=C_CARD, r=10, pad=8):
    o = lv.obj(parent)
    o.set_pos(x, y)
    o.set_size(w, h)
    o.set_style_bg_color(col(bg), 0)
    o.set_style_bg_opa(255, 0)
    o.set_style_border_width(0, 0)
    o.set_style_shadow_width(0, 0)
    o.set_style_radius(r, 0)
    o.set_style_pad_all(pad, 0)
    no_scroll(o)
    return o


def text(parent, s, x=0, y=0, color=C_TXT, fnt=None, w=None, align=None):
    l = lv.label(parent)
    l.set_text(s)
    l.set_style_text_color(col(color), 0)
    if fnt is not None:
        l.set_style_text_font(fnt, 0)
    if w:
        l.set_width(w)
    if align is not None:
        l.align(align, x, y)
    else:
        l.set_pos(x, y)
    return l


def button(parent, s, x, y, w, h, bg, cb, fnt=None, fg=C_BG):
    b = lv.button(parent)
    b.set_pos(x, y)
    b.set_size(w, h)
    b.set_style_bg_color(col(bg), 0)
    b.set_style_radius(8, 0)
    b.set_style_shadow_width(0, 0)
    l = lv.label(b)
    l.set_text(s)
    l.center()
    l.set_style_text_color(col(fg), 0)
    if fnt is not None:
        l.set_style_text_font(fnt, 0)
    b.add_event_cb(lambda e: cb(), lv.EVENT.CLICKED, None)
    return b, l


def bar(parent, x, y, w, h, color, val=0):
    b = lv.bar(parent)
    b.set_pos(x, y)
    b.set_size(w, h)
    b.set_range(0, 100)
    b.set_style_bg_color(col(C_CARD2), 0)
    b.set_style_bg_opa(255, 0)
    b.set_style_bg_color(col(color), lv.PART.INDICATOR)
    b.set_value(val, lv.ANIM.OFF)
    return b


# ------------------------------------------------------------------ model
ROOMS = ['Living', 'Kitchen', 'Bedroom', 'Office']
L = {}
for _n, _lvl, _on in (('Living', 40, False), ('Kitchen', 60, False),
                      ('Bedroom', 15, True), ('Office', 70, False)):
    L[_n] = {'level': _lvl, 'on': _on, 'auto': False}

MODES = ['Comfort', 'Eco', 'Away', 'Off']
MODE_COL = {'Comfort': C_WARM, 'Eco': C_OK, 'Away': C_VIO, 'Off': C_DIM}
DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
SPEEDS = [1, 5, 15, 30]      # simulated minutes per 250 ms tick
TH = 70                      # confidence needed to act automatically
LATE = 30                    # minutes a due routine waits for its condition

S = {
    'abs': 3 * 1440 + 6 * 60 + 20,   # Thursday 06:20
    'sp': 20.5, 'mode': 'Eco', 'prev_mode': 'Comfort',
    'indoor': 19.3, 'outdoor': 10.0, 'heating': False, 'kwh': 0.0,
    'auto': True, 'speed': 0, 'empty_since': None,
    'last': 'Learning your routines', 'toast_ttl': 0,
    'hm_hour': -1, 'hm_dirty': True, 'dirty': True, 'shown': None,
}

# occupants: weekday / weekend (leave, back) in minutes, None = stays home
PEOPLE = [
    {'name': 'Ana', 'home': True, 'leave': None, 'back': None,
     'wd': (500, 1070), 'we': (660, 810)},
    {'name': 'Leo', 'home': True, 'leave': None, 'back': None,
     'wd': (515, 1110), 'we': None},
]

# learned routines; lights are [room, level] (0 = off)
R = [
    {'name': 'Wake up', 't': 405, 'conf': 84, 'need': 'home', 'days': 'all',
     'wk': 75, 'lights': [['Bedroom', 30], ['Kitchen', 70]],
     'temp': 21.0, 'mode': 'Comfort'},
    {'name': 'Leave for work', 't': 505, 'conf': 77, 'need': 'empty',
     'days': 'wd', 'lights': [[n, 0] for n in ROOMS],
     'temp': 19.0, 'mode': 'Eco'},
    {'name': 'Pre-heat arrival', 't': 1035, 'conf': 72, 'need': 'any',
     'days': 'wd', 'lights': [], 'temp': 21.5, 'mode': 'Comfort'},
    {'name': 'Dinner', 't': 1170, 'conf': 66, 'need': 'home', 'days': 'all',
     'lights': [['Kitchen', 85], ['Living', 60]], 'temp': None, 'mode': None},
    {'name': 'Wind down', 't': 1335, 'conf': 74, 'need': 'home',
     'days': 'all', 'lights': [['Living', 25], ['Kitchen', 0], ['Bedroom', 20]],
     'temp': 20.0, 'mode': None},
    {'name': 'Night', 't': 1395, 'conf': 81, 'need': 'home', 'days': 'all',
     'lights': [[n, 0] for n in ROOMS], 'temp': 18.5, 'mode': 'Eco'},
]
for _r in R:
    _r['done'] = False
    _r['snooze'] = 0
    _r['applied'] = None

OCC = [0.95 if (h < 8 or h >= 18) else 0.25 for h in range(24)]


def now_m():
    return S['abs'] % 1440


def weekday():
    return (S['abs'] // 1440) % 7


def weekend():
    return weekday() >= 5


def hhmm(m):
    m %= 1440
    return '%02d:%02d' % (m // 60, m % 60)


def dur(d):
    if d < 60:
        return '%d min' % d
    return '%dh %02dm' % (d // 60, d % 60)


def phase(m):
    if m < 360:
        return 'Night'
    if m < 720:
        return 'Morning'
    if m < 1080:
        return 'Afternoon'
    if m < 1320:
        return 'Evening'
    return 'Night'


def plan_people():
    we = weekend()
    for p in PEOPLE:
        s = p['we'] if we else p['wd']
        if s:
            p['leave'] = s[0] + random.randint(-12, 12)
            p['back'] = s[1] + random.randint(-20, 20)
        else:
            p['leave'] = None
            p['back'] = None


def home_count():
    return sum(1 for p in PEOPLE if p['home'])


def due(r):
    return r['t'] + r['snooze'] + (r.get('wk', 0) if weekend() else 0)


def cond_ok(r):
    h = home_count()
    if r['need'] == 'home' and h == 0:
        return False, 'nobody home'
    if r['need'] == 'empty' and h > 0:
        names = [p['name'] for p in PEOPLE if p['home']]
        return False, ' & '.join(names) + ' still home'
    return True, ''


def target():
    md = S['mode']
    if md == 'Comfort':
        return S['sp']
    if md == 'Eco':
        return S['sp'] - 1.0
    if md == 'Away':
        return 16.0
    return None


def lights_watts():
    return sum(L[n]['level'] * 0.12 for n in ROOMS if L[n]['on'])


def describe(r):
    parts = []
    lights = r['lights']
    if lights:
        if len(lights) == len(ROOMS) and all(v == 0 for _, v in lights):
            parts.append('All lights off')
        else:
            parts.append(', '.join(
                '%s %s' % (n, ('%d%%' % v) if v else 'off') for n, v in lights))
    if r['temp'] is not None:
        parts.append('heat %.1f°C' % r['temp'])
    if r['mode']:
        parts.append(r['mode'])
    return '  •  '.join(parts)


# ------------------------------------------------------------------ engine
def notify(msg, color=C_ACC):
    S['last'] = msg
    toast(msg, color)


def apply(r, how):
    for n, lvl in r['lights']:
        if lvl > 0:
            L[n]['level'] = lvl
            L[n]['on'] = True
        else:
            L[n]['on'] = False
        L[n]['auto'] = True
    if r['temp'] is not None:
        S['sp'] = r['temp']
    if r['mode']:
        S['mode'] = r['mode']
        if r['mode'] != 'Away':
            S['prev_mode'] = r['mode']
    r['done'] = True
    r['applied'] = S['abs']
    r['conf'] = min(98, r['conf'] + (3 if how == 'manual' else 1))
    notify(('Applied: ' if how == 'manual' else 'Auto: ') + r['name'], C_OK)
    S['dirty'] = True


def away_rule():
    changed = False
    for n in ROOMS:
        if L[n]['on']:
            L[n]['on'] = False
            L[n]['auto'] = True
            changed = True
    if S['mode'] != 'Away':
        S['prev_mode'] = S['mode']
        S['mode'] = 'Away'
        changed = True
    if changed:
        notify('House empty: lights off, Away', C_VIO)
        S['dirty'] = True


def on_arrival(names):
    msg = 'Welcome home, ' + ' & '.join(names)
    if S['mode'] == 'Away':
        S['mode'] = S['prev_mode']
    m = now_m()
    if m >= 1140 or m < 420:          # after sunset: entry lights
        L['Living']['level'] = max(L['Living']['level'], 50)
        L['Living']['on'] = True
        L['Living']['auto'] = True
        msg += ', lights on'
    notify(msg, C_ACC)
    S['dirty'] = True


def new_day():
    for r in R:
        r['done'] = (r['days'] == 'wd' and weekend())
        r['snooze'] = 0
        r['applied'] = None
    plan_people()
    S['kwh'] = 0.0


def step():
    S['abs'] += 1
    m = now_m()
    if m == 0:
        new_day()

    # presence
    arrived = []
    for p in PEOPLE:
        was = p['home']
        p['home'] = not (p['leave'] is not None and p['leave'] <= m < p['back'])
        if p['home'] and not was:
            arrived.append(p['name'])
    h = home_count()
    if arrived:
        if h == len(arrived):
            on_arrival(arrived)
        else:
            notify(' & '.join(arrived) + ' is home', C_ACC)
    if h > 0:
        S['empty_since'] = None
    elif S['empty_since'] is None:
        S['empty_since'] = S['abs']
    elif S['abs'] - S['empty_since'] == 15:
        away_rule()

    # routines
    for r in R:
        if r['done']:
            continue
        d = due(r) - m
        if d > 0:
            continue
        ok, why = cond_ok(r)
        if ok and S['auto'] and r['conf'] >= TH:
            apply(r, 'auto')
        elif d <= -LATE:
            r['done'] = True
            r['conf'] = max(30, r['conf'] - 3)
            notify('Skipped %s (%s)' % (r['name'], why or 'not confirmed'), C_DIM)

    # climate & energy
    S['outdoor'] = 13 + 6 * math.sin((m - 600) / 1440 * 2 * math.pi)
    t = target()
    if t is None:
        S['heating'] = False
    elif S['indoor'] < t - 0.2:
        S['heating'] = True
    elif S['indoor'] >= t:
        S['heating'] = False
    S['indoor'] += (S['outdoor'] - S['indoor']) * 0.003
    if S['heating']:
        S['indoor'] += 0.05
    S['kwh'] += (lights_watts() + (2000 if S['heating'] else 0)) / 1000 / 60

    # learn occupancy per hour
    if m % 60 == 59:
        hr = m // 60
        OCC[hr] = OCC[hr] * 0.8 + (1.0 if h else 0.0) * 0.2
        S['hm_dirty'] = True


def next_routine():
    best = None
    for r in R:
        if r['done']:
            continue
        if best is None or due(r) < due(best):
            best = r
    return best


def learn_light(n):
    eff = L[n]['level'] if L[n]['on'] else 0
    for r in R:
        if r['applied'] is None or S['abs'] - r['applied'] > 45:
            continue
        for pair in r['lights']:
            if pair[0] == n:
                new = int(pair[1] * 0.6 + eff * 0.4 + 0.5)
                if new != pair[1]:
                    pair[1] = new
                    notify('Learned: %s %s %d%%' % (r['name'], n, new), C_VIO)
                return


def learn_temp():
    for r in R:
        if r['applied'] is None or S['abs'] - r['applied'] > 45:
            continue
        if r['temp'] is not None:
            new = round((r['temp'] * 0.6 + S['sp'] * 0.4) * 2) / 2
            if new != r['temp']:
                r['temp'] = new
                notify('Learned: %s %.1f°C' % (r['name'], new), C_VIO)
            return


# ------------------------------------------------------------------ screen
scr = lv.obj()
scr.set_style_bg_color(col(C_BG), 0)
scr.set_style_bg_opa(255, 0)
no_scroll(scr)

# status bar
top = box(scr, 0, 0, W, 28, bg=C_BAR, r=0, pad=0)
text(top, lv.SYMBOL.HOME + '  Predictive Home', 10, 0, C_ACC, F_M,
     align=lv.ALIGN.LEFT_MID)
st_mid = text(top, '', 168, 0, C_DIM, F_S, align=lv.ALIGN.LEFT_MID)
text(top, lv.SYMBOL.WIFI, -10, 0, C_ACC, F_M, align=lv.ALIGN.RIGHT_MID)
st_people = [text(top, '', -38, 0, C_DIM, F_S, align=lv.ALIGN.RIGHT_MID),
             text(top, '', -80, 0, C_DIM, F_S, align=lv.ALIGN.RIGHT_MID)]
st_people.reverse()        # Ana left, Leo right

# navigation
nav = box(scr, 2, 30, 50, 288, bg=C_BAR, r=10, pad=0)
NAV = [lv.SYMBOL.HOME, lv.SYMBOL.POWER, '°C', lv.SYMBOL.LIST]
nav_btns = []
pages = []
for i in range(4):
    p = lv.obj(scr)
    p.set_pos(58, 30)
    p.set_size(360, 288)
    p.set_style_bg_opa(0, 0)
    p.set_style_border_width(0, 0)
    p.set_style_pad_all(0, 0)
    no_scroll(p)
    pages.append(p)


def show_page(i):
    for j, p in enumerate(pages):
        if j == i:
            p.remove_flag(lv.obj.FLAG.HIDDEN)
        else:
            p.add_flag(lv.obj.FLAG.HIDDEN)
    for j, (b, l) in enumerate(nav_btns):
        b.set_style_bg_color(col(C_ACC if j == i else C_CARD2), 0)
        l.set_style_text_color(col(C_BG if j == i else C_TXT), 0)


for i, s in enumerate(NAV):
    nav_btns.append(button(nav, s, 5, 12 + i * 56, 40, 40, C_CARD2,
                           lambda i=i: show_page(i), F_M, C_TXT))

# toast (top layer)
toast_box = box(lv.layer_top(), 0, 0, 300, 30, bg=C_CARD2, r=15, pad=0)
toast_box.align(lv.ALIGN.BOTTOM_MID, 28, -10)
toast_box.set_style_border_width(1, 0)
toast_box.set_style_border_color(col(C_ACC), 0)
toast_box.remove_flag(lv.obj.FLAG.CLICKABLE)
toast_lbl = text(toast_box, '', 0, 0, C_TXT, F_S, align=lv.ALIGN.CENTER)
toast_box.add_flag(lv.obj.FLAG.HIDDEN)


def toast(msg, color=C_ACC):
    toast_lbl.set_text(msg)
    toast_lbl.set_style_text_color(col(color), 0)
    toast_box.set_style_border_color(col(color), 0)
    toast_box.remove_flag(lv.obj.FLAG.HIDDEN)
    S['toast_ttl'] = 14


# ------------------------------------------------------------ page 0: overview
p0 = pages[0]
c1 = box(p0, 0, 0, 172, 92)
ov_time = text(c1, '', 0, 0, C_TXT, F_XL)
ov_day = text(c1, '', 0, 44, C_DIM, F_S)
ov_mode = text(c1, '', 0, 62, C_WARM, F_S)

c2 = box(p0, 180, 0, 180, 92)
ov_in = text(c2, '', 0, 0, C_TXT, F_S)
ov_out = text(c2, '', 0, 19, C_TXT, F_S)
ov_home = text(c2, '', 0, 38, C_TXT, F_S)
ov_kwh = text(c2, '', 0, 57, C_TXT, F_S)

c3 = box(p0, 0, 100, 360, 136)
c3.set_style_border_width(1, 0)
c3.set_style_border_color(col(C_ACC), 0)
c3.set_style_border_opa(110, 0)
pr_head = text(c3, '', 0, 0, C_ACC, F_S)
pr_title = text(c3, '', 0, 16, C_TXT, F_L)
pr_detail = text(c3, '', 0, 42, C_DIM, F_S, w=344)
pr_conf = text(c3, '', 0, 64, C_TXT, F_S)
pr_bar = bar(c3, 112, 69, 128, 8, C_ACC)
pr_tag = text(c3, '', 250, 64, C_OK, F_S)
pr_reason = text(c3, '', 0, 84, C_DIM, F_S, w=180)


def on_apply():
    r = S['shown']
    if r is not None and not r['done']:
        apply(r, 'manual')
        refresh()


def on_snooze():
    r = S['shown']
    if r is not None and not r['done']:
        r['snooze'] += 15
        notify('%s moved to %s' % (r['name'], hhmm(due(r))), C_WARM)
        refresh()


def on_skip():
    r = S['shown']
    if r is not None and not r['done']:
        r['done'] = True
        r['conf'] = max(30, r['conf'] - 6)
        notify('Skipped %s, conf. %d%%' % (r['name'], r['conf']), C_DIM)
        refresh()


pr_btns = [button(c3, 'Apply', 186, 86, 52, 30, C_OK, on_apply, F_S)[0],
           button(c3, '+15m', 242, 86, 52, 30, C_WARM, on_snooze, F_S)[0],
           button(c3, 'Skip', 298, 86, 46, 30, C_CARD2, on_skip, F_S, C_TXT)[0]]

c4 = box(p0, 0, 244, 360, 44)
sw_auto = lv.switch(c4)
sw_auto.set_pos(0, 2)
sw_auto.set_size(44, 24)
sw_auto.add_state(lv.STATE.CHECKED)


def on_auto(e):
    S['auto'] = sw_auto.has_state(lv.STATE.CHECKED)
    notify('Auto-adapt ' + ('on' if S['auto'] else 'off: asking first'),
           C_OK if S['auto'] else C_WARM)
    refresh()


sw_auto.add_event_cb(on_auto, lv.EVENT.VALUE_CHANGED, None)
text(c4, 'Auto-adapt', 52, 5, C_TXT, F_S)
ov_last = text(c4, '', 132, 5, C_DIM, F_S)


def on_speed():
    S['speed'] = (S['speed'] + 1) % len(SPEEDS)
    spd_lbl.set_text('x%d' % SPEEDS[S['speed']])


spd_lbl = button(c4, 'x1', 288, 0, 56, 28, C_CARD2, on_speed, F_S, C_ACC)[1]

# ------------------------------------------------------------ page 1: lights
p1 = pages[1]
text(p1, 'Lights', 0, 0, C_TXT, F_L)
text(p1, 'AUTO = set by the panel. Tweaks teach it.', 76, 6, C_DIM, F_S)
W_ROOM = {}


def room_cbs(n, sw, sl):
    def on_sw(e):
        r = L[n]
        r['on'] = sw.has_state(lv.STATE.CHECKED)
        if r['on'] and r['level'] < 5:
            r['level'] = 50
        r['auto'] = False
        sync_rooms()
        learn_light(n)

    def on_sl(e):
        r = L[n]
        r['level'] = sl.get_value()
        r['on'] = r['level'] > 0
        r['auto'] = False
        sync_rooms()

    def on_rel(e):
        learn_light(n)

    sw.add_event_cb(on_sw, lv.EVENT.VALUE_CHANGED, None)
    sl.add_event_cb(on_sl, lv.EVENT.VALUE_CHANGED, None)
    sl.add_event_cb(on_rel, lv.EVENT.RELEASED, None)


for i, n in enumerate(ROOMS):
    c = box(p1, 0, 28 + i * 65, 360, 58)
    sw = lv.switch(c)
    sw.set_pos(0, 9)
    sw.set_size(44, 24)
    text(c, n, 56, 0, C_TXT, F_M)
    badge = text(c, 'AUTO', 140, 1, C_ACC, F_S)
    val = text(c, '', 0, 0, C_TXT, F_S, align=lv.ALIGN.TOP_RIGHT)
    sl = lv.slider(c)
    sl.set_pos(60, 25)
    sl.set_size(220, 8)
    sl.set_range(0, 100)
    sl.set_style_bg_color(col(C_CARD2), 0)
    sl.set_style_bg_color(col(C_WARM), lv.PART.INDICATOR)
    sl.set_style_bg_color(col(C_TXT), lv.PART.KNOB)
    W_ROOM[n] = (sw, sl, val, badge)
    room_cbs(n, sw, sl)


def sync_rooms():
    for n in ROOMS:
        sw, sl, val, badge = W_ROOM[n]
        r = L[n]
        if r['on']:
            sw.add_state(lv.STATE.CHECKED)
        else:
            sw.remove_state(lv.STATE.CHECKED)
        sl.set_value(r['level'], lv.ANIM.OFF)
        val.set_text(('%d%%' % r['level']) if r['on'] else 'off')
        val.set_style_text_color(col(C_WARM if r['on'] else C_DIM), 0)
        if r['auto']:
            badge.remove_flag(lv.obj.FLAG.HIDDEN)
        else:
            badge.add_flag(lv.obj.FLAG.HIDDEN)


# ------------------------------------------------------------ page 2: climate
p2 = pages[2]
cl = box(p2, 0, 0, 200, 288)
arc = lv.arc(cl)
arc.set_size(160, 160)
arc.align(lv.ALIGN.TOP_MID, 0, 4)
arc.set_range(32, 56)                  # 16.0 .. 28.0 °C in 0.5 steps
arc.set_style_arc_color(col(C_CARD2), 0)
arc.set_style_arc_width(12, 0)
arc.set_style_arc_color(col(C_WARM), lv.PART.INDICATOR)
arc.set_style_arc_width(12, lv.PART.INDICATOR)
arc.set_style_bg_color(col(C_TXT), lv.PART.KNOB)
cl_sp = text(arc, '', 0, -8, C_TXT, F_XL, align=lv.ALIGN.CENTER)
text(arc, 'set point', 0, 22, C_DIM, F_S, align=lv.ALIGN.CENTER)
cl_in = text(cl, '', 0, 170, C_TXT, F_S, align=lv.ALIGN.TOP_MID)


def on_arc(e):
    S['sp'] = arc.get_value() / 2


def nudge(dv):
    S['sp'] = max(16.0, min(28.0, S['sp'] + dv))
    learn_temp()
    refresh()


arc.add_event_cb(on_arc, lv.EVENT.VALUE_CHANGED, None)
arc.add_event_cb(lambda e: learn_temp(), lv.EVENT.RELEASED, None)
button(cl, '-', 22, 196, 60, 36, C_CARD2, lambda: nudge(-0.5), F_L, C_TXT)
button(cl, '+', 102, 196, 60, 36, C_CARD2, lambda: nudge(0.5), F_L, C_TXT)
cl_heat = text(cl, '', 0, 246, C_DIM, F_S, align=lv.ALIGN.TOP_MID)

cr = box(p2, 208, 0, 152, 288)
text(cr, 'Mode', 0, 0, C_DIM, F_S)
mode_btns = []


def set_mode(md):
    S['mode'] = md
    if md != 'Away':
        S['prev_mode'] = md
    notify('Mode: ' + md, MODE_COL[md])
    refresh()


for i, md in enumerate(MODES):
    mode_btns.append(button(cr, md, 0, 18 + i * 38, 136, 32, C_CARD2,
                            lambda md=md: set_mode(md), F_S, C_TXT))
cl_out = text(cr, '', 0, 176, C_TXT, F_S)
cl_pred = text(cr, '', 0, 198, C_DIM, F_S, w=136)

# ------------------------------------------------------------ page 3: habits
p3 = pages[3]
hb = box(p3, 0, 0, 360, 288)
text(hb, 'Learned routines', 0, 0, C_TXT, F_M)
text(hb, 'confidence', 0, 2, C_DIM, F_S, align=lv.ALIGN.TOP_RIGHT)
HB = []
for i, r in enumerate(R):
    y = 22 + i * 28
    nm = text(hb, '%s  %s' % (hhmm(r['t']), r['name']), 0, y, C_TXT, F_S)
    b = bar(hb, 170, y + 5, 120, 8, C_OK)
    pc = text(hb, '', 302, y, C_TXT, F_S)
    HB.append((nm, b, pc))
text(hb, 'Home occupancy by hour (learned)', 0, 188, C_DIM, F_S)
CELLS = []
for h in range(24):
    c = box(hb, h * 14, 208, 13, 24, bg=C_CARD2, r=3, pad=0)
    c.set_style_border_color(col(C_TXT), 0)
    CELLS.append(c)
for h in (0, 6, 12, 18):
    text(hb, '%02d' % h, h * 14, 236, C_DIM, F_S)
text(hb, '24', 322, 236, C_DIM, F_S)
text(hb, 'Brighter = someone is usually home', 0, 254, C_DIM, F_S)


# ------------------------------------------------------------------ refresh
def refresh():
    m = now_m()
    st_mid.set_text('%s %s  •  %s' % (DAYS[weekday()], hhmm(m), phase(m)))
    for lbl, p in zip(st_people, PEOPLE):
        lbl.set_text('• ' + p['name'])
        lbl.set_style_text_color(col(C_OK if p['home'] else C_DIM), 0)

    # overview
    ov_time.set_text(hhmm(m))
    ov_day.set_text('%s  •  %s' % (DAYS[weekday()], phase(m)))
    ov_mode.set_text('Mode: ' + S['mode'])
    ov_mode.set_style_text_color(col(MODE_COL[S['mode']]), 0)
    ov_in.set_text('Indoor  %.1f°C%s' % (S['indoor'],
                                          '  heating' if S['heating'] else ''))
    ov_in.set_style_text_color(col(C_WARM if S['heating'] else C_TXT), 0)
    ov_out.set_text('Outdoor  %.0f°C' % S['outdoor'])
    ov_home.set_text('Home  %d of %d people' % (home_count(), len(PEOPLE)))
    ov_kwh.set_text('Energy  %.2f kWh today' % S['kwh'])

    r = next_routine()
    if r is None:
        r = R[0]
        pr_head.set_text('TOMORROW')
        for b in pr_btns:
            b.add_flag(lv.obj.FLAG.HIDDEN)
        S['shown'] = None
    else:
        d = due(r) - m
        ok, why = cond_ok(r)
        if d > 0:
            pr_head.set_text('NEXT PREDICTED  •  in ' + dur(d))
        elif not ok:
            pr_head.set_text('DUE NOW  •  waiting: ' + why)
        else:
            pr_head.set_text('DUE NOW  •  confirm?')
        for b in pr_btns:
            b.remove_flag(lv.obj.FLAG.HIDDEN)
        S['shown'] = r
    pr_title.set_text('%s  %s' % (r['name'], hhmm(due(r))))
    pr_detail.set_text(describe(r))
    pr_conf.set_text('Confidence %d%%' % r['conf'])
    pr_bar.set_value(r['conf'], lv.ANIM.ON)
    auto_ok = S['auto'] and r['conf'] >= TH
    pr_bar.set_style_bg_color(col(C_OK if r['conf'] >= TH else C_WARM),
                              lv.PART.INDICATOR)
    pr_tag.set_text('AUTO' if auto_ok else 'ASKS YOU')
    pr_tag.set_style_text_color(col(C_OK if auto_ok else C_WARM), 0)
    seen = int(r['conf'] * 28 / 100 + 0.5)
    pr_reason.set_text('Seen on %d of the last 28 %s' %
                       (seen, 'weekdays' if r['days'] == 'wd' else 'days'))
    ov_last.set_text(S['last'][:22])

    # climate
    if not arc.has_state(lv.STATE.PRESSED):
        arc.set_value(int(S['sp'] * 2 + 0.5))
    cl_sp.set_text('%.1f°' % S['sp'])
    cl_in.set_text('Indoor %.1f°C' % S['indoor'])
    t = target()
    cl_heat.set_text(('Heating to %.1f°C' % t if S['heating'] else
                      'Holding %.1f°C' % t) if t is not None else 'Heating off')
    cl_heat.set_style_text_color(col(C_WARM if S['heating'] else C_DIM), 0)
    for (b, l), md in zip(mode_btns, MODES):
        sel = md == S['mode']
        b.set_style_bg_color(col(MODE_COL[md] if sel else C_CARD2), 0)
        l.set_style_text_color(col(C_BG if sel else C_TXT), 0)
    cl_out.set_text('Outdoor %.0f°C' % S['outdoor'])
    nxt = None
    for q in R:
        if not q['done'] and q['temp'] is not None:
            if nxt is None or due(q) < due(nxt):
                nxt = q
    if nxt is not None:
        cl_pred.set_text('Predicted: %s sets %.1f°C at %s' %
                         (nxt['name'], nxt['temp'], hhmm(due(nxt))))
    else:
        cl_pred.set_text('No more changes predicted today')

    # lights
    if S['dirty']:
        sync_rooms()
        S['dirty'] = False

    # habits
    for (nm, b, pc), q in zip(HB, R):
        b.set_value(q['conf'], lv.ANIM.ON)
        b.set_style_bg_color(col(C_OK if q['conf'] >= TH else C_WARM),
                             lv.PART.INDICATOR)
        pc.set_text('%d%%' % q['conf'])
        nm.set_style_text_color(col(C_DIM if q['done'] else C_TXT), 0)
    hr = m // 60
    if S['hm_dirty'] or hr != S['hm_hour']:
        for h, c in enumerate(CELLS):
            c.set_style_bg_color(col(mix(C_CARD2, C_ACC, OCC[h])), 0)
            c.set_style_border_width(2 if h == hr else 0, 0)
        S['hm_hour'] = hr
        S['hm_dirty'] = False


# ------------------------------------------------------------------ main loop
def tick(t):
    for _ in range(SPEEDS[S['speed']]):
        step()
    if S['toast_ttl'] > 0:
        S['toast_ttl'] -= 1
        if S['toast_ttl'] == 0:
            toast_box.add_flag(lv.obj.FLAG.HIDDEN)
    refresh()


plan_people()
show_page(0)
refresh()
lv.screen_load(scr)
toast('Good morning. Watching your routines.', C_ACC)
TMR = lv.timer_create(tick, 250, None)