everlights 0.1.0 → 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 +4 -4
- data/README.md +20 -1
- data/exe/everlights +17 -3
- data/lib/everlights/sync.rb +28 -9
- data/lib/everlights/web.html +854 -0
- data/lib/everlights/web.rb +206 -0
- data/lib/everlights.rb +19 -0
- data/skills/everlights/SKILL.md +4 -2
- metadata +5 -2
|
@@ -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
|
data/skills/everlights/SKILL.md
CHANGED
|
@@ -9,7 +9,7 @@ The `everlights` CLI talks to the bridge on the LAN (no auth). It needs `EVERLIG
|
|
|
9
9
|
|
|
10
10
|
## Before you write anything
|
|
11
11
|
|
|
12
|
-
1. Run `everlights calendar list` and `everlights show` (names what's playing and which show it's from) first (`everlights bridge` if something seems broken). Report what's already scheduled or showing.
|
|
12
|
+
1. Run `everlights calendar list` and `everlights show` (names what's playing and which show it's from) first (`everlights bridge health` if something seems broken; it marks problems WARN). Report what's already scheduled or showing.
|
|
13
13
|
2. Confirm before every write: `set`, `play`, `off`, `clear`, `sequence add/update/remove`, `calendar add/remove` and `bridge time`. These change real lights on a real house, so state the exact command you'll run.
|
|
14
14
|
3. Only run `bridge reboot --yes` when the user explicitly asks; it interrupts the lights. The CLI refuses to remove built-in sequences, or sequences an event still uses.
|
|
15
15
|
|
|
@@ -59,9 +59,11 @@ el.calendar.remove "2026-12-24", "Christmas"
|
|
|
59
59
|
When the user wants a recurring or seasonal plan ("Christmas every December", "Fridays in football season"), edit `config/everlights.yml` rather than adding calendar entries one by one. The format reference is `config/everlights.example.yml`.
|
|
60
60
|
|
|
61
61
|
1. Edit `sequences:` or `schedule:`. Rules higher in the list win nights they share.
|
|
62
|
-
2. Run `everlights sync --dry-run` and show the user the plan, including the Skipped
|
|
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.
|
|
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:
|
|
@@ -31,6 +33,7 @@ metadata:
|
|
|
31
33
|
source_code_uri: https://github.com/rickychilcott/everlights
|
|
32
34
|
bug_tracker_uri: https://github.com/rickychilcott/everlights/issues
|
|
33
35
|
rubygems_mfa_required: 'true'
|
|
36
|
+
github_repo: ssh://github.com/rickychilcott/everlights
|
|
34
37
|
rdoc_options: []
|
|
35
38
|
require_paths:
|
|
36
39
|
- lib
|
|
@@ -45,7 +48,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
|
|
|
45
48
|
- !ruby/object:Gem::Version
|
|
46
49
|
version: '0'
|
|
47
50
|
requirements: []
|
|
48
|
-
rubygems_version:
|
|
51
|
+
rubygems_version: 4.0.20
|
|
49
52
|
specification_version: 4
|
|
50
53
|
summary: Client and CLI for the EverLights Smart Lights Bridge local API
|
|
51
54
|
test_files: []
|