everlights 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ee4915d68adebdaaaa5d1ea02be82d7530ebbdee06fbfd2905b73aa49fa9cf6e
4
- data.tar.gz: f6ed7abeccd0e26b23795679e3cf8dcf876b73163cd684d9ffe109ceadc8a085
3
+ metadata.gz: 0d319ee1f69ecca30fa28e49bac2a468bb9f069d9f438d6d7ca6bc5e20adb1ed
4
+ data.tar.gz: 427cd966f9b74e8c158db2847862ea7d739e064cfac5b0e3b418ce797f657cf4
5
5
  SHA512:
6
- metadata.gz: 011d597b5b53676084adad56466ddb9dde0fa77f8e6c6a37264078495a10959e3350a90e0d365afbcf24c4c0a3a0188b0dd3476808a1fc10bf9f63761de0daee
7
- data.tar.gz: d99fd9e1c63b2d3e70edd0e0a0ce3cc072a677f4a3c4734b65d90bcdeb45662f2f5e1f42f49eea37a9b5fbdbd6b4d59060492a1478aca51dedb7a165cdd6050a
6
+ metadata.gz: ea88456723a18232c6aaf93ff903dfd050cb4054eb2bd97eb782cc13dc9bb227198d5efac12510553e37e692a798d06731df53f0a19d9fcd14a23a62926a0dc2
7
+ data.tar.gz: 197bbe6f6247cd149164cfd5785ac1e86aeca84570dc4ce9c770ac35fcdcce05d34d0f6eae9e46293438ab920fec3a8f13f829ea2de60ff7a6d18aa5b84476c0
data/README.md CHANGED
@@ -87,6 +87,20 @@ schedule: # higher in the list wins a shared night
87
87
  - **Config location:** `--config` or `$EVERLIGHTS_CONFIG`. The config's `bridge.host` is used by every command unless `--host` or `$EVERLIGHTS_HOST` is set.
88
88
  - **Time zone:** set `timezone:` in the config, or it uses your machine's.
89
89
 
90
+ ### In a browser
91
+
92
+ ```sh
93
+ everlights web # http://localhost:4567 (--port to change)
94
+ ```
95
+
96
+ The **Calendar** view shows each night ahead as a bulb on a light string, lit with the sequence that plays. Drag rules to set their priority. Drag sequences onto rules, or between them. Rule changes are saved to the config file straight away.
97
+
98
+ Hover any sequence chip to open its card. For your own sequences you can edit colors and effects there, then **Save** or **Revert**. Built-ins and app-made sequences can be previewed or copied into yours. The **Sequences** view has the same editor for all of your sequences. The **Bridge** view shows health checks (the same as `bridge health`), firmware, network, reboots, and each zone's signal and sensors. It has buttons to set the clock and to reboot; reboot asks you to click twice. **Apply** sends the pending changes to the bridge.
99
+
100
+ **Preview** (on a sequence, or click a bridge sequence) shows it on the lights now, and edits to it show as you make them. **Stop preview** hands the lights back to the calendar. So does closing the page: the preview is cleared about 20 seconds after the page stops checking in, and also when the server quits. During a running show, a preview only lasts until the show's next sequence change.
101
+
102
+ The page only listens on localhost. Saving rewrites the YAML, which drops your comments; the first save keeps the original at `everlights.yml.bak`, and that copy is never replaced. If you edit the file by hand while the page is open, the page reloads it instead of overwriting it.
103
+
90
104
  To keep the calendar topped up, run it on a schedule, for example monthly from cron:
91
105
  `0 9 1 * * cd ~/everlights && everlights sync >> config/sync.log 2>&1`
92
106
 
data/exe/everlights CHANGED
@@ -34,6 +34,7 @@ USAGE = <<~TXT
34
34
  Sync (config/everlights.yml: sequences + schedule, see config/everlights.example.yml):
35
35
  sync [--dry-run] [--adopt] build sequences and the calendar ahead; prints the plan
36
36
  sync --check plan only; exit 2 if the bridge needs a sync (for cron)
37
+ web [--port N] edit the config in a browser and apply it (localhost:4567)
37
38
 
38
39
  Options:
39
40
  TXT
@@ -56,6 +57,7 @@ parser = OptionParser.new do |o|
56
57
  o.on("--yes", "confirm bridge reboot") { opts[:yes] = true }
57
58
  o.on("--dry-run", "sync: print the plan only") { opts[:dry_run] = true }
58
59
  o.on("--check", "sync: plan only, exit 2 if anything would change") { opts[:check] = true }
60
+ o.on("--port N", Integer, "web: port (default 4567)") { opts[:port] = _1 }
59
61
  o.on("--adopt", "sync: take over bridge items whose names match the config") { opts[:adopt] = true }
60
62
  end
61
63
  parser.parse!
@@ -95,22 +97,7 @@ begin
95
97
  end
96
98
  end
97
99
  when "bridge health"
98
- # ponytail: thresholds are guesses from one bridge; tune when real failures show what matters
99
- b = el.status
100
- ago = ->(v) { v ? ((Time.now - Time.parse(v)) / 60).round : Float::INFINITY }
101
- mins = ->(m) { m.infinite? ? "never" : "#{m} min ago" }
102
- cloud, radio = ago.(b["lastServerCheckin"]), ago.(b["lastRadioResponse"])
103
- checks = [
104
- [!!b["serverReachable"] && cloud <= 15, "cloud", "#{b["serverReachable"] ? "reachable" : "unreachable"}, checked in #{mins.(cloud)}"],
105
- [!!b.dig("network", "ntp"), "clock", "ntp #{b.dig("network", "ntp") ? "on" : "off"}"],
106
- [b["minFreeHeap"].to_i >= 10_000, "memory", "lowest free since boot #{b["minFreeHeap"]} bytes (warn under 10000)"],
107
- [radio <= 10, "radio", "answered #{mins.(radio)}, #{b["radioRebootCount"]} radio reboots"],
108
- *b["zones"].map do |z|
109
- last = ago.(z["lastResponseDate"])
110
- [!!z["active"] && last <= 10, "zone #{z["serial"]}", "#{z["active"] ? "active" : "inactive"}, answered #{mins.(last)}, #{z["rebootCount"]} reboots"]
111
- end,
112
- [:info, "reboots", "#{b["rebootCount"]} total, last reset reason #{b["resetReason"]}"]
113
- ]
100
+ checks = Everlights.health(el.status)
114
101
  checks.each { |ok, name, text| puts "#{{info: "info", true => "ok ", false => "WARN"}[ok]} #{name.ljust(19)} #{text}" }
115
102
  exit 2 unless checks.all? { _1[0] }
116
103
  when "bridge time"
@@ -197,8 +184,7 @@ begin
197
184
 
198
185
  when "sync"
199
186
  raise Everlights::Error, "no config at #{config_path}; copy config/everlights.example.yml to start" unless config
200
- state_path = File.join(File.dirname(config_path), ".sync-state.yml")
201
- plan = Everlights::Sync.new(el, config, state_path: state_path, adopt: opts[:adopt]).plan
187
+ plan = Everlights::Sync.new(el, config, state_path: Everlights::Sync.state_path(config_path), adopt: opts[:adopt]).plan
202
188
  puts plan
203
189
  if plan.empty? then nil
204
190
  elsif opts[:check] then exit 2
@@ -208,6 +194,11 @@ begin
208
194
  puts "\nApplied."
209
195
  end
210
196
 
197
+ when "web"
198
+ raise Everlights::Error, "no config at #{config_path}; copy config/everlights.example.yml to start" unless config
199
+ require_relative "../lib/everlights/web"
200
+ Everlights::Web.new(el, config_path, port: opts[:port] || 4567).start
201
+
211
202
  else abort parser.help
212
203
  end
213
204
  rescue Everlights::Error, IndexError, ArgumentError, TypeError, Date::Error, SystemCallError, Net::OpenTimeout => e
@@ -19,7 +19,8 @@ module Everlights
19
19
 
20
20
  Action = Struct.new(:kind, :op, :name, :detail, :run)
21
21
 
22
- Plan = Struct.new(:actions, :skips, :horizon, :sync) do
22
+ # shows: {rule name => [[start, end], ...]}, the nights each rule plays, tonight's show under way included
23
+ Plan = Struct.new(:actions, :skips, :horizon, :sync, :shows) do
23
24
  def empty? = actions.empty?
24
25
  def apply! = sync.apply(self)
25
26
 
@@ -63,12 +64,18 @@ module Everlights
63
64
  def self.load_config(path)
64
65
  config = YAML.safe_load_file(path, permitted_classes: [Date]) || {}
65
66
  # YAML 1.1 reads the key `on:` as boolean true; put it back
66
- Array(config["schedule"]).each { |r| r["on"] = r.delete(true) if r.is_a?(Hash) && r.key?(true) }
67
+ # (transform_keys keeps `on` where it was, so a saved file reads in the same order)
68
+ config["schedule"].map! { |r| r.is_a?(Hash) ? r.transform_keys { _1 == true ? "on" : _1 } : r } if config["schedule"].is_a?(Array)
67
69
  config
68
70
  rescue Psych::SyntaxError => e
69
71
  raise Error, "#{path}: #{e.message}"
70
72
  end
71
73
 
74
+ # What sync has made on the bridge, next to the config.
75
+ def self.state_path(config_path) = File.join(File.dirname(config_path), ".sync-state.yml")
76
+
77
+ attr_reader :bridge_seqs # the bridge's sequences, as read by the last #plan
78
+
72
79
  def initialize(client, config, state_path: nil, adopt: false, now: Time.now)
73
80
  @c, @cfg, @state_path, @adopt, @now = client, config || {}, state_path, adopt, now
74
81
  end
@@ -76,7 +83,7 @@ module Everlights
76
83
  def plan
77
84
  @errors = []
78
85
  @state = load_state
79
- bridge_seqs = @c.sequence_list
86
+ bridge_seqs = @bridge_seqs = @c.sequence_list
80
87
  bridge_events = @c.event_list
81
88
  actions = @adopt ? adopt(bridge_seqs, bridge_events) : []
82
89
  owned_seq_ids = @state["sequences"].values
@@ -150,11 +157,13 @@ module Everlights
150
157
 
151
158
  # One calendar entry per rule. Nights already under way stay; ended ones are dropped.
152
159
  live = ->(event) { event["occurrences"].select { |o| Time.parse(o["start"]) <= @now + MARGIN && Time.parse(o["end"]) > @now } }
160
+ shows = {}
153
161
  rules.each do |r|
154
162
  nights = wanted[r[:name]]
155
163
  current = bridge_events.find { _1["id"] == @state["events"][r[:name]] }
156
- kept = current ? live.(current).map { [Time.parse(_1["start"]), Time.parse(_1["end"])] } : []
164
+ kept = current ? live.(current).map { [Time.parse(_1["start"]).localtime, Time.parse(_1["end"]).localtime] } : []
157
165
  occurrences = kept + nights
166
+ shows[r[:name]] = occurrences unless occurrences.empty?
158
167
  flags = r[:start][:dusk] ? ["StartAtDusk"] : []
159
168
  if current.nil?
160
169
  next if nights.empty?
@@ -203,7 +212,7 @@ module Everlights
203
212
  end
204
213
  end
205
214
 
206
- Plan.new(actions, skips, horizon, self)
215
+ Plan.new(actions, skips, horizon, self, shows)
207
216
  end
208
217
 
209
218
  def apply(plan)
@@ -0,0 +1,854 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>EverLights schedule</title>
7
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 16 16%22%3E%3Ccircle cx=%228%22 cy=%228%22 r=%226%22 fill=%22%23ffb547%22/%3E%3C/svg%3E">
8
+ <link rel="preconnect" href="https://fonts.googleapis.com">
9
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
+ <link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,400;12..96,500;12..96,700&display=swap" rel="stylesheet">
11
+ <style>
12
+ :root {
13
+ --dusk: #1c2340; /* page: the sky when shows start */
14
+ --night: #141a30; /* panels */
15
+ --wire: #3b4373; /* lines, unlit bulbs */
16
+ --frost: #ecebf6; /* text */
17
+ --haze: #a3a6cc; /* secondary text */
18
+ --ember: #ffb547; /* the one action color: apply */
19
+ --alarm: #ff8a80;
20
+ color-scheme: dark;
21
+ }
22
+ * { box-sizing: border-box; }
23
+ [hidden] { display: none !important; }
24
+ body {
25
+ margin: 0; background: var(--dusk); color: var(--frost);
26
+ font: 15px/1.45 "Bricolage Grotesque", system-ui, sans-serif; font-variant-numeric: tabular-nums;
27
+ }
28
+ button, input, select { font: inherit; color: inherit; }
29
+ :focus-visible { outline: 2px solid var(--ember); outline-offset: 2px; }
30
+ .muted { color: var(--haze); }
31
+
32
+ header {
33
+ position: sticky; top: 0; z-index: 5; display: flex; flex-wrap: wrap; gap: 12px 24px; align-items: center;
34
+ padding: 14px clamp(16px, 4vw, 40px); background: color-mix(in srgb, var(--dusk) 88%, transparent);
35
+ backdrop-filter: blur(8px); border-bottom: 1px solid var(--wire);
36
+ }
37
+ h1 { font-size: 22px; font-weight: 700; margin: 0; letter-spacing: -.01em; }
38
+ h1 small { font-weight: 400; font-size: 14px; color: var(--haze); margin-left: 8px; }
39
+ .status { margin-left: auto; display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
40
+ .status .saved { color: var(--haze); font-size: 13px; }
41
+ .btn { border: 1px solid var(--wire); background: none; border-radius: 6px; padding: 6px 12px; cursor: pointer; }
42
+ .btn:hover { border-color: var(--haze); }
43
+ .previewing { display: flex; gap: 10px; align-items: center; font-size: 14px; }
44
+ .previewing::before { content: ""; width: 9px; height: 9px; border-radius: 50%; background: var(--ember); box-shadow: 0 0 8px var(--ember); }
45
+ .apply { background: var(--ember); color: #2a1a00; border-color: var(--ember); font-weight: 700; }
46
+ .apply:disabled { background: none; color: var(--haze); border-color: var(--wire); font-weight: 400; cursor: default; }
47
+ .review { width: 100%; margin: 0; padding: 10px 0 0; list-style: none; font-size: 14px; display: grid; gap: 2px; }
48
+ .review b { display: inline-block; width: 64px; font-weight: 500; }
49
+ .op-create b { color: #9be89b; } .op-delete b { color: var(--alarm); } .op-update b { color: var(--ember); }
50
+ .problems { width: 100%; color: var(--alarm); margin: 0; padding-left: 18px; font-size: 14px; }
51
+
52
+ main { padding: 24px clamp(16px, 4vw, 40px) 80px; max-width: 1400px; margin: 0 auto; }
53
+ h2 { font-size: 17px; font-weight: 500; margin: 0 0 4px; }
54
+ h2 + p { margin: 0 0 14px; color: var(--haze); font-size: 14px; }
55
+
56
+ /* The calendar: each month is a light string, each night a bulb lit with that night's sequence. */
57
+ .strings { overflow-x: auto; padding-bottom: 4px; }
58
+ .string { display: grid; grid-template-columns: 76px repeat(31, 22px); align-items: center; height: 30px; min-width: max-content; position: relative; }
59
+ .string::before { content: ""; position: absolute; left: 76px; right: 0; top: 50%; border-top: 1px solid var(--wire); }
60
+ .string .m { color: var(--haze); font-size: 13px; }
61
+ .bulb {
62
+ width: 13px; height: 13px; border-radius: 50%; justify-self: center; position: relative; z-index: 1;
63
+ border: 1px solid var(--wire); background: var(--dusk); cursor: pointer; transition: opacity .15s;
64
+ }
65
+ .bulb.lit { border: 0; box-shadow: 0 0 9px -1px var(--glow); }
66
+ .bulb.note { background: repeating-linear-gradient(45deg, var(--wire) 0 2px, var(--dusk) 2px 4px); }
67
+ .bulb.today { outline: 1px solid var(--frost); outline-offset: 3px; }
68
+ .bulb.weekend { width: 15px; height: 15px; }
69
+ .strings.focus .bulb:not(.hit) { opacity: .18; }
70
+ .readout { min-height: 22px; font-size: 14px; margin: 8px 0 0; }
71
+
72
+ .cols { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); gap: 40px; margin-top: 36px; }
73
+ @media (max-width: 900px) { .cols { grid-template-columns: 1fr; } }
74
+ .toolbar { display: flex; gap: 8px; align-items: baseline; margin-bottom: 12px; }
75
+ .toolbar h2 { margin-right: auto; }
76
+
77
+ /* Rules */
78
+ .rules { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
79
+ .rule { background: var(--night); border: 1px solid transparent; border-radius: 8px; }
80
+ .rule.drop-before { box-shadow: 0 -3px 0 var(--ember); }
81
+ .rule.drop-after { box-shadow: 0 3px 0 var(--ember); }
82
+ .rule.dragging { opacity: .4; }
83
+ .rule.open { border-color: var(--wire); }
84
+ .rule-head { display: grid; grid-template-columns: 24px 1fr auto; gap: 8px; align-items: center; padding: 8px 10px 8px 4px; }
85
+ .grip { cursor: grab; border: 0; background: none; color: var(--haze); padding: 4px; line-height: 1; letter-spacing: -2px; }
86
+ .rule-title { border: 0; background: none; text-align: left; padding: 0; cursor: pointer; }
87
+ .rule-title strong { font-weight: 500; }
88
+ .rule-title span { color: var(--haze); font-size: 13px; margin-left: 8px; }
89
+ .rule-body { padding: 4px 14px 14px 36px; display: grid; gap: 10px; }
90
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; min-height: 30px; padding: 0 10px 8px 36px; }
91
+ .rule.open .chips { padding-bottom: 0; }
92
+ .rule.over { border-color: var(--ember); border-style: dashed; }
93
+ .chip {
94
+ display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--wire); border-radius: 999px;
95
+ padding: 2px 4px 2px 3px; font-size: 13px; cursor: grab; background: var(--dusk);
96
+ }
97
+ .chip .sw { width: 22px; height: 14px; border-radius: 999px; }
98
+ .chip input { width: 3.2em; border: 0; background: none; color: var(--haze); text-align: right; padding: 0; }
99
+ .chip .x { border: 0; background: none; color: var(--haze); cursor: pointer; padding: 0 4px; }
100
+ .add-seq { border: 1px dashed var(--wire); border-radius: 999px; background: none; padding: 2px 10px; width: 150px; font-size: 13px; }
101
+ .field { display: grid; grid-template-columns: 70px 1fr; gap: 8px; align-items: center; font-size: 14px; }
102
+ .field > span { color: var(--haze); }
103
+ .field input[type=text], .field select, .seq-name {
104
+ background: var(--dusk); border: 1px solid var(--wire); border-radius: 6px; padding: 5px 8px; width: 100%;
105
+ }
106
+ .pair { display: flex; gap: 8px; align-items: center; }
107
+ .days { display: flex; gap: 4px; flex-wrap: wrap; }
108
+ .days label { position: relative; }
109
+ .days input { position: absolute; opacity: 0; }
110
+ .days span { display: inline-block; padding: 3px 8px; border: 1px solid var(--wire); border-radius: 6px; font-size: 13px; cursor: pointer; }
111
+ .days input:checked + span { background: var(--wire); }
112
+ .days input:focus-visible + span { outline: 2px solid var(--ember); }
113
+ .remove { justify-self: start; border: 0; background: none; color: var(--alarm); cursor: pointer; padding: 0; font-size: 13px; }
114
+
115
+ /* Sequences */
116
+ .seqs { display: grid; gap: 10px; }
117
+ .seq { background: var(--night); border-radius: 8px; padding: 12px; display: grid; gap: 10px; }
118
+ .seq-top { display: flex; gap: 8px; align-items: center; }
119
+ .seq-name { font-weight: 500; }
120
+ .bulbs { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
121
+ .swatch { position: relative; }
122
+ .swatch input { width: 28px; height: 28px; padding: 0; border: 0; border-radius: 50%; background: none; cursor: pointer; }
123
+ .swatch input::-webkit-color-swatch-wrapper { padding: 0; }
124
+ .swatch input::-webkit-color-swatch { border: 0; border-radius: 50%; }
125
+ .swatch input::-moz-color-swatch { border: 0; border-radius: 50%; }
126
+ .swatch .x { position: absolute; top: -6px; right: -6px; width: 16px; height: 16px; border-radius: 50%; border: 0; padding: 0;
127
+ font-size: 11px; line-height: 16px; background: var(--wire); cursor: pointer; display: none; }
128
+ .swatch:hover .x, .swatch:focus-within .x { display: block; }
129
+ .plus { width: 28px; height: 28px; border-radius: 50%; border: 1px dashed var(--wire); background: none; cursor: pointer; color: var(--haze); }
130
+ .fx { display: grid; grid-template-columns: 120px 1fr 34px 20px; gap: 8px; align-items: center; font-size: 14px; }
131
+ .fx select { background: var(--dusk); border: 1px solid var(--wire); border-radius: 6px; padding: 3px 6px; }
132
+ .fx input[type=range] { accent-color: var(--ember); }
133
+ .fx .x { border: 0; background: none; color: var(--haze); cursor: pointer; }
134
+ .seqs.cards { grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); align-items: start; }
135
+ .seq-actions { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
136
+ .seq-actions .btn { padding: 4px 10px; font-size: 14px; }
137
+ .btn.save { border-color: var(--ember); color: var(--ember); }
138
+ .btn:disabled { opacity: .45; cursor: default; }
139
+ .dirty { color: var(--ember); font-size: 13px; }
140
+ .readonly .bulbs span { width: 22px; height: 22px; border-radius: 50%; }
141
+ .palette { margin-top: 28px; }
142
+ .palette input[type=search] { background: var(--night); border: 1px solid var(--wire); border-radius: 6px; padding: 5px 8px; width: 100%; margin-bottom: 10px; }
143
+ .palette .chips { padding: 0; }
144
+ aside .chips { max-height: 60vh; overflow-y: auto; }
145
+ .chip.on { border-color: var(--ember); }
146
+
147
+ /* Views */
148
+ .tabs { display: flex; gap: 4px; }
149
+ .tabs a { color: var(--haze); text-decoration: none; padding: 5px 12px; border-radius: 6px; }
150
+ .tabs a[aria-current=page] { color: var(--frost); background: var(--night); }
151
+ body:not([data-view=sequences]) #view-sequences, body:not([data-view=bridge]) #view-bridge,
152
+ body:not([data-view=calendar]) #view-calendar { display: none; }
153
+
154
+ /* Bridge */
155
+ .checks { list-style: none; margin: 0 0 32px; padding: 0; display: grid; gap: 6px; }
156
+ .checks li { display: grid; grid-template-columns: 14px 170px 1fr; gap: 10px; align-items: baseline; }
157
+ .checks li::before { content: ""; width: 9px; height: 9px; border-radius: 50%; border: 1px solid var(--wire); align-self: center; }
158
+ .checks .ok::before { background: #9be89b; border: 0; box-shadow: 0 0 7px #9be89b; }
159
+ .checks .warn::before { background: var(--alarm); border: 0; box-shadow: 0 0 7px var(--alarm); }
160
+ .checks .warn { color: var(--alarm); }
161
+ .panels { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 16px; align-items: start; }
162
+ .panel { background: var(--night); border-radius: 8px; padding: 14px 16px; }
163
+ .panel h3 { font-size: 15px; font-weight: 500; margin: 0 0 10px; }
164
+ .panel dl { display: grid; grid-template-columns: 130px 1fr; gap: 4px 12px; margin: 0; font-size: 14px; }
165
+ .panel dt { color: var(--haze); }
166
+ .panel dd { margin: 0; }
167
+ .actions { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
168
+ .btn.danger { border-color: var(--alarm); color: var(--alarm); }
169
+ details { margin-top: 24px; font-size: 13px; }
170
+ details pre { background: var(--night); padding: 12px; border-radius: 8px; overflow-x: auto; }
171
+
172
+ /* Hover card for any sequence chip */
173
+ .pop {
174
+ position: absolute; z-index: 10; width: min(380px, calc(100vw - 32px)); background: var(--night);
175
+ border: 1px solid var(--wire); border-radius: 10px; box-shadow: 0 12px 32px rgb(5 8 20 / .55);
176
+ }
177
+ .pop .seq { background: none; }
178
+ .error { color: var(--alarm); }
179
+ @media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
180
+ </style>
181
+ </head>
182
+ <body>
183
+ <header>
184
+ <h1>EverLights <small id="where"></small></h1>
185
+ <nav class="tabs" aria-label="Views"><a href="#calendar" id="tab-calendar">Calendar</a><a href="#sequences" id="tab-sequences">Sequences</a><a href="#bridge" id="tab-bridge">Bridge</a></nav>
186
+ <div class="status">
187
+ <span class="previewing" id="previewing" hidden><span id="preview-name"></span> is on the lights <button class="btn" id="stop-preview">Stop preview</button></span>
188
+ <span class="saved" id="saved" aria-live="polite">Reading the bridge…</span>
189
+ <button class="btn" id="review-btn" aria-expanded="false" hidden>Review</button>
190
+ <button class="btn apply" id="apply" disabled>Apply</button>
191
+ </div>
192
+ <ul class="review" id="review" hidden></ul>
193
+ <ul class="problems" id="problems" hidden></ul>
194
+ </header>
195
+
196
+ <main>
197
+ <div id="view-calendar">
198
+ <section aria-labelledby="cal-h">
199
+ <h2 id="cal-h">Nights ahead</h2>
200
+ <p>Each bulb is one night, lit with the sequence that plays. Striped bulbs have no show; hover for why.</p>
201
+ <div class="strings" id="strings"></div>
202
+ <p class="readout" id="readout" aria-live="polite"></p>
203
+ </section>
204
+
205
+ <div class="cols">
206
+ <section aria-labelledby="rules-h">
207
+ <div class="toolbar"><h2 id="rules-h">Schedule</h2><button class="btn" id="new-rule">New rule</button></div>
208
+ <p class="muted" style="margin:-6px 0 14px;font-size:14px">Higher rules win shared nights. Drag the handle to reorder, or focus it and use the arrow keys. Drag sequences onto a rule to add them; hover one to see, edit or preview it.</p>
209
+ <ol class="rules" id="rules"></ol>
210
+ </section>
211
+ <aside class="palette" style="margin-top:0" aria-labelledby="side-h">
212
+ <h2 id="side-h">Sequences</h2>
213
+ <p>Yours first, then the bridge's.</p>
214
+ <input type="search" id="side-filter" placeholder="Filter" aria-label="Filter sequences">
215
+ <div class="chips" id="side"></div>
216
+ </aside>
217
+ </div>
218
+ </div>
219
+
220
+ <div id="view-sequences">
221
+ <div class="toolbar"><h2>Your sequences</h2><button class="btn" id="new-seq">New sequence</button></div>
222
+ <div class="seqs cards" id="seqs"></div>
223
+ <div class="palette">
224
+ <h2>On the bridge</h2>
225
+ <p>Built-ins and app-made sequences. Hover one to preview it or copy it into yours.</p>
226
+ <input type="search" id="filter" placeholder="Filter" aria-label="Filter bridge sequences">
227
+ <div class="chips" id="palette"></div>
228
+ </div>
229
+ </div>
230
+
231
+ <div id="view-bridge">
232
+ <div class="toolbar">
233
+ <h2>Health</h2>
234
+ <div class="actions">
235
+ <span class="muted" id="bridge-at" aria-live="polite"></span>
236
+ <button class="btn" id="bridge-refresh">Refresh</button>
237
+ <button class="btn" id="bridge-time" title="The bridge normally keeps time over NTP">Set clock to now</button>
238
+ <button class="btn danger" id="bridge-reboot">Reboot</button>
239
+ </div>
240
+ </div>
241
+ <ul class="checks" id="checks"></ul>
242
+ <div class="panels" id="panels"></div>
243
+ <details><summary class="muted">Everything the bridge reports</summary><pre id="raw"></pre></details>
244
+ </div>
245
+ </main>
246
+ <div class="pop" id="pop" role="dialog" aria-label="Sequence" hidden></div>
247
+ <datalist id="seq-names"></datalist>
248
+
249
+ <script>
250
+ const $ = (id) => document.getElementById(id);
251
+ const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
252
+ let S = null; // last state from the server
253
+ let cfg = null; // the config being edited
254
+ let open = new Set(); // expanded rule names
255
+
256
+ function el(tag, attrs = {}, ...kids) {
257
+ const n = document.createElement(tag);
258
+ for (const [k, v] of Object.entries(attrs)) {
259
+ if (v == null || v === false) continue;
260
+ if (k.startsWith("on")) n.addEventListener(k.slice(2), v);
261
+ else if (k === "style") n.style.cssText = v;
262
+ else if (k in n && k !== "list") n[k] = v;
263
+ else n.setAttribute(k, v === true ? "" : v);
264
+ }
265
+ n.append(...kids.flat().filter((k) => k != null && k !== false));
266
+ return n;
267
+ }
268
+
269
+ // --- sequences and colors ---
270
+ const parseRef = (ref) => { const m = String(ref).match(/^(.*?):(\d+)$/); return m ? [m[1].trim(), m[2]] : [String(ref).trim(), ""]; };
271
+ function colorsOf(name) {
272
+ const lower = name.toLowerCase();
273
+ const own = Object.entries(cfg.sequences || {}).find(([n]) => n.toLowerCase() === lower);
274
+ if (own) return (own[1]?.colors || []).map(String);
275
+ return S.bridge_sequences.find((s) => s.name.toLowerCase() === lower)?.colors || [];
276
+ }
277
+ const hex = (c) => "#" + String(c).replace(/^#/, "");
278
+ function stripe(colors) {
279
+ if (!colors.length) return "transparent";
280
+ if (colors.length === 1) return hex(colors[0]);
281
+ const w = 100 / colors.length;
282
+ return `linear-gradient(90deg, ${colors.map((c, i) => `${hex(c)} ${i * w}% ${(i + 1) * w}%`).join(", ")})`;
283
+ }
284
+ function wheel(colors) {
285
+ if (colors.length < 2) return hex(colors[0] || "000000");
286
+ const w = 360 / colors.length;
287
+ return `conic-gradient(${colors.map((c, i) => `${hex(c)} ${i * w}deg ${(i + 1) * w}deg`).join(", ")})`;
288
+ }
289
+ const ruleColors = (rule) => colorsOf(parseRef((rule?.sequences || [])[0] || "")[0]);
290
+
291
+ // --- the calendar ---
292
+ const fmtDay = (d) => d.toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric" });
293
+ function renderStrings() {
294
+ const box = $("strings"); box.replaceChildren();
295
+ const today = new Date(S.today + "T12:00");
296
+ const last = new Date(today); last.setDate(last.getDate() + S.horizon);
297
+ const rules = Object.fromEntries((cfg.schedule || []).map((r) => [r.name, r]));
298
+ for (let m = new Date(today.getFullYear(), today.getMonth(), 1); m <= last; m.setMonth(m.getMonth() + 1)) {
299
+ const row = el("div", { className: "string" }, el("span", { className: "m" }, m.toLocaleDateString(undefined, m.getMonth() === 0 || +m === +new Date(today.getFullYear(), today.getMonth(), 1) ? { month: "short", year: "numeric" } : { month: "short" })));
300
+ const days = new Date(m.getFullYear(), m.getMonth() + 1, 0).getDate();
301
+ for (let d = 1; d <= days; d++) {
302
+ const date = new Date(m.getFullYear(), m.getMonth(), d, 12);
303
+ const iso = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
304
+ if (date < today || date > last) { row.append(el("span")); continue; }
305
+ const n = S.nights?.[iso];
306
+ const colors = n && !n.note ? ruleColors(rules[n.rule]) : [];
307
+ const text = !n ? `${fmtDay(date)}: no rule` : n.note ? `${fmtDay(date)}: ${n.rule}, no show (${n.note})`
308
+ : `${fmtDay(date)}: ${n.rule}, ${n.start}–${n.end}${rules[n.rule] ? ", " + rules[n.rule].sequences.map((s) => parseRef(s)[0]).join(", ") : ""}`;
309
+ const bulb = el("span", {
310
+ className: `bulb${colors.length ? " lit" : ""}${n?.note ? " note" : ""}${iso === S.today ? " today" : ""}${[0, 6].includes(date.getDay()) ? " weekend" : ""}`,
311
+ title: text, "data-rule": n?.rule,
312
+ onmouseenter: () => ($("readout").textContent = text),
313
+ onclick: () => n && focusRule(n.rule),
314
+ });
315
+ if (colors.length) { bulb.style.background = wheel(colors); bulb.style.setProperty("--glow", hex(colors[0])); }
316
+ row.append(bulb);
317
+ }
318
+ box.append(row);
319
+ }
320
+ }
321
+ function highlight(name) {
322
+ $("strings").classList.toggle("focus", !!name);
323
+ for (const b of $("strings").querySelectorAll(".bulb")) b.classList.toggle("hit", b.dataset.rule === name);
324
+ }
325
+ function focusRule(name) {
326
+ open.add(name); renderRules();
327
+ document.querySelector(`[data-name="${CSS.escape(name)}"]`)?.scrollIntoView({ behavior: "smooth", block: "center" });
328
+ }
329
+
330
+ // --- rules ---
331
+ function when(r) {
332
+ if (r.on != null) return String(r.on);
333
+ const span = r.from != null ? `${r.from} to ${r.to}` : "all year";
334
+ const ev = r.every ? [].concat(r.every) : null;
335
+ return ev && ev.length < 7 ? `${ev.join(", ")}, ${span}` : `nightly, ${span}`;
336
+ }
337
+ function times(r) {
338
+ const d = cfg.defaults || {};
339
+ return `${r.start ?? d.start ?? "dusk"}–${r.end ?? d.end ?? "23:00"}`;
340
+ }
341
+ let drag = null; // {type: "rule", i} | {type: "seq", name, from?: [ruleIndex, chipIndex]}
342
+
343
+ function chip(ref, ri, ci) {
344
+ const [name, secs] = parseRef(ref);
345
+ const r = cfg.schedule[ri];
346
+ return el("span", {
347
+ className: "chip", draggable: true, "data-ci": ci, "data-pop": name, tabindex: 0,
348
+ // r.sequences[ci], not ref: the seconds may have changed since this chip was drawn
349
+ ondragstart: (e) => { drag = { type: "seq", name: r.sequences[ci], from: [ri, ci] }; e.dataTransfer.setData("text/plain", name); e.stopPropagation(); closePop(); },
350
+ },
351
+ el("span", { className: "sw", style: `background:${stripe(colorsOf(name))}` }),
352
+ name,
353
+ el("input", { type: "number", min: 1, value: secs, placeholder: String(cfg.defaults?.seconds ?? 20), "aria-label": `${name} seconds`,
354
+ title: "Seconds per pass; blank uses the default",
355
+ onchange: (e) => { r.sequences[ci] = e.target.value ? `${name}:${e.target.value}` : name; save(); } }),
356
+ el("button", { className: "x", "aria-label": `Remove ${name} from ${r.name}`, onclick: () => { r.sequences.splice(ci, 1); save(true); } }, "×"),
357
+ );
358
+ }
359
+
360
+ function chipZone(r, ri) {
361
+ return el("div", { className: "chips" }, (r.sequences || []).map((ref, ci) => chip(ref, ri, ci)),
362
+ el("input", { className: "add-seq", list: "seq-names", placeholder: "Add sequence", "aria-label": `Add a sequence to ${r.name}`,
363
+ onchange: (e) => { const v = e.target.value.trim(); if (v) { (r.sequences ||= []).push(v); save(true); } } }));
364
+ }
365
+
366
+ // a sequence dropped anywhere on a rule: before the chip it lands on, else at the end
367
+ function dropSeq(e, r, ri) {
368
+ const target = e.target.closest(".chip[data-ci]");
369
+ let at = target ? +target.dataset.ci : (r.sequences || []).length;
370
+ if (drag.from) {
371
+ const [fr, fc] = drag.from;
372
+ cfg.schedule[fr].sequences.splice(fc, 1);
373
+ if (fr === ri && fc < at) at--;
374
+ }
375
+ (r.sequences ||= []).splice(at, 0, drag.name);
376
+ drag = null; save(true);
377
+ }
378
+
379
+ function field(label, ...kids) { return el("label", { className: "field" }, el("span", {}, label), ...kids); }
380
+ function text(obj, key, attrs = {}) {
381
+ return el("input", { type: "text", value: obj[key] ?? "", ...attrs,
382
+ onchange: (e) => { const v = e.target.value.trim(); v ? (obj[key] = v) : delete obj[key]; save(); } });
383
+ }
384
+
385
+ function ruleBody(r, ri) {
386
+ const once = r.on != null;
387
+ const every = r.every ? [].concat(r.every).map((d) => DAYS.find((x) => x.toLowerCase() === String(d).slice(0, 3).toLowerCase())) : DAYS;
388
+ const setDays = (days) => {
389
+ if (days.length === 7 && r.from != null) delete r.every; else r.every = days;
390
+ save();
391
+ };
392
+ const d = cfg.defaults || {};
393
+ return el("div", { className: "rule-body" },
394
+ field("Name", el("input", { type: "text", value: r.name, onchange: (e) => {
395
+ const was = r.name; r.name = e.target.value.trim() || was;
396
+ if (open.delete(was)) open.add(r.name);
397
+ save(true);
398
+ } })),
399
+ field("When", el("select", { onchange: (e) => {
400
+ if (e.target.value === "on") { delete r.from; delete r.to; delete r.every; r.on = "Dec 25"; }
401
+ else { delete r.on; r.every = DAYS.slice(); }
402
+ save(true);
403
+ } }, el("option", { value: "on", selected: once }, "One night a year"), el("option", { value: "span", selected: !once }, "Several nights"))),
404
+ once ? field("Date", text(r, "on", { placeholder: "Dec 25, Easter-2, 4th Thursday of November" }))
405
+ : [
406
+ field("From", el("div", { className: "pair" },
407
+ text(r, "from", { placeholder: "Dec 1", "aria-label": "From" }), el("span", { className: "muted" }, "to"),
408
+ text(r, "to", { placeholder: "Jan 6", "aria-label": "To" }))),
409
+ el("div", { className: "field" }, el("span", {}, "Nights"), el("div", { className: "days" }, DAYS.map((day) =>
410
+ el("label", {}, el("input", { type: "checkbox", checked: every.includes(day),
411
+ // read the boxes, not `every`: a save that keeps focus doesn't redraw this rule
412
+ onchange: (e) => { const boxes = e.target.closest(".days").querySelectorAll("input"); setDays(DAYS.filter((_, i) => boxes[i].checked)); } }), el("span", {}, day))))),
413
+ ],
414
+ field("Starts", text(r, "start", { placeholder: `${d.start ?? "dusk"} (default); dusk+15 or 18:30` })),
415
+ field("Ends", text(r, "end", { placeholder: `${d.end ?? "23:00"} (default)` })),
416
+ el("button", { className: "remove", onclick: () => { cfg.schedule.splice(ri, 1); save(true); } }, `Remove ${r.name}`),
417
+ );
418
+ }
419
+
420
+ function moveRule(from, to) {
421
+ const [r] = cfg.schedule.splice(from, 1);
422
+ cfg.schedule.splice(to, 0, r);
423
+ save(true);
424
+ requestAnimationFrame(() => document.querySelector(`[data-name="${CSS.escape(r.name)}"] .grip`)?.focus());
425
+ }
426
+
427
+ function renderRules() {
428
+ const list = $("rules");
429
+ list.replaceChildren(...(cfg.schedule || []).map((r, ri) => {
430
+ const isOpen = open.has(r.name);
431
+ const li = el("li", { className: `rule${isOpen ? " open" : ""}`, "data-name": r.name,
432
+ onmouseenter: () => highlight(r.name), onmouseleave: () => highlight(null),
433
+ ondragover: (e) => {
434
+ if (drag?.type === "seq") { e.preventDefault(); li.classList.add("over"); return; }
435
+ if (drag?.type !== "rule") return;
436
+ e.preventDefault();
437
+ const box = li.getBoundingClientRect(), after = e.clientY > box.top + box.height / 2;
438
+ li.classList.toggle("drop-after", after); li.classList.toggle("drop-before", !after);
439
+ },
440
+ ondragleave: (e) => { if (!li.contains(e.relatedTarget)) li.classList.remove("drop-before", "drop-after", "over"); },
441
+ ondrop: (e) => {
442
+ li.classList.remove("over");
443
+ if (drag?.type === "seq") { e.preventDefault(); return dropSeq(e, r, ri); }
444
+ if (drag?.type !== "rule") return;
445
+ e.preventDefault();
446
+ const after = li.classList.contains("drop-after");
447
+ li.classList.remove("drop-before", "drop-after");
448
+ let to = ri + (after ? 1 : 0);
449
+ if (drag.i < to) to--;
450
+ if (to !== drag.i) moveRule(drag.i, to);
451
+ drag = null;
452
+ },
453
+ },
454
+ el("div", { className: "rule-head" },
455
+ el("button", { className: "grip", draggable: true, "aria-label": `Move ${r.name}; arrow keys reorder`, title: "Drag to reorder",
456
+ ondragstart: (e) => { drag = { type: "rule", i: ri }; e.dataTransfer.setData("text/plain", r.name); li.classList.add("dragging"); },
457
+ ondragend: () => li.classList.remove("dragging"),
458
+ onkeydown: (e) => {
459
+ if (e.key === "ArrowUp" && ri > 0) { e.preventDefault(); moveRule(ri, ri - 1); }
460
+ if (e.key === "ArrowDown" && ri < cfg.schedule.length - 1) { e.preventDefault(); moveRule(ri, ri + 1); }
461
+ } }, "⋮⋮"),
462
+ el("button", { className: "rule-title", "aria-expanded": String(isOpen),
463
+ onclick: () => { isOpen ? open.delete(r.name) : open.add(r.name); renderRules(); } },
464
+ el("strong", {}, r.name), el("span", {}, `${when(r)}, ${times(r)}`)),
465
+ el("span", { className: "sw", "aria-hidden": "true", style: `width:22px;height:14px;border-radius:999px;background:${stripe(ruleColors(r))}` }),
466
+ ),
467
+ chipZone(r, ri),
468
+ isOpen && ruleBody(r, ri),
469
+ );
470
+ return li;
471
+ }));
472
+ }
473
+
474
+ // --- sequences: one editor for the cards and the hover card. Edits are a draft until Save. ---
475
+ const drafts = new Map(); // name -> {name, colors, effects}
476
+ const own = (name) => Object.keys(cfg.sequences).find((n) => n.toLowerCase() === name.toLowerCase());
477
+ const bridgeSeq = (name) => S.bridge_sequences.find((s) => s.name.toLowerCase() === name.toLowerCase());
478
+ const asSpec = (d) => ({ colors: d.colors, ...(Object.keys(d.effects || {}).length ? { effects: d.effects } : {}) });
479
+ const savedDraft = (name) => { const s = cfg.sequences[name] || {}; return { name, colors: [...(s.colors || [])], effects: { ...(s.effects || {}) } }; }; // `Name:` with no value is null
480
+ const draftOf = (name) => drafts.get(name) || savedDraft(name);
481
+ const isDirty = (name) => drafts.has(name) && JSON.stringify(drafts.get(name)) !== JSON.stringify(savedDraft(name));
482
+
483
+ function renameSeq(old, name) {
484
+ if (!name || name === old) return;
485
+ cfg.sequences = Object.fromEntries(Object.entries(cfg.sequences).map(([k, v]) => [k === old ? name : k, v]));
486
+ for (const r of cfg.schedule || []) {
487
+ r.sequences = (r.sequences || []).map((ref) => {
488
+ const [n, secs] = parseRef(ref);
489
+ return n.toLowerCase() === old.toLowerCase() ? (secs ? `${name}:${secs}` : name) : ref;
490
+ });
491
+ }
492
+ }
493
+
494
+ function saveSeq(name) {
495
+ const d = drafts.get(name);
496
+ if (!d) return;
497
+ const to = d.name.trim() || name;
498
+ if (to !== name && own(to)) return renderStatus(`There's already a sequence called ${to}`);
499
+ cfg.sequences[name] = asSpec(d);
500
+ renameSeq(name, to);
501
+ drafts.delete(name);
502
+ if (preview?.name === name) preview.name = to;
503
+ if (pop.name === name) pop.name = to;
504
+ save(true);
505
+ }
506
+
507
+ function previewButton(name, spec, isOwn) {
508
+ const on = preview?.name === name;
509
+ return el("button", { className: "btn", "aria-pressed": String(on), onclick: () => (on ? stopPreview() : startPreview(name, spec, isOwn)) },
510
+ on ? "Stop preview" : "Preview");
511
+ }
512
+
513
+ // an own sequence; redraws itself in place as the draft changes
514
+ function seqEditor(name, { card = false } = {}) {
515
+ const d = draftOf(name);
516
+ const box = el("div", { className: "seq", "data-seq": name });
517
+ const changed = (redraw = true) => {
518
+ drafts.set(name, d);
519
+ if (preview?.name === name && preview.sent !== JSON.stringify(asSpec(d))) startPreview(name, asSpec(d)); // edits show on the lights
520
+ if (redraw) box.replaceWith(seqEditor(name, { card }));
521
+ };
522
+ const fx = Object.entries(d.effects);
523
+ const setFx = () => { d.effects = Object.fromEntries(fx); changed(); };
524
+ const dirty = isDirty(name);
525
+ box.append(...[
526
+ el("div", { className: "seq-top" },
527
+ el("span", { className: "chip", draggable: true, title: "Drag onto a rule", "aria-hidden": "true",
528
+ ondragstart: (e) => { drag = { type: "seq", name }; e.dataTransfer.setData("text/plain", name); closePop(); } },
529
+ el("span", { className: "sw", style: `background:${stripe(d.colors)}` })),
530
+ el("input", { className: "seq-name", type: "text", value: d.name, "aria-label": "Sequence name",
531
+ onchange: (e) => { d.name = e.target.value; changed(); } }),
532
+ ),
533
+ el("div", { className: "bulbs" },
534
+ d.colors.map((c, i) => el("span", { className: "swatch" },
535
+ el("input", { type: "color", value: hex(c).toLowerCase(), "aria-label": `${name} color ${i + 1}`,
536
+ oninput: (e) => { d.colors[i] = e.target.value.slice(1).toUpperCase(); box.querySelector(".sw").style.background = stripe(d.colors); },
537
+ onchange: (e) => { d.colors[i] = e.target.value.slice(1).toUpperCase(); changed(); } }),
538
+ d.colors.length > 1 && el("button", { className: "x", "aria-label": `Remove ${name} color ${i + 1}`,
539
+ onclick: () => { d.colors.splice(i, 1); changed(); } }, "×"))),
540
+ el("button", { className: "plus", "aria-label": `Add a color to ${name}`, title: "Add a color",
541
+ onclick: () => { d.colors.push(d.colors.at(-1) || "FFFFFF"); changed(); } }, "+"),
542
+ ),
543
+ fx.map(([type, value], i) => el("div", { className: "fx" },
544
+ el("select", { "aria-label": "Effect", onchange: (e) => { fx[i][0] = e.target.value; setFx(); } },
545
+ S.effects.map((t) => el("option", { value: t, selected: t === type }, t))),
546
+ el("input", { type: "range", min: 0, max: 255, value, "aria-label": `${type} strength`,
547
+ oninput: (e) => (e.target.nextSibling.textContent = e.target.value),
548
+ onchange: (e) => { fx[i][1] = +e.target.value; setFx(); } }),
549
+ el("span", { className: "muted" }, String(value)),
550
+ el("button", { className: "x", "aria-label": `Remove ${type}`, onclick: () => { fx.splice(i, 1); setFx(); } }, "×"),
551
+ )),
552
+ el("button", { className: "remove", style: "color:var(--haze)",
553
+ onclick: () => { const t = S.effects.find((t) => !fx.some(([x]) => x === t)); if (t) { fx.push([t, 128]); setFx(); } } }, "Add effect"),
554
+ el("div", { className: "seq-actions" },
555
+ el("button", { className: "btn save", disabled: !dirty, onclick: () => saveSeq(name) }, "Save"),
556
+ dirty && el("button", { className: "btn", onclick: () => { drafts.delete(name); box.replaceWith(seqEditor(name, { card })); } }, "Revert"),
557
+ previewButton(name, asSpec(d), true),
558
+ dirty && el("span", { className: "dirty" }, "Not saved"),
559
+ card && el("button", { className: "btn", style: "margin-left:auto", onclick: () => { delete cfg.sequences[name]; drafts.delete(name); save(true); } }, "Delete"),
560
+ ),
561
+ ].flat());
562
+ return box;
563
+ }
564
+
565
+ // a bridge sequence: look, preview, or copy into yours
566
+ function bridgeCard(s) {
567
+ const effects = Object.fromEntries((s.effects || []).map((e) => [e.effectType, e.value]));
568
+ return el("div", { className: "seq readonly" },
569
+ el("div", { className: "seq-top" }, el("strong", {}, s.name), el("span", { className: "muted" }, s.builtin ? "built in" : "made in the app")),
570
+ el("div", { className: "bulbs" }, s.colors.map((c) => el("span", { style: `background:${hex(c)}` }))),
571
+ Object.keys(effects).length ? el("div", { className: "muted" }, Object.entries(effects).map(([t, v]) => `${t} ${v}`).join(", ")) : null,
572
+ el("div", { className: "seq-actions" },
573
+ previewButton(s.name, { colors: s.colors, effects: s.effects }, false),
574
+ el("button", { className: "btn", onclick: () => {
575
+ let name = `${s.name} (mine)`, n = 2;
576
+ while (own(name)) name = `${s.name} (mine ${n++})`;
577
+ cfg.sequences[name] = asSpec({ colors: [...s.colors], effects });
578
+ save(true); openPop(name, pop.anchor, true);
579
+ } }, "Copy to mine")),
580
+ );
581
+ }
582
+
583
+ function renderSeqs() {
584
+ $("seqs").replaceChildren(...Object.keys(cfg.sequences).map((name) => seqEditor(name, { card: true })));
585
+ }
586
+
587
+ // chip for the sidebar and bridge list: drag onto a rule, hover or click for its card
588
+ function seqChip(name, colors) {
589
+ return el("span", { className: `chip${preview?.name === name ? " on" : ""}`, draggable: true, tabindex: 0, "data-pop": name,
590
+ ondragstart: (e) => { drag = { type: "seq", name }; e.dataTransfer.setData("text/plain", name); closePop(); } },
591
+ el("span", { className: "sw", style: `background:${stripe(colors)}` }), name);
592
+ }
593
+
594
+ function renderPalette() {
595
+ const q = $("filter").value.toLowerCase(), sq = $("side-filter").value.toLowerCase();
596
+ const bridge = S.bridge_sequences;
597
+ $("palette").replaceChildren(...bridge.filter((s) => s.name.toLowerCase().includes(q)).map((s) => seqChip(s.name, s.colors)));
598
+ $("side").replaceChildren(
599
+ ...Object.keys(cfg.sequences).filter((n) => n.toLowerCase().includes(sq)).map((n) => seqChip(n, draftOf(n).colors)),
600
+ ...bridge.filter((s) => s.name.toLowerCase().includes(sq)).map((s) => seqChip(s.name, s.colors)));
601
+ $("seq-names").replaceChildren(...[...Object.keys(cfg.sequences), ...bridge.map((s) => s.name)].map((n) => el("option", { value: n })));
602
+ }
603
+
604
+ // --- the hover card: opens on hover (or click / Enter) over any [data-pop] chip; stays while you work in it ---
605
+ const pop = { el: $("pop"), name: null, anchor: null, pinned: false, timer: null };
606
+ function openPop(name, anchor, pinned = false) {
607
+ clearTimeout(pop.timer);
608
+ const mine = own(name), b = !mine && bridgeSeq(name);
609
+ if (!mine && !b) return;
610
+ pop.pinned = pinned || (pop.pinned && pop.name === (mine || name)); // a pinned card unpins when it moves to another sequence
611
+ pop.name = mine || name; pop.anchor = anchor;
612
+ pop.el.replaceChildren(mine ? seqEditor(mine) : bridgeCard(b));
613
+ pop.el.hidden = false;
614
+ if (anchor?.isConnected) {
615
+ const a = anchor.getBoundingClientRect(), w = pop.el.offsetWidth;
616
+ pop.el.style.left = `${Math.max(16, Math.min(a.left, innerWidth - w - 16)) + scrollX}px`;
617
+ pop.el.style.top = `${a.bottom + 6 + scrollY}px`;
618
+ }
619
+ }
620
+ function closePop(force = false) {
621
+ clearTimeout(pop.timer);
622
+ if (!force && (pop.pinned || pop.el.contains(document.activeElement) || (pop.name && isDirty(pop.name)))) return;
623
+ // an unsaved draft stays (the Sequences view shares it); Revert or Save drop it
624
+ pop.el.hidden = true; pop.name = null; pop.pinned = false;
625
+ }
626
+ const later = (fn, ms) => { clearTimeout(pop.timer); pop.timer = setTimeout(fn, ms); };
627
+ document.addEventListener("mouseover", (e) => {
628
+ const chip = e.target.closest("[data-pop]");
629
+ if (chip && !drag) later(() => openPop(chip.dataset.pop, chip), pop.el.hidden ? 350 : 120);
630
+ else if (pop.el.contains(e.target)) clearTimeout(pop.timer);
631
+ else if (!pop.el.hidden) later(() => closePop(), 300);
632
+ });
633
+ document.addEventListener("click", (e) => {
634
+ const chip = e.target.closest("[data-pop]");
635
+ if (chip && !e.target.closest("input, button")) openPop(chip.dataset.pop, chip, true);
636
+ else if (!pop.el.hidden && !pop.el.contains(e.target) && e.target.isConnected) closePop(true);
637
+ });
638
+ document.addEventListener("keydown", (e) => {
639
+ if (e.key === "Escape" && !pop.el.hidden) { const back = pop.anchor; closePop(true); back?.focus?.(); }
640
+ const chip = e.target.closest?.("[data-pop]");
641
+ if (chip && e.target === chip && (e.key === "Enter" || e.key === " ")) {
642
+ e.preventDefault(); openPop(chip.dataset.pop, chip, true); pop.el.querySelector("input, button")?.focus();
643
+ }
644
+ });
645
+ function refreshPop() {
646
+ if (pop.el.hidden || !pop.name) return;
647
+ const anchor = pop.anchor?.isConnected ? pop.anchor : document.querySelector(`[data-pop="${CSS.escape(pop.name)}"]`);
648
+ openPop(pop.name, anchor);
649
+ }
650
+
651
+ // --- status, saving, applying ---
652
+ function renderStatus(msg) {
653
+ const plan = S.plan || [];
654
+ $("where").textContent = S.host ? `bridge ${S.host}` : "";
655
+ $("saved").textContent = msg ?? (S.error ? "" : plan.length ? `${plan.length} change${plan.length === 1 ? "" : "s"} to send to the bridge` : "The bridge matches your schedule");
656
+ $("apply").disabled = !!S.error || !plan.length;
657
+ $("apply").textContent = plan.length ? `Apply ${plan.length}` : "Apply";
658
+ $("review-btn").hidden = !plan.length;
659
+ $("review").replaceChildren(...plan.map((a) => el("li", { className: `op-${a.op}` }, el("b", {}, a.op), `${a.kind === "event" ? "" : "sequence "}${a.name}`, a.detail ? el("span", { className: "muted" }, `: ${a.detail}`) : null)));
660
+ if (!plan.length) { $("review").hidden = true; $("review-btn").setAttribute("aria-expanded", "false"); }
661
+ const problems = S.error ? S.error.replace(/^config problems, nothing applied:\n/, "").split("\n").map((l) => l.replace(/^\s*- /, "")) : [];
662
+ $("problems").hidden = !problems.length;
663
+ $("problems").replaceChildren(...problems.map((p) => el("li", {}, p)));
664
+ }
665
+
666
+ // keep the last good calendar, bridge list and dates while there are problems
667
+ const merge = (state) => {
668
+ for (const k of ["nights", "bridge_sequences", "today", "horizon", "host"]) if (!(k in state)) state[k] = S?.[k];
669
+ state.bridge_sequences ||= [];
670
+ return state;
671
+ };
672
+ function useConfig(c) {
673
+ cfg = c; cfg.sequences ||= {}; cfg.schedule ||= [];
674
+ for (const spec of Object.values(cfg.sequences)) if (spec) spec.colors = (spec.colors || []).map(String);
675
+ }
676
+
677
+ let version = null; // of everlights.yml as last read; a save is refused if the file changed since
678
+ function take(state, msg) {
679
+ S = merge(state);
680
+ if (S.version) version = S.version;
681
+ if (S.config) useConfig(S.config);
682
+ if (!cfg) return renderStatus();
683
+ renderStrings(); renderRules(); renderSeqs(); renderPalette(); renderStatus(msg);
684
+ }
685
+
686
+ let saving = Promise.resolve(), saves = 0;
687
+ function save(structural = false) {
688
+ if (structural) { renderRules(); renderSeqs(); renderPalette(); refreshPop(); }
689
+ $("saved").textContent = "Saving…";
690
+ const body = JSON.stringify(cfg), mine = ++saves;
691
+ saving = saving.then(() => fetch("/api/config", { method: "PUT", headers: { "Content-Type": "application/json", ...(version && { "If-Match": version }) }, body }))
692
+ .then(async (r) => {
693
+ const state = await r.json(), latest = mine === saves;
694
+ if (r.status === 412) { // edited outside the page: show the file; saves queued on the old copy get 412 too
695
+ if (latest) take(state, "everlights.yml changed outside this page, so it was reloaded. Redo your last change.");
696
+ return;
697
+ }
698
+ if (!r.ok) throw new Error(state.error || r.statusText);
699
+ version = state.version;
700
+ if (!latest) return; // a newer save is queued; drawing this answer would undo it on screen
701
+ const focused = document.activeElement;
702
+ const keep = focused && focused !== document.body && !structural;
703
+ S = merge(state);
704
+ if (state.config && !keep) useConfig(state.config); // don't redraw fields under the cursor
705
+ renderStrings(); renderStatus(state.error ? "Saved, with problems to fix" : undefined);
706
+ if (!keep) { renderRules(); renderSeqs(); renderPalette(); refreshPop(); }
707
+ else document.querySelectorAll(".rule").forEach((li, i) => (li.querySelector(".rule-title span").textContent = `${when(cfg.schedule[i])}, ${times(cfg.schedule[i])}`));
708
+ })
709
+ .catch((e) => renderStatus(`Couldn't save: ${e.message}`));
710
+ }
711
+
712
+ // --- preview on the lights; the server clears it if these pings stop (tab closed, laptop asleep) ---
713
+ let preview = null, pinger = null;
714
+ const post = (path, body, opts = {}) => fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), ...opts })
715
+ .then(async (r) => { const j = await r.json(); if (j.error) throw new Error(j.error); return j; });
716
+
717
+ async function startPreview(name, spec, own = true) {
718
+ try {
719
+ await post("/api/preview", { colors: spec.colors, effects: spec.effects });
720
+ preview = { name, own, sent: JSON.stringify(spec) };
721
+ clearInterval(pinger);
722
+ pinger = setInterval(() => post("/api/preview", { ping: true }).then((j) => { if (!j.previewing) previewEnded(); }).catch(() => {}), 5000);
723
+ renderPreview();
724
+ } catch (e) { renderStatus(`Couldn't preview: ${e.message}`); }
725
+ }
726
+ async function stopPreview() {
727
+ try { await post("/api/preview", { stop: true }); previewEnded(); }
728
+ catch (e) { renderStatus(`Couldn't stop the preview: ${e.message}`); }
729
+ }
730
+ function previewEnded() { preview = null; clearInterval(pinger); renderPreview(); }
731
+ function renderPreview() {
732
+ $("previewing").hidden = !preview;
733
+ $("preview-name").textContent = preview?.name || "";
734
+ renderSeqs(); renderPalette(); refreshPop();
735
+ }
736
+ $("stop-preview").onclick = stopPreview;
737
+ addEventListener("pagehide", () => preview && post("/api/preview", { stop: true }, { keepalive: true }));
738
+
739
+ $("apply").onclick = async () => {
740
+ $("apply").disabled = true; $("apply").textContent = "Applying…";
741
+ await saving; // apply what's on screen, not the file as of an edit ago
742
+ try {
743
+ const r = await fetch("/api/apply", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" }), state = await r.json();
744
+ if (!r.ok) throw new Error(state.error || r.statusText);
745
+ take(state, state.error ? undefined : `Applied ${state.applied} change${state.applied === 1 ? "" : "s"}`);
746
+ } catch (e) {
747
+ // part of the plan may have gone through before the error: show where things stand now
748
+ const msg = `Couldn't apply: ${e.message}`, state = await fetch("/api/state").then((r) => r.json()).catch(() => null);
749
+ state?.config ? take(state, msg) : renderStatus(msg);
750
+ }
751
+ };
752
+ $("review-btn").onclick = (e) => {
753
+ const show = $("review").hidden;
754
+ $("review").hidden = !show; e.target.setAttribute("aria-expanded", String(show));
755
+ };
756
+ $("new-rule").onclick = () => {
757
+ let name = "New rule", n = 2;
758
+ while (cfg.schedule.some((r) => r.name === name)) name = `New rule ${n++}`;
759
+ cfg.schedule.unshift({ name, on: "Dec 25", sequences: [] });
760
+ open.add(name); save(true);
761
+ };
762
+ $("new-seq").onclick = () => {
763
+ let name = "New sequence", n = 2;
764
+ while (cfg.sequences[name]) name = `New sequence ${n++}`;
765
+ cfg.sequences[name] = { colors: ["FFB547"] };
766
+ save(true);
767
+ requestAnimationFrame(() => document.querySelector(`#seqs [data-seq="${CSS.escape(name)}"] .seq-name`)?.select());
768
+ };
769
+ $("filter").oninput = $("side-filter").oninput = renderPalette;
770
+
771
+ // --- bridge info ---
772
+ const ago = (iso) => {
773
+ if (!iso || iso.startsWith("1970")) return "never";
774
+ const m = Math.round((Date.now() - new Date(iso)) / 60000);
775
+ return m < 1 ? "just now" : m < 120 ? `${m} min ago` : m < 2880 ? `${Math.round(m / 60)} h ago` : `${Math.round(m / 1440)} days ago`;
776
+ };
777
+ const yes = (v, y = "yes", n = "no") => (v ? y : n);
778
+ function panel(title, rows) {
779
+ return el("section", { className: "panel" }, el("h3", {}, title),
780
+ el("dl", {}, rows.filter(([, v]) => v != null && v !== "").flatMap(([k, v]) => [el("dt", {}, k), el("dd", {}, String(v))])));
781
+ }
782
+ async function loadBridge() {
783
+ $("bridge-at").textContent = "Reading the bridge…";
784
+ try {
785
+ const r = await fetch("/api/bridge"), j = await r.json();
786
+ if (j.error) throw new Error(j.error);
787
+ const b = j.status, net = b.network || {};
788
+ $("checks").replaceChildren(...j.checks.map((c) => el("li", { className: c.ok === true ? "ok" : c.ok === false ? "warn" : "info" },
789
+ el("span", {}, c.name), el("span", {}, c.text))));
790
+ $("panels").replaceChildren(
791
+ panel(`Bridge ${b.serial}`, [
792
+ ["Firmware", `${b.firmwareVersion}, radio ${b.radioFirmwareVersion}`],
793
+ ["Network", `${net.interface || "?"}, ${b.localIp}${b.ssid ? `, ${b.ssid}` : ""}`],
794
+ ["Clock", `${yes(net.ntp, "NTP on", "NTP off")}${b.timeOffset ? `, offset ${b.timeOffset}` : ""}`],
795
+ ["Cloud", `${yes(b.serverReachable, "reachable", "unreachable")}, checked in ${ago(b.lastServerCheckin)}`],
796
+ ["Memory", b.minFreeHeap != null && `lowest free since boot ${b.minFreeHeap.toLocaleString()} bytes`],
797
+ ]),
798
+ panel("Reboots and links", [
799
+ ["Reboots", b.rebootCount],
800
+ ["Last reset", b.resetReason != null && `reason ${b.resetReason}`],
801
+ ["Supervisor", b.supervisorRebootCount != null && `${b.supervisorRebootCount} reboots`],
802
+ ["Radio", `${b.radioRebootCount} reboots, ${b.radioLoopsPerSecond ?? "?"} loops/s, answered ${ago(b.lastRadioResponse)}`],
803
+ ["Wi-Fi retries", b.wifiReconnectAttempts],
804
+ ["MQTT", b.mqttOutageMs != null && `${b.mqttOutageMs} ms outage, last ack ${Math.round((b.mqttBrokerAckAgeMs || 0) / 1000)} s ago`],
805
+ ]),
806
+ ...(b.zones || []).map((z) => panel(`Zone ${z.serial}`, [
807
+ ["State", yes(z.active, "active", "inactive")],
808
+ ["Lights", `${z.configuredLength} pixels, ${z.colorOrder}`],
809
+ ["Firmware", `${z.firmwareVersion}, hardware ${z.hardwareVersion}`],
810
+ ["Signal", `RSSI ${z.rssi}, SNR ${z.snr}`],
811
+ ["Sensors", `temperature ${z.temperature}, voltage ${z.voltage}, current ${z.current} (raw)`],
812
+ ["Reboots", z.rebootCount],
813
+ ["Last answer", ago(z.lastResponseDate)],
814
+ ])),
815
+ );
816
+ $("raw").textContent = JSON.stringify(b, null, 2);
817
+ $("bridge-at").textContent = `Read ${new Date().toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}`;
818
+ } catch (e) { $("bridge-at").textContent = `Couldn't read the bridge: ${e.message}`; }
819
+ }
820
+ async function bridgeAction(action, done) {
821
+ try { await post("/api/bridge", { action }); $("bridge-at").textContent = done; }
822
+ catch (e) { $("bridge-at").textContent = `Couldn't ${action === "time" ? "set the clock" : "reboot"}: ${e.message}`; }
823
+ }
824
+ $("bridge-refresh").onclick = loadBridge;
825
+ $("bridge-time").onclick = () => bridgeAction("time", "Bridge clock set to now").then(loadBridge);
826
+ // two steps instead of a confirm() dialog
827
+ $("bridge-reboot").onclick = (e) => {
828
+ const btn = e.currentTarget;
829
+ if (btn.dataset.armed) {
830
+ delete btn.dataset.armed; btn.textContent = "Reboot";
831
+ bridgeAction("reboot", "Rebooting; the lights may blink. Refresh in a minute.");
832
+ } else {
833
+ btn.dataset.armed = "1"; btn.textContent = "Reboot now? Click again";
834
+ setTimeout(() => { if (btn.dataset.armed) { delete btn.dataset.armed; btn.textContent = "Reboot"; } }, 5000);
835
+ }
836
+ };
837
+
838
+ // views: #calendar (default), #sequences, #bridge
839
+ function showView() {
840
+ const view = ["#sequences", "#bridge"].includes(location.hash) ? location.hash.slice(1) : "calendar";
841
+ document.body.dataset.view = view;
842
+ if (view === "bridge") loadBridge();
843
+ for (const v of ["calendar", "sequences", "bridge"]) $(`tab-${v}`).removeAttribute("aria-current");
844
+ $(`tab-${view}`).setAttribute("aria-current", "page");
845
+ closePop(true);
846
+ }
847
+ addEventListener("hashchange", showView);
848
+ showView();
849
+ document.addEventListener("dragend", () => { drag = null; document.querySelectorAll(".over,.drop-before,.drop-after").forEach((n) => n.classList.remove("over", "drop-before", "drop-after")); });
850
+
851
+ fetch("/api/state").then((r) => r.json()).then((s) => take(s)).catch((e) => ($("saved").textContent = `Couldn't load: ${e.message}`));
852
+ </script>
853
+ </body>
854
+ </html>
@@ -0,0 +1,206 @@
1
+ require "socket"
2
+ require "io/wait"
3
+ require "json"
4
+ require "digest"
5
+ require "fileutils"
6
+ require_relative "../everlights"
7
+
8
+ module Everlights
9
+ # `everlights web`: a page on localhost for editing the sync config and applying it.
10
+ # GET / the page
11
+ # GET /api/state config and its version, bridge sequences, the night-by-night schedule, the plan
12
+ # PUT /api/config save the whole config (JSON) to the YAML file, then GET /api/state. Send If-Match: <version>
13
+ # and a file edited since then is left alone: 412, with the state as it is on disk.
14
+ # POST /api/apply run the plan against the bridge
15
+ # GET /api/bridge status, health checks
16
+ # POST /api/bridge {action: "time"} sets the bridge clock to now; {action: "reboot"} restarts it
17
+ # POST /api/preview {colors:, effects:} on the lights now; {stop: true} hands back to the calendar;
18
+ # {ping: true} keeps it up. With no ping for PREVIEW_GRACE seconds the preview is cleared.
19
+ # ponytail: a thread per connection but one request at a time under a lock; a slow bridge call holds up the next request.
20
+ class Web
21
+ PAGE = File.join(__dir__, "web.html")
22
+ PREVIEW_GRACE = 20
23
+ IDLE = 10 # seconds a connection may sit before sending a request; browsers open spare ones
24
+ # A bad config or an unreachable bridge: the page shows the message.
25
+ FAILURES = [Error, IndexError, ArgumentError, TypeError, Date::Error, JSON::ParserError,
26
+ SystemCallError, Net::OpenTimeout, Net::ReadTimeout].freeze
27
+
28
+ def initialize(client, config_path, port: 4567)
29
+ @c, @path, @port = client, config_path, port
30
+ @state_path = Sync.state_path(config_path)
31
+ @lock = Mutex.new
32
+ end
33
+
34
+ def start
35
+ server = TCPServer.new("127.0.0.1", @port)
36
+ puts "everlights web: http://localhost:#{@port} (editing #{@path}; ctrl-c to stop)"
37
+ loop do
38
+ ready = IO.select([server], nil, nil, 5) # wake up now and then to drop an abandoned preview
39
+ expire_preview
40
+ Thread.new(server.accept) { handle(_1) } if ready
41
+ end
42
+ rescue Interrupt
43
+ puts
44
+ ensure
45
+ server&.close
46
+ begin
47
+ @lock.synchronize { stop_preview }
48
+ rescue StandardError => e
49
+ warn "web: couldn't clear the preview: #{e.message}"
50
+ end
51
+ end
52
+
53
+ # A bridge error leaves the preview in place, to try again on the next wake-up.
54
+ def expire_preview(now = Time.now)
55
+ @lock.synchronize { stop_preview if @preview_until && now > @preview_until }
56
+ rescue StandardError => e
57
+ warn "web: couldn't clear the preview, will retry: #{e.message}"
58
+ end
59
+
60
+ def stop_preview
61
+ return unless @preview_until
62
+ @c.clear
63
+ @preview_until = nil
64
+ end
65
+
66
+ def handle(conn)
67
+ return unless conn.wait_readable(IDLE)
68
+ verb, path = conn.gets&.split
69
+ return unless path
70
+ headers = {}
71
+ while (line = conn.gets) && line != "\r\n"
72
+ k, v = line.split(":", 2)
73
+ headers[k.downcase] = v.to_s.strip
74
+ end
75
+ body = conn.read(headers["content-length"].to_i)
76
+ code, type, out = @lock.synchronize { respond(verb, path, headers, body) }
77
+ conn.write "HTTP/1.1 #{code} X\r\nContent-Type: #{type}; charset=utf-8\r\nContent-Length: #{out.bytesize}\r\n" \
78
+ "Cache-Control: no-store\r\nConnection: close\r\n\r\n#{out}"
79
+ rescue SystemCallError, IOError
80
+ nil # the browser hung up
81
+ ensure
82
+ conn.close
83
+ end
84
+
85
+ def respond(verb, path, headers, body)
86
+ route(verb, path, headers, body)
87
+ rescue *FAILURES => e
88
+ [422, "application/json", JSON.generate(error: e.message)]
89
+ rescue StandardError => e
90
+ warn "web: #{e.class}: #{e.message}\n #{Array(e.backtrace).first(3).join("\n ")}"
91
+ [500, "application/json", JSON.generate(error: "#{e.class}: #{e.message}")]
92
+ end
93
+
94
+ def route(verb, path, headers, body)
95
+ # Another site open in the browser can reach localhost: refuse foreign Host headers (DNS rebinding),
96
+ # and require JSON on writes so cross-site forms can't post without a CORS preflight we never answer.
97
+ return [403, "text/plain", "forbidden"] unless headers["host"].to_s.match?(/\A(localhost|127\.0\.0\.1)(:\d+)?\z/)
98
+ write = verb != "GET"
99
+ return [415, "text/plain", "send JSON"] if write && !headers["content-type"].to_s.start_with?("application/json")
100
+
101
+ case [verb, path.split("?").first]
102
+ when %w[GET /] then [200, "text/html", File.read(PAGE)]
103
+ when %w[GET /api/state] then [200, "application/json", JSON.generate(state)]
104
+ when %w[PUT /api/config]
105
+ saved = save(JSON.parse(body), headers["if-match"])
106
+ [saved ? 200 : 412, "application/json", JSON.generate(state)]
107
+ when %w[POST /api/apply]
108
+ plan = Sync.new(@c, load, state_path: @state_path).plan
109
+ plan.apply!
110
+ [200, "application/json", JSON.generate(state.merge(applied: plan.actions.size))]
111
+ when %w[GET /api/bridge]
112
+ status = @c.status
113
+ [200, "application/json", JSON.generate(status: status, now: Everlights.stamp(Time.now),
114
+ checks: Everlights.health(status).map { |ok, name, text| {ok: ok, name: name, text: text} })]
115
+ when %w[POST /api/bridge]
116
+ case JSON.parse(body)["action"]
117
+ when "time" then @c.set_time(Time.now)
118
+ when "reboot" then @c.reboot
119
+ else raise Error, "unknown action"
120
+ end
121
+ [200, "application/json", JSON.generate(ok: true)]
122
+ when %w[POST /api/preview]
123
+ req = JSON.parse(body)
124
+ if req["stop"] then stop_preview
125
+ elsif req["ping"] then @preview_until &&= Time.now + PREVIEW_GRACE
126
+ else
127
+ colors = Everlights.colors(req["colors"])
128
+ raise Error, "nothing to preview: no colors" if colors.empty?
129
+ @c.set(*colors, effects: Everlights.effects(req["effects"]))
130
+ @preview_until = Time.now + PREVIEW_GRACE
131
+ end
132
+ [200, "application/json", JSON.generate(previewing: !!@preview_until)]
133
+ else [404, "text/plain", "not found"]
134
+ end
135
+ end
136
+
137
+ def load
138
+ config = Sync.load_config(@path)
139
+ ENV["TZ"] = config["timezone"] if config["timezone"]
140
+ # an unquoted 18:30 loads as a number; show and save it as "18:30"
141
+ hm = ->(v) { v.is_a?(Integer) ? format("%02d:%02d", *(v / Sync::YAML_MINUTE).divmod(60)) : v }
142
+ [config["defaults"], *config["schedule"]].each do |r|
143
+ %w[start end].each { r[_1] = hm.(r[_1]) if r.is_a?(Hash) && r.key?(_1) }
144
+ end
145
+ config
146
+ end
147
+
148
+ def version = Digest::SHA256.file(@path).hexdigest
149
+
150
+ # False, writing nothing, when the file isn't at `version` any more (edited by hand); no version skips the check.
151
+ def save(config, version = nil)
152
+ raise Error, "config must be an object" unless config.is_a?(Hash)
153
+ text = File.read(@path)
154
+ return false if version && version != Digest::SHA256.hexdigest(text)
155
+ # ponytail: one backup, never replaced: the file as it was before the page first saved it.
156
+ # Comments added by hand after that are lost on the next save; dated backups if that bites.
157
+ bak = "#{@path}.bak"
158
+ FileUtils.cp(@path, bak) unless File.exist?(bak)
159
+ header = text[/\A(?:#.*\n|[ \t]*\n)*/]
160
+ File.write(@path, header + Web.dump(config))
161
+ true
162
+ end
163
+
164
+ # YAML like a person writes it: lists of plain values and small maps on one line.
165
+ def self.dump(config)
166
+ doc = YAML.parse_stream(YAML.dump(config))
167
+ doc.each do |n|
168
+ leaves = n.respond_to?(:children) && n.children&.all?(Psych::Nodes::Scalar)
169
+ n.style = Psych::Nodes::Sequence::FLOW if n.is_a?(Psych::Nodes::Sequence) && leaves
170
+ n.style = Psych::Nodes::Mapping::FLOW if n.is_a?(Psych::Nodes::Mapping) && leaves && n.children.size <= 4
171
+ end
172
+ doc.to_yaml.delete_prefix("---\n")
173
+ end
174
+
175
+ def state
176
+ config = load
177
+ out = {config: config, version: version, effects: EFFECTS, today: Date.today.iso8601,
178
+ horizon: Integer(config["horizon_days"] || 120, exception: false) || 120, host: config.dig("bridge", "host")}
179
+ sync = Sync.new(@c, config, state_path: @state_path)
180
+ plan = begin
181
+ sync.plan
182
+ rescue *FAILURES => e
183
+ out[:error] = e.message
184
+ nil
185
+ end
186
+ if (bridge = sync.bridge_seqs) # read by the plan, even one that found config problems
187
+ mine = (config["sequences"] || {}).keys.map(&:downcase)
188
+ out[:bridge_sequences] = bridge.reject { mine.include?(_1["alias"].downcase) }.sort_by { _1["alias"].downcase }
189
+ .map { {name: _1["alias"], colors: _1["pattern"], effects: _1["effects"], builtin: _1["id"].start_with?(BUILTIN_PREFIX)} }
190
+ end
191
+ return out unless plan
192
+
193
+ nights = {}
194
+ plan.shows.each do |rule, list|
195
+ list.each { |s, e| nights[s.to_date.iso8601] = {rule: rule, start: s.strftime("%H:%M"), end: e.strftime("%H:%M")} }
196
+ end
197
+ plan.skips.each do |d, rule, why|
198
+ next if why.end_with?(" wins this night")
199
+ nights[d.iso8601] ||= {rule: rule, note: why} # tonight's show, once under way, is in shows and stays
200
+ end
201
+ out.merge(nights: nights, plan: plan.actions.map { {kind: _1.kind, op: _1.op, name: _1.name, detail: _1.detail} })
202
+ rescue *FAILURES => e
203
+ (out || {config: config}).merge(error: e.message)
204
+ end
205
+ end
206
+ end
data/lib/everlights.rb CHANGED
@@ -161,6 +161,25 @@ module Everlights
161
161
  end
162
162
  end
163
163
 
164
+ # [[ok, name, text], ...] from Client#status; ok is true, false, or :info.
165
+ # ponytail: thresholds are guesses from one bridge; tune when real failures show what matters
166
+ def self.health(b, now: Time.now)
167
+ ago = ->(v) { v ? ((now - Time.parse(v)) / 60).round : Float::INFINITY }
168
+ mins = ->(m) { m.infinite? ? "never" : "#{m} min ago" }
169
+ cloud, radio = ago.(b["lastServerCheckin"]), ago.(b["lastRadioResponse"])
170
+ [
171
+ [!!b["serverReachable"] && cloud <= 15, "cloud", "#{b["serverReachable"] ? "reachable" : "unreachable"}, checked in #{mins.(cloud)}"],
172
+ [!!b.dig("network", "ntp"), "clock", "ntp #{b.dig("network", "ntp") ? "on" : "off"}"],
173
+ [b["minFreeHeap"].to_i >= 10_000, "memory", "lowest free since boot #{b["minFreeHeap"]} bytes (warn under 10000)"],
174
+ [radio <= 10, "radio", "answered #{mins.(radio)}, #{b["radioRebootCount"]} radio reboots"],
175
+ *b["zones"].map do |z|
176
+ last = ago.(z["lastResponseDate"])
177
+ [!!z["active"] && last <= 10, "zone #{z["serial"]}", "#{z["active"] ? "active" : "inactive"}, answered #{mins.(last)}, #{z["rebootCount"]} reboots"]
178
+ end,
179
+ [:info, "reboots", "#{b["rebootCount"]} total, last reset reason #{b["resetReason"]}"]
180
+ ]
181
+ end
182
+
164
183
  def self.stamp(t) = (t.is_a?(Time) ? t : Time.parse(t.to_s)).getutc.iso8601(6)
165
184
 
166
185
  class Sequences
@@ -62,6 +62,8 @@ When the user wants a recurring or seasonal plan ("Christmas every December", "F
62
62
  2. Run `everlights sync --dry-run` and show the user the plan, including the Skipped and No show sections. `everlights sync --check` is the same plan, but exits 2 when anything would change.
63
63
  3. Run `everlights sync` only after they confirm.
64
64
 
65
+ If the user would rather click and drag, suggest `everlights web`: it edits the same file and has its own Apply button.
66
+
65
67
  Sync only changes what it created itself. Config problems abort before anything is written; fix every one it lists. Use `--adopt` only when the user says the state file was lost.
66
68
 
67
69
  ## Unverified
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: everlights
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.1
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ricky Chilcott
@@ -23,6 +23,8 @@ files:
23
23
  - exe/everlights
24
24
  - lib/everlights.rb
25
25
  - lib/everlights/sync.rb
26
+ - lib/everlights/web.html
27
+ - lib/everlights/web.rb
26
28
  - skills/everlights/SKILL.md
27
29
  homepage: https://github.com/rickychilcott/everlights
28
30
  licenses: