everlights 0.2.0 → 1.0.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: 0d319ee1f69ecca30fa28e49bac2a468bb9f069d9f438d6d7ca6bc5e20adb1ed
4
- data.tar.gz: 427cd966f9b74e8c158db2847862ea7d739e064cfac5b0e3b418ce797f657cf4
3
+ metadata.gz: f14eeff731dd3d21e13f7a8cc9e80ab6654d2ef9ab40695ea581f876f3539270
4
+ data.tar.gz: ef5c19da8d2f55f9372de48752637ec345144bbd1deeeaef5e9b664c24b21093
5
5
  SHA512:
6
- metadata.gz: ea88456723a18232c6aaf93ff903dfd050cb4054eb2bd97eb782cc13dc9bb227198d5efac12510553e37e692a798d06731df53f0a19d9fcd14a23a62926a0dc2
7
- data.tar.gz: 197bbe6f6247cd149164cfd5785ac1e86aeca84570dc4ce9c770ac35fcdcce05d34d0f6eae9e46293438ab920fec3a8f13f829ea2de60ff7a6d18aa5b84476c0
6
+ metadata.gz: 01d38fcf71f206f7776602b64da1a079a7e909312a2f0bfecaa66e6570d7a99d0808d70c6e9b22eaefe33c7b4cdeecda96b0f96af3f64371c7f548fdb794a79a
7
+ data.tar.gz: '08162ef079d98039a969903365bb9945ae594a1810776f8b9aea3a9cb99a220df34e164e183bf392ab934e5ac14b5d40933dc919bd38ee6682a19eb115e4ff96'
data/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
  </picture>
8
8
  </p>
9
9
 
10
- A Ruby client and CLI for the EverLights v3 Smart Lights Bridge. It talks to the bridge directly on your local network: no cloud, no account, and no dependencies outside Ruby's standard library.
10
+ A Ruby client and CLI for the EverLights v3 Smart Lights Bridge, with no dependencies outside Ruby's standard library. Bridge firmware B5010 and later only take commands through the EverLights cloud, so it signs in with your EverLights app account. On older firmware it can talk to the bridge directly on your local network, with no account.
11
11
 
12
12
  Use it to show colors now, manage saved sequences, and put shows on the calendar weeks or months ahead. The bridge stores scheduled shows itself, so they run with no computer on.
13
13
 
@@ -17,14 +17,19 @@ Use it to show colors now, manage saved sequences, and put shows on the calendar
17
17
 
18
18
  ```sh
19
19
  gem install everlights
20
- export EVERLIGHTS_HOST=192.168.1.50 # your bridge's IP (EverLights app → device information)
20
+ everlights login you@example.com # your EverLights app account; asks for the password
21
21
  ```
22
22
 
23
+ `login` saves a login token in `~/.config/everlights/cloud.json` (readable only by you, and never your password), then sends commands to your bridge through the EverLights cloud. It picks the account's first bridge; `--bridge SERIAL` picks another. The password can also come from a pipe, for example from 1Password: `op read "op://Private/EverLights/password" | everlights login you@example.com`. `everlights logout` forgets the token.
24
+
25
+ On firmware older than B5010 you can skip the login and use the local API: `export EVERLIGHTS_HOST=192.168.1.50` (your bridge's IP, from the EverLights app → device information). Once you're logged in, `--host` still selects the local API for a single command.
26
+
23
27
  Requires Ruby 3.1+.
24
28
 
25
29
  ## CLI
26
30
 
27
31
  ```sh
32
+ everlights login you@example.com # once; then everything goes through the cloud
28
33
  everlights bridge # firmware, network, cloud, zone health
29
34
  everlights bridge health # ok/WARN checks; exits 2 on any warning
30
35
  everlights show # what's playing, e.g. "Halloween Fade (Halloween show)"
@@ -47,6 +52,7 @@ everlights calendar remove 2026-12-24 Christmas # one night
47
52
 
48
53
  - **Calendar defaults:** a show starts at dusk and ends at 23:00. Each sequence plays for 20 seconds unless you write `name:seconds`.
49
54
  - **Times** use your machine's local time zone. An end time earlier than the start means the next morning. `--until` repeats the show nightly and stays correct across DST changes.
55
+ - **Gradients:** anywhere a color goes, `FF7A1E..FF9E3D:4` is 4 colors blended evenly from the first to the last. Middle stops bend it: `FF0000..FFFFFF..0000FF:9`. In the web editor, ↔ blends the colors between a sequence's first and last.
50
56
  - **Effects:** `bars blink chase fade gradient lightning melt pingPong random reverseChase strobe twinkle wipe`, each with a strength from 0 to 255.
51
57
  - **JSON:** add `--json` to list commands and `bridge`.
52
58
  - **Now commands** (`set`, `play`, `off`): during a running show they only last until its next sequence change.
@@ -57,9 +63,10 @@ everlights calendar remove 2026-12-24 Christmas # one night
57
63
  Describe your own sequences and a schedule once. `everlights sync` then builds them on the bridge for the months ahead:
58
64
 
59
65
  ```sh
60
- cp config/everlights.example.yml config/everlights.yml # gitignored; edit the IP, location and schedule
66
+ everlights init # writes config/everlights.yml: US holidays, a birthday, a season
61
67
  everlights sync --dry-run # print the plan
62
68
  everlights sync # apply it
69
+ everlights export # what the app made, as config YAML to adopt
63
70
  ```
64
71
 
65
72
  ```yaml
@@ -80,9 +87,10 @@ schedule: # higher in the list wins a shared night
80
87
  - `on:` takes a date (`2027-03-14`), a yearly date (`Dec 25`), `Nth Weekday of Month`, `last Monday of May`, or `Easter`.
81
88
  - `from:`/`to:` repeats nightly, every year, and can cross New Year.
82
89
  - `every:` takes weekdays, optionally limited by `from:`/`to:`.
90
+ - `ics:` takes a calendar feed (an `https://` or `webcal://` URL, or a file), and the show plays on each event's day: a team's games, school events, a shared family calendar. `match: Bobcats` keeps only events whose title contains it. Cancelled events are skipped. A recurring event counts once, on its first date, and a multi-day event on its first day. The feed is read each time sync plans.
83
91
  - **Times:** `start:` is `dusk`, `dusk+15` or `"18:30"`; `end:` defaults to `"23:00"`. An end earlier than the start means the next morning.
84
92
  - **Future only:** sync adds only nights that start more than 15 minutes from now. Each rule becomes one calendar entry, and re-running sync rolls the window forward.
85
- - **Leaves your app-made shows alone:** sync only changes or deletes what it created, tracked in `config/.sync-state.yml`. It skips nights an app-made show already covers, and refuses names that clash with built-ins or app-made items. If the state file is lost, `--adopt` takes back items whose names match the config.
93
+ - **Leaves your app-made shows alone:** sync only changes or deletes what it created, tracked in `config/.sync-state.yml`. It skips nights an app-made show already covers, and refuses names that clash with built-ins or app-made items. If the state file is lost, `--adopt` takes back items whose names match the config. To bring shows and sequences made in the app under the config, `everlights export` prints them as config YAML: add it to the file, then `sync --adopt`.
86
94
  - **All or nothing:** every config problem is reported before anything is written.
87
95
  - **Config location:** `--config` or `$EVERLIGHTS_CONFIG`. The config's `bridge.host` is used by every command unless `--host` or `$EVERLIGHTS_HOST` is set.
88
96
  - **Time zone:** set `timezone:` in the config, or it uses your machine's.
@@ -111,7 +119,8 @@ To only be told when it needs a sync, use `everlights sync --check`. It prints t
111
119
  ```ruby
112
120
  require "everlights"
113
121
 
114
- el = Everlights::Client.new("192.168.1.50") # or ENV["EVERLIGHTS_HOST"]
122
+ el = Everlights::Client.new(cloud: Everlights::Cloud.new) # after `everlights login`; or Everlights::Cloud.login(email, password)
123
+ el = Everlights::Client.new("192.168.1.50") # local API, firmware before B5010; or ENV["EVERLIGHTS_HOST"]
115
124
 
116
125
  el.play "Hallows Eve"
117
126
  el.set "FF0000", "00FF00", effects: {twinkle: 100}
@@ -161,6 +170,19 @@ The bridge (an ESP32) serves plain JSON over HTTP on port 80, with no authentica
161
170
 
162
171
  Verified against bridge firmware B4042, radio R3052 and zone firmware N3063. Firmware updates arrive over the air from EverLights' cloud; there is no local update endpoint.
163
172
 
173
+ **Firmware B5010 (October 2026) turned off local control.** The bridge updates itself, and on B5010 every endpoint except `GET /v1` answers `410 {"error":"gone","cloud":true}`. Without a login, commands stop with a message saying so, and `bridge health` warns.
174
+
175
+ The cloud serves the same API through a tunnel, which is how the EverLights app reaches the bridge now:
176
+
177
+ | | |
178
+ |---|---|
179
+ | `POST https://appserver-v2.myeverlights.com/v1/oauth/token` | sign in: `{grant_type: "password", username, password}`, or `refresh_token`. The refresh token changes each time it's used |
180
+ | `GET …/v1/bridges` | the account's bridges |
181
+ | `GET …/v1/bridges/{serial}/remotetoken` | a token for that bridge's tunnel |
182
+ | `https://remote.myeverlights.com/bridges/{serial}/proxy/v1/…` | the bridge API above, with `Authorization: Bearer <tunnel token>` |
183
+
184
+ Writes through the tunnel go out at least 0.25 seconds apart, because the bridge misbehaves when they stack up. B5010 also stopped reporting network and memory in its status, so `bridge health` shows those as info. The cloud is the app's private API: EverLights could change it at any time.
185
+
164
186
  Not yet confirmed:
165
187
  - What each effect's 0–255 value does.
166
188
  - How the bridge handles overlapping calendar entries.
@@ -180,11 +202,11 @@ ruby -Ilib -e 'Dir["test/*_test.rb"].each { require "./#{_1}" }'
180
202
 
181
203
  The tests run against a fake bridge, so no hardware is needed. CI runs them on every push and pull request.
182
204
 
183
- To release, bump the version in `everlights.gemspec`, commit, then tag and push (`git tag v0.2.0 && git push origin v0.2.0`). The release workflow tests, then publishes to RubyGems and GitHub Packages and creates a GitHub release with the `.gem` attached.
205
+ To release, bump the version in `everlights.gemspec`, commit, then tag and push (`git tag v1.0.0 && git push origin v1.0.0`). The release workflow tests, then publishes to RubyGems and GitHub Packages and creates a GitHub release with the `.gem` attached.
184
206
 
185
207
  ## Credits
186
208
 
187
- The protocol work builds on [weswitt/everlights3](https://github.com/weswitt/everlights3), whose OpenAPI spec mapped the endpoints, and [theOrakle/everlightsv3](https://github.com/theOrakle/everlightsv3), which is also the source of the logo images. There is also a Home Assistant [core integration](https://www.home-assistant.io/integrations/everlights) for the older v2 bridge.
209
+ The protocol work builds on [weswitt/everlights3](https://github.com/weswitt/everlights3), whose OpenAPI spec mapped the endpoints, and [theOrakle/everlightsv3](https://github.com/theOrakle/everlightsv3), which is also the source of the logo images. [borski/everlightsv3_cloud](https://github.com/borski/everlightsv3_cloud) mapped the cloud tunnel. There is also a Home Assistant [core integration](https://www.home-assistant.io/integrations/everlights) for the older v2 bridge.
188
210
 
189
211
  ## License
190
212
 
@@ -0,0 +1,105 @@
1
+ # Your year of light shows. `everlights init` writes this file; edit it, then:
2
+ # everlights sync --dry-run # see the plan
3
+ # everlights sync # apply it
4
+ #
5
+ # Sync builds sequences and calendar entries for the next `horizon_days`, only on nights that haven't
6
+ # started yet. It only changes or deletes what it created itself (tracked in .sync-state.yml next to
7
+ # this file), so shows you make in the EverLights app are left alone.
8
+
9
+ bridge: # only for the local API (firmware before B5010); after `everlights login` it isn't used
10
+ host: 192.168.1.50 # EverLights app -> device information. --host / $EVERLIGHTS_HOST override it.
11
+
12
+ location: # for dusk: sunset is calculated per night from this
13
+ lat: 40.0
14
+ lon: -83.0
15
+
16
+ # timezone: America/New_York # optional; defaults to this machine's
17
+ horizon_days: 120 # how far ahead each sync fills the calendar
18
+
19
+ defaults: # any rule can override these
20
+ start: dusk # dusk, dusk+15, dusk-10, or "18:30"
21
+ end: "23:00" # quote times; earlier than start means the next morning
22
+ seconds: 20 # how long each sequence plays before the next
23
+
24
+ sequences: # your own; they show up in the app under Personal
25
+ My Birthday:
26
+ colors: [FF1E8C, FFC400, 00A8FF, FFFFFF, 9D2BFF, FFC400, 2BFF6A, FFFFFF]
27
+ Ember Glow:
28
+ colors: [FF7A1E..FF9E3D:4, FF9233] # a gradient: 4 colors from FF7A1E to FF9E3D, then one more
29
+ effects: {chase: 60, twinkle: 180} # bars blink chase fade gradient lightning melt pingPong random reverseChase strobe twinkle wipe
30
+
31
+ # One rule per show. When two rules want the same night, the one higher in this list wins,
32
+ # so single nights come first and seasons last.
33
+ # A rule's "when" is exactly one of:
34
+ # on: 2027-03-14 | Dec 25 | 4th Thursday of November | last Monday of May | Easter | Easter-47
35
+ # from: Dec 1 / to: Jan 1 (every night in between, every year)
36
+ # every: [Friday, Saturday] (optionally with from:/to: to limit it to a season)
37
+ # ics: https://.../games.ics (each event's day in a calendar feed; match: Bobcats keeps titles with it)
38
+ # sequences: built-in or your own names (`everlights sequence list`); "Name:30" plays it for 30 seconds.
39
+ schedule:
40
+ - name: New Year's Eve
41
+ on: Dec 31
42
+ sequences: [New Year's]
43
+ end: "00:30"
44
+
45
+ - name: Christmas Day
46
+ on: Dec 25
47
+ sequences: [Christmas, "Candy Cane Lane:30"]
48
+ end: "01:00"
49
+
50
+ - name: Valentine's Day
51
+ on: Feb 14
52
+ sequences: [Valentine's Day]
53
+
54
+ - name: St. Patrick's Day
55
+ on: Mar 17
56
+ sequences: [St Patrick's Day]
57
+
58
+ - name: Easter
59
+ on: Easter
60
+ sequences: [Easter]
61
+
62
+ - name: Mother's Day
63
+ on: 2nd Sunday of May
64
+ sequences: [Mother's Day]
65
+
66
+ - name: Memorial Day
67
+ on: last Monday of May
68
+ sequences: [Star Spangled Twinkle]
69
+
70
+ - name: Father's Day
71
+ on: 3rd Sunday of June
72
+ sequences: [Father's Day]
73
+
74
+ - name: Independence Day
75
+ on: Jul 4
76
+ sequences: [Independence Day, 4th of July]
77
+ end: "23:59"
78
+
79
+ - name: Halloween
80
+ on: Oct 31
81
+ sequences: [Halloween, Hallows Eve]
82
+
83
+ - name: Veterans Day
84
+ on: Nov 11
85
+ sequences: [Star Spangled Twinkle]
86
+
87
+ - name: Thanksgiving
88
+ on: 4th Thursday of November
89
+ sequences: [Thanksgiving]
90
+
91
+ - name: Birthday
92
+ on: 2027-03-14
93
+ sequences: [My Birthday]
94
+
95
+ - name: Christmas Season
96
+ from: Dec 1
97
+ to: Jan 1
98
+ sequences: [Christmas, Winter]
99
+
100
+ - name: Fall Weekends
101
+ every: [Friday, Saturday]
102
+ from: Sep 15
103
+ to: Nov 20
104
+ start: dusk+15
105
+ sequences: [Fall Wave]
data/exe/everlights CHANGED
@@ -5,6 +5,11 @@ require "optparse"
5
5
  USAGE = <<~TXT
6
6
  Usage: everlights COMMAND [args] [options]
7
7
 
8
+ Cloud (bridge firmware B5010 and later turned off local control):
9
+ login EMAIL [--bridge SERIAL] sign in to your EverLights account; commands then go through the cloud
10
+ (asks for the password, or reads it from a pipe; saves tokens, not it)
11
+ logout forget the login; commands use the local bridge API again
12
+
8
13
  Bridge:
9
14
  bridge firmware, network, cloud, zone health
10
15
  bridge health ok/WARN per check; exit 2 on any warning (for cron)
@@ -31,10 +36,12 @@ USAGE = <<~TXT
31
36
  default dusk to 23:00, 20s per sequence
32
37
  calendar remove DATE NAME
33
38
 
34
- Sync (config/everlights.yml: sequences + schedule, see config/everlights.example.yml):
39
+ Sync (config/everlights.yml: sequences + schedule):
40
+ init [--host HOST] write a starter config: holidays, a birthday, a season
35
41
  sync [--dry-run] [--adopt] build sequences and the calendar ahead; prints the plan
36
42
  sync --check plan only; exit 2 if the bridge needs a sync (for cron)
37
43
  web [--port N] edit the config in a browser and apply it (localhost:4567)
44
+ export what the app made (sequences, shows) as config YAML, for sync --adopt
38
45
 
39
46
  Options:
40
47
  TXT
@@ -42,7 +49,8 @@ TXT
42
49
  opts = {effects: {}, limit: 365}
43
50
  parser = OptionParser.new do |o|
44
51
  o.banner = USAGE
45
- o.on("--host HOST", "bridge IP (default $EVERLIGHTS_HOST, then the config's bridge.host)") { opts[:host] = _1 }
52
+ o.on("--host HOST", "bridge IP, for the local API (default when not logged in: $EVERLIGHTS_HOST, then the config's bridge.host)") { opts[:host] = _1 }
53
+ o.on("--bridge SERIAL", "login: which of the account's bridges to use (default the first)") { opts[:bridge] = _1 }
46
54
  o.on("--config PATH", "config file (default $EVERLIGHTS_CONFIG, then config/everlights.yml)") { opts[:config] = _1 }
47
55
  o.on("--zone SERIAL", "limit set/play/off/clear/show to a zone (repeatable)") { (opts[:zones] ||= []) << _1 }
48
56
  o.on("--effect E[=N]", "N 0-255 (default 128): #{Everlights::EFFECTS.join(" ")}") do |e|
@@ -68,15 +76,53 @@ def json(obj) = puts(JSON.pretty_generate(obj))
68
76
  begin
69
77
  config_path = opts[:config] || ENV["EVERLIGHTS_CONFIG"] || "config/everlights.yml"
70
78
  config = if File.exist?(config_path) then Everlights::Sync.load_config(config_path)
71
- elsif opts[:config] || ENV["EVERLIGHTS_CONFIG"] then raise Everlights::Error, "no config at #{config_path}"
79
+ elsif (opts[:config] || ENV["EVERLIGHTS_CONFIG"]) && ARGV.first != "init" then raise Everlights::Error, "no config at #{config_path}"
72
80
  end
73
81
  ENV["TZ"] = config["timezone"] if config&.dig("timezone")
74
- el = Everlights::Client.new(opts[:host] || ENV["EVERLIGHTS_HOST"] || config&.dig("bridge", "host"))
75
- zones = opts[:zones]
76
82
  cmd = ARGV.shift
77
83
  cmd = "#{cmd} #{ARGV.shift}" if %w[sequence calendar].include?(cmd) ||
78
84
  (cmd == "bridge" && %w[health time reboot].include?(ARGV.first))
79
85
  arg = ARGV.join(" ")
86
+ cloud = Everlights::Cloud.new
87
+
88
+ case cmd
89
+ when "login"
90
+ abort "login EMAIL" unless ARGV.size == 1
91
+ password = if $stdin.tty?
92
+ require "io/console"
93
+ IO.console.getpass("EverLights password for #{arg}: ")
94
+ else $stdin.gets.to_s.chomp
95
+ end
96
+ cloud, bridges = Everlights::Cloud.login(arg, password, bridge: opts[:bridge])
97
+ bridges.each { |b| puts "#{b["serial"] == cloud.bridge ? "*" : " "} #{b["serial"]} #{b["name"]} firmware #{b["firmware"]}" }
98
+ puts "Logged in. Commands now go to bridge #{cloud.bridge} through the EverLights cloud."
99
+ puts "To use another, run `everlights login #{arg} --bridge SERIAL`." if bridges.size > 1
100
+ exit
101
+ when "logout"
102
+ cloud.logout
103
+ puts "Logged out. Commands use the local bridge API again."
104
+ exit
105
+ when "init"
106
+ raise Everlights::Error, "#{config_path} already exists; edit it, or pass --config to start another" if File.exist?(config_path)
107
+ text = File.read(File.expand_path("../config/everlights.example.yml", __dir__))
108
+ text = opts[:host] ? text.sub("192.168.1.50", opts[:host]) : text.sub(/^bridge:.*\n host:.*\n/) { _1.gsub(/^/, "# ") }
109
+ text = text.sub(/^location:.*\n(?: .*\n)+/) { _1.gsub(/^/, "# ") } # no default: a wrong one means wrong dusk times
110
+ tz = File.symlink?("/etc/localtime") && File.readlink("/etc/localtime")[%r{zoneinfo/(.+)\z}, 1]
111
+ text = text.sub(/^# timezone: \S+/) { "timezone: #{tz}" } if tz
112
+ FileUtils.mkdir_p(File.dirname(config_path))
113
+ File.write(config_path, text)
114
+ puts "Wrote #{config_path}. Next:"
115
+ puts " - Uncomment `location:` and put in your latitude and longitude; dusk is worked out from them."
116
+ puts " - Run `everlights login EMAIL`, or set bridge.host for the local API (firmware before B5010)." unless cloud.logged_in? || opts[:host]
117
+ puts " - Edit the sequences and schedule, then run `everlights sync --dry-run`."
118
+ exit
119
+ end
120
+
121
+ # Logged in: through the cloud, unless --host asks for the local API.
122
+ el = if cloud.logged_in? && !opts[:host] then Everlights::Client.new(cloud: cloud)
123
+ else Everlights::Client.new(opts[:host] || ENV["EVERLIGHTS_HOST"] || config&.dig("bridge", "host"))
124
+ end
125
+ zones = opts[:zones]
80
126
 
81
127
  case cmd
82
128
  when "bridge"
@@ -85,8 +131,8 @@ begin
85
131
  else
86
132
  at = ->(v) { v ? Time.parse(v).localtime.strftime("%Y-%m-%d %H:%M:%S") : "?" }
87
133
  net = b["network"] || {}
88
- puts "Bridge #{b["serial"]} firmware #{b["firmwareVersion"]}, radio #{b["radioFirmwareVersion"]}"
89
- puts " network #{net["interface"] || "?"} #{b["localIp"]}, ntp #{net["ntp"] ? "ok" : "off"}"
134
+ puts "Bridge #{b["serial"]} firmware #{b["firmwareVersion"]}, radio #{b["radioFirmwareVersion"] || "?"}#{" (via the EverLights cloud)" if el.cloud?}"
135
+ puts " network #{net["interface"] || "?"} #{b["localIp"]}, ntp #{{true => "ok", false => "off"}.fetch(net["ntp"], "?")}"
90
136
  puts " cloud #{b["serverReachable"] ? "reachable" : "UNREACHABLE"}, last check-in #{at.(b["lastServerCheckin"])}"
91
137
  puts " reboots #{b["rebootCount"]}"
92
138
  b["zones"].each do |z|
@@ -97,7 +143,7 @@ begin
97
143
  end
98
144
  end
99
145
  when "bridge health"
100
- checks = Everlights.health(el.status)
146
+ checks = Everlights.health(el.status, via_cloud: el.cloud?)
101
147
  checks.each { |ok, name, text| puts "#{{info: "info", true => "ok ", false => "WARN"}[ok]} #{name.ljust(19)} #{text}" }
102
148
  exit 2 unless checks.all? { _1[0] }
103
149
  when "bridge time"
@@ -183,7 +229,7 @@ begin
183
229
  puts "removed #{name.join(" ")} on #{date}"
184
230
 
185
231
  when "sync"
186
- raise Everlights::Error, "no config at #{config_path}; copy config/everlights.example.yml to start" unless config
232
+ raise Everlights::Error, "no config at #{config_path}; run `everlights init` to start one" unless config
187
233
  plan = Everlights::Sync.new(el, config, state_path: Everlights::Sync.state_path(config_path), adopt: opts[:adopt]).plan
188
234
  puts plan
189
235
  if plan.empty? then nil
@@ -194,8 +240,20 @@ begin
194
240
  puts "\nApplied."
195
241
  end
196
242
 
243
+ when "export"
244
+ require_relative "../lib/everlights/web"
245
+ found, notes = Everlights::Sync.export(el, state_path: Everlights::Sync.state_path(config_path))
246
+ found.reject! { _2.empty? }
247
+ puts "# Made outside sync: in the EverLights app, or with `sequence add` / `calendar add`."
248
+ if found.empty? then puts "# Nothing. Everything on the bridge is built in or made by sync."
249
+ else
250
+ puts "# To manage these from your config, add them to it, then run `everlights sync --adopt --dry-run`."
251
+ end
252
+ notes.each { puts "# Left out: #{_1}" }
253
+ puts Everlights::Web.dump(found) unless found.empty?
254
+
197
255
  when "web"
198
- raise Everlights::Error, "no config at #{config_path}; copy config/everlights.example.yml to start" unless config
256
+ raise Everlights::Error, "no config at #{config_path}; run `everlights init` to start one" unless config
199
257
  require_relative "../lib/everlights/web"
200
258
  Everlights::Web.new(el, config_path, port: opts[:port] || 4567).start
201
259
 
@@ -0,0 +1,113 @@
1
+ require "net/http"
2
+ require "json"
3
+ require "fileutils"
4
+
5
+ module Everlights
6
+ # The EverLights cloud, for bridges on firmware B5010 and later, which turned off local control.
7
+ # The app server signs in and hands out a token per bridge. The tunnel then serves the bridge's own
8
+ # API under /bridges/{serial}/proxy/v1/. Protocol mapped by github.com/borski/everlightsv3_cloud.
9
+ #
10
+ # Everlights::Cloud.login("me@example.com", password) # once; saves tokens, never the password
11
+ # el = Everlights::Client.new(cloud: Everlights::Cloud.new)
12
+ class Cloud
13
+ API = "https://appserver-v2.myeverlights.com/v1"
14
+ TUNNEL = "https://remote.myeverlights.com/bridges"
15
+ MARGIN = 300 # renew a token this many seconds before it expires
16
+ TIMEOUT = 15
17
+
18
+ def self.default_path = ENV["EVERLIGHTS_CLOUD"] || File.join(Dir.home, ".config", "everlights", "cloud.json")
19
+
20
+ # Signs in and saves the tokens and the bridge to use: `bridge` (a serial), or the account's first.
21
+ def self.login(email, password, bridge: nil, path: default_path, api: API, tunnel: TUNNEL)
22
+ cloud = new(path, api: api, tunnel: tunnel)
23
+ cloud.grant("grant_type" => "password", "username" => email, "password" => password)
24
+ all = cloud.bridges
25
+ raise Error, "no bridges on this EverLights account" if all.empty?
26
+ pick = bridge ? all.find { _1["serial"] == bridge } : all.first
27
+ raise Error, "no bridge #{bridge} on this account; it has #{all.map { _1["serial"] }.join(", ")}" unless pick
28
+ cloud.data.merge!("email" => email, "bridge" => pick["serial"])
29
+ cloud.save
30
+ [cloud, all]
31
+ end
32
+
33
+ attr_reader :tunnel
34
+
35
+ def initialize(path = Cloud.default_path, api: API, tunnel: TUNNEL)
36
+ @path, @api, @tunnel = path, api, tunnel
37
+ end
38
+
39
+ def logged_in? = File.exist?(@path)
40
+ def logout = FileUtils.rm_f(@path)
41
+ def bridge = data["bridge"]
42
+ def data = @data ||= (logged_in? ? JSON.parse(File.read(@path)) : {})
43
+
44
+ def save
45
+ FileUtils.mkdir_p(File.dirname(@path), mode: 0o700)
46
+ File.write(@path, JSON.pretty_generate(data), perm: 0o600)
47
+ File.chmod(0o600, @path) # perm: only applies when the file is new
48
+ end
49
+
50
+ # The account's bridges: [{"serial", "name", "firmware"}]
51
+ def bridges
52
+ api(Net::HTTP::Get, "/bridges").reject { _1["unpairedDate"] }.map do |b|
53
+ {"serial" => b["bridgeSerial"], "name" => b["alias"], "firmware" => b.dig("bridge", "firmwareVersion")}
54
+ end
55
+ end
56
+
57
+ # The tunnel's token for the bridge, renewed when near expiry or when `fresh`.
58
+ def tunnel_token(fresh: false)
59
+ saved = data["tunnel_token"]
60
+ return saved if saved && !fresh && Time.now.to_i < data["tunnel_expires"].to_i - MARGIN
61
+ token = api(Net::HTTP::Get, "/bridges/#{bridge}/remotetoken")["token"] or raise Error, "no tunnel token in the cloud's reply"
62
+ data.merge!("tunnel_token" => token, "tunnel_expires" => expiry(token))
63
+ save
64
+ token
65
+ end
66
+
67
+ def grant(params)
68
+ res = call(Net::HTTP::Post, "#{@api}/oauth/token", body: params)
69
+ raise Error, "EverLights didn't accept the #{params["grant_type"] == "password" ? "email or password" : "saved login; run `everlights login` again"}" if %w[400 401 403].include?(res.code)
70
+ raise Error, "login -> #{res.code}: #{res.body}" unless res.is_a?(Net::HTTPSuccess)
71
+ body = JSON.parse(res.body)
72
+ data.merge!("access_token" => body.fetch("access_token"), "refresh_token" => body["refresh_token"] || data["refresh_token"],
73
+ "access_expires" => Time.now.to_i + Integer(body["expires_in"] || 3600))
74
+ end
75
+
76
+ private
77
+
78
+ # ponytail: the refresh token changes on every use. Two processes renewing at the same moment
79
+ # (cron sync while `web` runs) leave one with a dead token; it then asks for `everlights login`.
80
+ def access_token(fresh: false)
81
+ return data["access_token"] if !fresh && Time.now.to_i < data["access_expires"].to_i - MARGIN
82
+ @data = nil # another process may have renewed it since we read the file
83
+ return data["access_token"] if !fresh && Time.now.to_i < data["access_expires"].to_i - MARGIN
84
+ raise Error, "not logged in; run `everlights login`" unless data["refresh_token"]
85
+ grant("grant_type" => "refresh_token", "refresh_token" => data["refresh_token"])
86
+ save
87
+ data["access_token"]
88
+ end
89
+
90
+ def api(verb, path)
91
+ res = call(verb, "#{@api}#{path}", token: access_token)
92
+ # the app server answers a stale token with 400 "Authorization failure", not 401
93
+ res = call(verb, "#{@api}#{path}", token: access_token(fresh: true)) if %w[400 401 403].include?(res.code)
94
+ raise Error, "cloud #{verb::METHOD} #{path} -> #{res.code}: #{res.body}" unless res.is_a?(Net::HTTPSuccess)
95
+ JSON.parse(res.body)
96
+ end
97
+
98
+ def call(verb, url, token: nil, body: nil)
99
+ uri = URI(url)
100
+ req = verb.new(uri, "Accept" => "application/json", "Content-Type" => "application/json")
101
+ req["Authorization"] = "Bearer #{token}" if token
102
+ req.body = JSON.generate(body) if body
103
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: TIMEOUT, read_timeout: TIMEOUT) { _1.request(req) }
104
+ end
105
+
106
+ # A JWT's exp claim, read without verifying; an hour if it has none
107
+ def expiry(token)
108
+ Integer(JSON.parse(token.split(".")[1].tr("-_", "+/").unpack1("m"))["exp"])
109
+ rescue StandardError
110
+ Time.now.to_i + 3600
111
+ end
112
+ end
113
+ end
@@ -1,7 +1,7 @@
1
1
  require "yaml"
2
2
 
3
3
  module Everlights
4
- # Builds sequences and calendar entries on the bridge from a config (see config/everlights.example.yml).
4
+ # Builds sequences and calendar entries on the bridge from a config (`everlights init` writes one; format in config/everlights.example.yml).
5
5
  #
6
6
  # config = Everlights::Sync.load_config("config/everlights.yml")
7
7
  # plan = Everlights::Sync.new(el, config, state_path: "config/.sync-state.yml").plan # raises Error listing every config problem
@@ -74,6 +74,43 @@ module Everlights
74
74
  # What sync has made on the bridge, next to the config.
75
75
  def self.state_path(config_path) = File.join(File.dirname(config_path), ".sync-state.yml")
76
76
 
77
+ # What's on the bridge that sync didn't make (the EverLights app, `sequence add`, `calendar add`), as config:
78
+ # [{"sequences" => {...}, "schedule" => [...]}, notes about what a config can't say].
79
+ # Shows become one rule each, from their nights still to come.
80
+ def self.export(client, state_path: nil, now: Time.now)
81
+ state = state_path && File.exist?(state_path) ? YAML.safe_load_file(state_path) || {} : {}
82
+ ours = (state["sequences"] || {}).values + (state["events"] || {}).values
83
+ seqs = client.sequence_list
84
+ names = seqs.to_h { [_1["id"], _1["alias"]] }
85
+ sequences = seqs.reject { _1["id"].start_with?(BUILTIN_PREFIX) || ours.include?(_1["id"]) }.to_h do |s|
86
+ effects = s["effects"].to_h { [_1["effectType"], _1["value"]] }
87
+ [s["alias"], effects.empty? ? {"colors" => s["pattern"]} : {"colors" => s["pattern"], "effects" => effects}]
88
+ end
89
+ notes = []
90
+ schedule = client.event_list.reject { ours.include?(_1["id"]) }.filter_map do |e|
91
+ nights = e["occurrences"].map { [Time.parse(_1["start"]).localtime, Time.parse(_1["end"]).localtime] }
92
+ .select { |_, finish| finish > now }.sort
93
+ days = nights.map { _1[0].to_date }
94
+ next if days.empty?
95
+ unless days.each_cons(2).all? { |a, b| b == a + 1 }
96
+ notes << "#{e["alias"]}: its nights aren't in a row (#{days.map(&:iso8601).join(", ")}); write rules for them by hand"
97
+ next
98
+ end
99
+ notes << "#{e["alias"]}: plays on some zones only; a rule plays on every zone" unless e["zoneSerials"] == [ALL_ZONES]
100
+ start, finish = nights[0]
101
+ rule = {"name" => e["alias"]}
102
+ rule.merge!(days.size == 1 ? {"on" => days[0]} : {"from" => days[0], "to" => days[-1]})
103
+ rule["start"] = e["flags"].include?("StartAtDusk") ? "dusk" : start.strftime("%H:%M")
104
+ rule["end"] = finish.strftime("%H:%M")
105
+ rule["sequences"] = e["sequences"].map do |q|
106
+ name = names.fetch(q["sequenceId"], q["sequenceId"])
107
+ q["duration"] == DEFAULT_SECONDS ? name : "#{name}:#{q["duration"]}"
108
+ end
109
+ rule
110
+ end
111
+ [{"sequences" => sequences, "schedule" => schedule}, notes]
112
+ end
113
+
77
114
  attr_reader :bridge_seqs # the bridge's sequences, as read by the last #plan
78
115
 
79
116
  def initialize(client, config, state_path: nil, adopt: false, now: Time.now)
@@ -223,6 +260,20 @@ module Everlights
223
260
 
224
261
  # --- dates ---
225
262
 
263
+ # The dates of an iCalendar feed's events, in local time; `match` keeps events whose title contains it.
264
+ # ponytail: an event counts on its start date only: a recurring one (RRULE) on its first, a multi-day one
265
+ # on its first day. Team and school feeds list each event; expand RRULE if a feed needs it.
266
+ def self.ics_dates(text, match = nil)
267
+ text.gsub("\r\n", "\n").gsub(/\n[ \t]/, "") # unfold continued lines
268
+ .scan(/^BEGIN:VEVENT\n(.*?)^END:VEVENT$/m).filter_map do |(event)|
269
+ next if event.match?(/^STATUS:CANCELLED$/)
270
+ next if match && !event[/^SUMMARY[^:\n]*:(.*)$/, 1].to_s.downcase.include?(match.to_s.downcase)
271
+ m = event.match(/^DTSTART[^:\n]*:(\d{4})(\d\d)(\d\d)(?:T(\d\d)(\d\d)(\d\d)(Z)?)?/) or next
272
+ y, mo, d, h, mi, s = m.captures.first(6).map(&:to_i)
273
+ m[7] ? Time.utc(y, mo, d, h, mi, s).localtime.to_date : Date.new(y, mo, d) # floating and TZID times: their own date
274
+ end.uniq
275
+ end
276
+
226
277
  # Anonymous Gregorian algorithm.
227
278
  def self.easter(year)
228
279
  a, b, c = year % 19, year / 100, year % 100
@@ -313,7 +364,7 @@ module Everlights
313
364
  start = check(where) { parse_start(r.fetch("start", defaults["start"])) }
314
365
  finish = check(where) { parse_hm(r.fetch("end", defaults["end"])) }
315
366
  if start&.dig(:dusk) && !(@cfg.dig("location", "lat") && @cfg.dig("location", "lon"))
316
- @errors << "#{where}: dusk needs `location: {lat:, lon:}` in the config"
367
+ @errors << "rules that start at dusk need `location: {lat:, lon:}` in the config"
317
368
  end
318
369
  seconds = r.fetch("seconds", defaults["seconds"])
319
370
  @errors << "#{where}: needs sequences" if Array(r["sequences"]).empty?
@@ -328,18 +379,41 @@ module Everlights
328
379
  end
329
380
 
330
381
  def matcher(r, where)
331
- on, every, range = r["on"], r["every"], r.key?("from") || r.key?("to")
332
- if [on, every].compact.size + (range && !every ? 1 : 0) != 1
333
- @errors << "#{where}: needs exactly one of `on:`, `from:`/`to:`, or `every:`"
382
+ on, every, range, ics = r["on"], r["every"], r.key?("from") || r.key?("to"), r["ics"]
383
+ if [on, every, ics].compact.size + (range && !every ? 1 : 0) != 1
384
+ @errors << "#{where}: needs exactly one of `on:`, `from:`/`to:`, `every:`, or `ics:`"
334
385
  return nil
335
386
  end
336
387
  return check(where) { on_matcher(on) } if on
388
+ if ics
389
+ dates = check(where) { Sync.ics_dates(fetch(ics), r["match"]) }
390
+ return dates && ->(d) { dates.include?(d) }
391
+ end
337
392
  in_range = range ? check(where) { range_matcher(r["from"], r["to"]) } : ->(_) { true }
338
393
  return in_range unless every && in_range
339
394
  days = check(where) { Array(every).map { weekday(_1) } }
340
395
  days && ->(d) { days.include?(d.wday) && in_range.(d) }
341
396
  end
342
397
 
398
+ # ponytail: fetched on every plan, and `web` plans on each save; cache it if a slow feed makes the page drag
399
+ def fetch(source)
400
+ src = source.to_s.strip
401
+ raise Error, "`ics:` needs a URL or a file path" if src.empty?
402
+ return File.read(src) unless src.match?(%r{\A(https?|webcal)://}i)
403
+ uri = URI(src.sub(/\Awebcal/i, "https"))
404
+ 3.times do
405
+ res = Net::HTTP.get_response(uri)
406
+ return res.body if res.is_a?(Net::HTTPSuccess)
407
+ raise Error, "#{src} -> #{res.code}" unless res.is_a?(Net::HTTPRedirection)
408
+ uri = URI.join(uri, res["location"])
409
+ end
410
+ raise Error, "#{src}: too many redirects"
411
+ rescue Error
412
+ raise
413
+ rescue StandardError => e # no network, no such file, bad TLS, ...
414
+ raise Error, "can't read #{src}: #{e.message}"
415
+ end
416
+
343
417
  def on_matcher(v)
344
418
  at = date_expr(v)
345
419
  ->(d) { (d.year - 1..d.year + 1).any? { at.(_1) == d } } # offsets can cross a year boundary
@@ -275,6 +275,11 @@ function colorsOf(name) {
275
275
  return S.bridge_sequences.find((s) => s.name.toLowerCase() === lower)?.colors || [];
276
276
  }
277
277
  const hex = (c) => "#" + String(c).replace(/^#/, "");
278
+ // the same count of colors, evenly from the first to the last (as "FIRST..LAST:N" does in the config)
279
+ function blend(colors) {
280
+ const [a, b] = [colors[0], colors.at(-1)].map((c) => [1, 3, 5].map((i) => parseInt(hex(c).slice(i, i + 2), 16)));
281
+ return colors.map((_, i) => a.map((v, k) => Math.round(v + (b[k] - v) * i / (colors.length - 1)).toString(16).padStart(2, "0")).join("").toUpperCase());
282
+ }
278
283
  function stripe(colors) {
279
284
  if (!colors.length) return "transparent";
280
285
  if (colors.length === 1) return hex(colors[0]);
@@ -329,6 +334,7 @@ function focusRule(name) {
329
334
 
330
335
  // --- rules ---
331
336
  function when(r) {
337
+ if (r.ics != null) return r.match ? `calendar feed, "${r.match}"` : "calendar feed";
332
338
  if (r.on != null) return String(r.on);
333
339
  const span = r.from != null ? `${r.from} to ${r.to}` : "all year";
334
340
  const ev = r.every ? [].concat(r.every) : null;
@@ -383,7 +389,7 @@ function text(obj, key, attrs = {}) {
383
389
  }
384
390
 
385
391
  function ruleBody(r, ri) {
386
- const once = r.on != null;
392
+ const kind = r.ics != null ? "ics" : r.on != null ? "on" : "span";
387
393
  const every = r.every ? [].concat(r.every).map((d) => DAYS.find((x) => x.toLowerCase() === String(d).slice(0, 3).toLowerCase())) : DAYS;
388
394
  const setDays = (days) => {
389
395
  if (days.length === 7 && r.from != null) delete r.every; else r.every = days;
@@ -397,11 +403,18 @@ function ruleBody(r, ri) {
397
403
  save(true);
398
404
  } })),
399
405
  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(); }
406
+ for (const k of ["on", "from", "to", "every", "ics", "match"]) delete r[k];
407
+ if (e.target.value === "on") r.on = "Dec 25";
408
+ else if (e.target.value === "ics") r.ics = "";
409
+ else r.every = DAYS.slice();
402
410
  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" }))
411
+ } }, el("option", { value: "on", selected: kind === "on" }, "One night a year"), el("option", { value: "span", selected: kind === "span" }, "Several nights"),
412
+ el("option", { value: "ics", selected: kind === "ics" }, "Days in a calendar feed"))),
413
+ kind === "on" ? field("Date", text(r, "on", { placeholder: "Dec 25, Easter-2, 4th Thursday of November" }))
414
+ : kind === "ics" ? [
415
+ field("Feed", text(r, "ics", { placeholder: "https://… .ics (webcal:// works too)" })),
416
+ field("Title has", text(r, "match", { placeholder: "e.g. Bobcats; blank for every event" })),
417
+ ]
405
418
  : [
406
419
  field("From", el("div", { className: "pair" },
407
420
  text(r, "from", { placeholder: "Dec 1", "aria-label": "From" }), el("span", { className: "muted" }, "to"),
@@ -539,6 +552,8 @@ function seqEditor(name, { card = false } = {}) {
539
552
  onclick: () => { d.colors.splice(i, 1); changed(); } }, "×"))),
540
553
  el("button", { className: "plus", "aria-label": `Add a color to ${name}`, title: "Add a color",
541
554
  onclick: () => { d.colors.push(d.colors.at(-1) || "FFFFFF"); changed(); } }, "+"),
555
+ d.colors.length > 2 && el("button", { className: "plus", "aria-label": `Blend ${name} from its first color to its last`,
556
+ title: "Blend: fill the colors between the first and last evenly", onclick: () => { d.colors = blend(d.colors); changed(); } }, "↔"),
542
557
  ),
543
558
  fx.map(([type, value], i) => el("div", { className: "fx" },
544
559
  el("select", { "aria-label": "Effect", onchange: (e) => { fx[i][0] = e.target.value; setFx(); } },
@@ -651,7 +666,7 @@ function refreshPop() {
651
666
  // --- status, saving, applying ---
652
667
  function renderStatus(msg) {
653
668
  const plan = S.plan || [];
654
- $("where").textContent = S.host ? `bridge ${S.host}` : "";
669
+ $("where").textContent = S.host || "";
655
670
  $("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
671
  $("apply").disabled = !!S.error || !plan.length;
657
672
  $("apply").textContent = plan.length ? `Apply ${plan.length}` : "Apply";
@@ -111,7 +111,7 @@ module Everlights
111
111
  when %w[GET /api/bridge]
112
112
  status = @c.status
113
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} })]
114
+ checks: Everlights.health(status, via_cloud: @c.is_a?(Client) && @c.cloud?).map { |ok, name, text| {ok: ok, name: name, text: text} })]
115
115
  when %w[POST /api/bridge]
116
116
  case JSON.parse(body)["action"]
117
117
  when "time" then @c.set_time(Time.now)
@@ -142,6 +142,12 @@ module Everlights
142
142
  [config["defaults"], *config["schedule"]].each do |r|
143
143
  %w[start end].each { r[_1] = hm.(r[_1]) if r.is_a?(Hash) && r.key?(_1) }
144
144
  end
145
+ # a gradient ("FF0000..0000FF:5") reaches the page as the colors it makes, and is saved as them
146
+ (config["sequences"].is_a?(Hash) ? config["sequences"] : {}).each_value do |s|
147
+ s["colors"] = Everlights.colors(s["colors"]) if s.is_a?(Hash) && Array(s["colors"]).any? { _1.to_s.include?("..") }
148
+ rescue Error
149
+ nil # a bad one is left for the plan to report
150
+ end
145
151
  config
146
152
  end
147
153
 
@@ -165,9 +171,11 @@ module Everlights
165
171
  def self.dump(config)
166
172
  doc = YAML.parse_stream(YAML.dump(config))
167
173
  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
174
+ next unless n.respond_to?(:children) && n.children&.all?(Psych::Nodes::Scalar)
175
+ next unless n.is_a?(Psych::Nodes::Sequence) || (n.is_a?(Psych::Nodes::Mapping) && n.children.size <= 4)
176
+ n.style = n.class::FLOW
177
+ # "Name:30" can't be plain inside [...]; let libyaml quote it rather than tag it `! 'Name:30'`
178
+ n.children.each { _1.quoted = true if _1.plain }
171
179
  end
172
180
  doc.to_yaml.delete_prefix("---\n")
173
181
  end
@@ -175,7 +183,7 @@ module Everlights
175
183
  def state
176
184
  config = load
177
185
  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")}
186
+ horizon: Integer(config["horizon_days"] || 120, exception: false) || 120, host: (@c.to_s if @c.is_a?(Client))}
179
187
  sync = Sync.new(@c, config, state_path: @state_path)
180
188
  plan = begin
181
189
  sync.plan
data/lib/everlights.rb CHANGED
@@ -20,16 +20,33 @@ module Everlights
20
20
  BUILTIN_PREFIX = "00000000-0000-0000-0000-" # ids of EverLights' stock sequences
21
21
  DEFAULT_SECONDS = 20
22
22
  EFFECTS = %w[bars blink chase fade gradient lightning melt pingPong random reverseChase strobe twinkle wipe].freeze
23
+ # Firmware B5010 (Oct 2026) answers every endpoint but GET /v1 with 410 {"error":"gone","cloud":true}.
24
+ NO_LOCAL_CONTROL = "the bridge's firmware has turned off local control (410 gone): firmware B5010 and later " \
25
+ "only take commands from the EverLights cloud. Run `everlights login` to send them that way."
23
26
 
24
27
  class Client
25
- def initialize(host = nil, timeout: 10)
26
- host ||= ENV["EVERLIGHTS_HOST"]
27
- raise Error, "no host: pass one or set EVERLIGHTS_HOST" unless host
28
- uri = URI("http://#{host}")
28
+ WRITE_GAP = 0.25 # seconds between writes through the cloud; the bridge misbehaves when they stack up
29
+
30
+ # host: the bridge on the LAN. cloud: an Everlights::Cloud, for firmware B5010+ (no local control).
31
+ def initialize(host = nil, timeout: 10, cloud: nil)
32
+ if (@cloud = cloud)
33
+ raise Error, "not logged in; run `everlights login`" unless cloud.bridge
34
+ uri = URI(cloud.tunnel)
35
+ @prefix = "#{uri.path}/#{cloud.bridge}/proxy"
36
+ timeout = Cloud::TIMEOUT
37
+ else
38
+ host ||= ENV["EVERLIGHTS_HOST"]
39
+ raise Error, "no bridge: run `everlights login`, or pass --host or set EVERLIGHTS_HOST for a local one" unless host
40
+ uri = URI("http://#{host}")
41
+ end
29
42
  @http = Net::HTTP.new(uri.host, uri.port)
43
+ @http.use_ssl = uri.scheme == "https"
30
44
  @http.open_timeout = @http.read_timeout = timeout
31
45
  end
32
46
 
47
+ def cloud? = !!@cloud
48
+ def to_s = @cloud ? "bridge #{@cloud.bridge} via the EverLights cloud" : "bridge #{@http.address}"
49
+
33
50
  def sequences = Sequences.new(self)
34
51
  def calendar = Calendar.new(self)
35
52
 
@@ -131,27 +148,56 @@ module Everlights
131
148
  def get(path) = request(Net::HTTP::Get, path)
132
149
 
133
150
  def request(verb, path, body = nil)
134
- req = verb.new(path, "Content-Type" => "application/json")
135
- req.body = JSON.generate(body) if body
136
- res = @http.request(req)
151
+ pace if @cloud && (verb != Net::HTTP::Get || path.end_with?("/reboot"))
152
+ res = send_request(verb, path, body)
153
+ # the tunnel turned the token away before the bridge saw the request, so once more is safe
154
+ res = send_request(verb, path, body, fresh: true) if @cloud && res.code == "401"
155
+ raise Error, NO_LOCAL_CONTROL if res.code == "410" && res.body.to_s.match?(/"cloud"\s*:\s*true/)
137
156
  raise Error, "#{verb::METHOD} #{path} -> #{res.code}: #{res.body}" unless res.is_a?(Net::HTTPSuccess)
138
157
  res.body.to_s.empty? ? nil : JSON.parse(res.body)
139
158
  end
140
159
 
160
+ def send_request(verb, path, body, fresh: false)
161
+ req = verb.new(@cloud ? "#{@prefix}#{path}#{"/" if path == "/v1"}" : path, "Content-Type" => "application/json")
162
+ req["Authorization"] = "Bearer #{@cloud.tunnel_token(fresh: fresh)}" if @cloud
163
+ req.body = JSON.generate(body) if body
164
+ @http.request(req)
165
+ end
166
+
167
+ def pace
168
+ wait = WRITE_GAP - (Process.clock_gettime(Process::CLOCK_MONOTONIC) - (@last_write || 0))
169
+ sleep wait if wait.positive?
170
+ @last_write = Process.clock_gettime(Process::CLOCK_MONOTONIC)
171
+ end
172
+
141
173
  def colors(pattern) = Everlights.colors(pattern)
142
174
  def effects_body(effects) = Everlights.effects(effects)
143
175
  def stamp(t) = Everlights.stamp(t)
144
176
  end
145
177
 
146
- # ["#ff0000", ...] -> ["FF0000", ...]
178
+ # ["#ff0000", ...] -> ["FF0000", ...]; a gradient "FF0000..0000FF:5" becomes its 5 colors
147
179
  def self.colors(pattern)
148
- Array(pattern).map do |c|
149
- hex = c.to_s.delete_prefix("#").upcase
180
+ Array(pattern).flat_map do |c|
181
+ hex = c.to_s.delete("#").upcase
182
+ next gradient(hex) if hex.include?("..")
150
183
  raise Error, "bad color #{c.inspect}, want RRGGBB" unless hex.match?(/\A\h{6}\z/)
151
184
  hex
152
185
  end
153
186
  end
154
187
 
188
+ # "FF7A1E..FF9E3D:4" -> 4 colors evenly from the first to the last; middle stops bend it: "FF0000..FFFFFF..0000FF:9"
189
+ def self.gradient(text)
190
+ m = text.match(/\A(\h{6}(?:\.\.\h{6})+):(\d+)\z/) or raise Error, "bad gradient #{text.inspect}, want RRGGBB..RRGGBB:COUNT"
191
+ stops = m[1].split("..").map { |h| h.scan(/../).map { _1.to_i(16) } }
192
+ count = m[2].to_i
193
+ raise Error, "gradient #{text.inspect}: count must be at least 2" if count < 2
194
+ (0...count).map do |i|
195
+ at = i * (stops.size - 1) / (count - 1).to_f # position along the stops, 0..stops-1
196
+ k = [at.floor, stops.size - 2].min
197
+ stops[k].zip(stops[k + 1]).map { |a, b| format("%02X", (a + (b - a) * (at - k)).round) }.join
198
+ end
199
+ end
200
+
155
201
  # {chase: 100} or the API's [{"effectType" => "chase", "value" => 100}] -> API form with string keys
156
202
  def self.effects(effects)
157
203
  (effects || {}).map do |e|
@@ -163,20 +209,25 @@ module Everlights
163
209
 
164
210
  # [[ok, name, text], ...] from Client#status; ok is true, false, or :info.
165
211
  # ponytail: thresholds are guesses from one bridge; tune when real failures show what matters
166
- def self.health(b, now: Time.now)
212
+ # via_cloud: commands go through the cloud, so the bridge's local control being off is expected.
213
+ # Firmware B5010 stopped reporting network and memory; those show as info, not warnings.
214
+ def self.health(b, now: Time.now, via_cloud: false)
167
215
  ago = ->(v) { v ? ((now - Time.parse(v)) / 60).round : Float::INFINITY }
168
216
  mins = ->(m) { m.infinite? ? "never" : "#{m} min ago" }
169
217
  cloud, radio = ago.(b["lastServerCheckin"]), ago.(b["lastRadioResponse"])
218
+ unreported = ->(name) { [:info, name, "not reported by firmware #{b["firmwareVersion"]}"] }
170
219
  [
220
+ *([[via_cloud ? :info : false, "local control",
221
+ "off in firmware #{b["firmwareVersion"]}; #{via_cloud ? "commands go through the cloud" : "run `everlights login`"}"]] if b["cloud"]),
171
222
  [!!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"],
223
+ b.key?("network") ? [!!b.dig("network", "ntp"), "clock", "ntp #{b.dig("network", "ntp") ? "on" : "off"}"] : unreported.("clock"),
224
+ b.key?("minFreeHeap") ? [b["minFreeHeap"].to_i >= 10_000, "memory", "lowest free since boot #{b["minFreeHeap"]} bytes (warn under 10000)"] : unreported.("memory"),
225
+ [radio <= 10, "radio", "answered #{mins.(radio)}#{", #{b["radioRebootCount"]} radio reboots" if b["radioRebootCount"]}"],
175
226
  *b["zones"].map do |z|
176
227
  last = ago.(z["lastResponseDate"])
177
228
  [!!z["active"] && last <= 10, "zone #{z["serial"]}", "#{z["active"] ? "active" : "inactive"}, answered #{mins.(last)}, #{z["rebootCount"]} reboots"]
178
229
  end,
179
- [:info, "reboots", "#{b["rebootCount"]} total, last reset reason #{b["resetReason"]}"]
230
+ [:info, "reboots", "#{b["rebootCount"]} total#{", last reset reason #{b["resetReason"]}" if b["resetReason"]}"]
180
231
  ]
181
232
  end
182
233
 
@@ -273,3 +324,4 @@ module Everlights
273
324
  end
274
325
 
275
326
  require_relative "everlights/sync"
327
+ require_relative "everlights/cloud"
@@ -5,18 +5,20 @@ description: Control EverLights permanent outdoor lights through the local bridg
5
5
 
6
6
  # EverLights
7
7
 
8
- The `everlights` CLI talks to the bridge on the LAN (no auth). It needs `EVERLIGHTS_HOST` (bridge IP) or `--host`. Lists print text (add `--json` for JSON); `status`, `zones` and `show` print JSON.
8
+ The `everlights` CLI talks to the bridge through the EverLights cloud once the user has run `everlights login` (firmware B5010 and later need this). On older firmware it can use the LAN instead with `EVERLIGHTS_HOST` (the bridge's IP) or `--host`. Lists print text (add `--json` for JSON); `status`, `zones` and `show` print JSON.
9
9
 
10
10
  ## Before you write anything
11
11
 
12
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
- 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.
14
+ 3. If a command fails with "turned off local control" or "not logged in", the bridge is on firmware B5010 or later and needs `everlights login EMAIL`. Ask the user to run it themselves. Never ask for their password or handle it yourself.
15
+ 4. 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
16
 
16
17
  ## Concepts
17
18
 
18
19
  - **Zone**: one run of pixels, identified by serial. `everlights zones` lists them. Commands default to all zones; `--zone SERIAL` narrows one.
19
20
  - **Sequence**: a saved pattern of hex colors (`RRGGBB`, repeated along the run) plus up to a few effects. The bridge has about 96 built-ins (`everlights sequence list xmas` searches by name; `*` marks user-made ones). Sequences added here show up in the EverLights app under Personal. Built-in names include "Birthday", so give personal sequences distinct names (e.g. "My Birthday").
21
+ - **Gradient**: anywhere a color goes, `FF0000..0000FF:5` is 5 colors blended evenly; middle stops bend it (`FF0000..FFFFFF..0000FF:9`).
20
22
  - **Effect**: `--effect TYPE=N`, N 0-255 (default 128; higher seems faster). Types: bars blink chase fade gradient lightning melt pingPong random reverseChase strobe twinkle wipe. Built-ins often stack two, e.g. `fade` + `reverseChase`.
21
23
  - **Manual program** (`set`/`play`): shows immediately. During a scheduled show, it only lasts until the show's next sequence change (about 20 seconds). Outside a show it stays. `clear` hands control back to the calendar.
22
24
  - **Calendar entry**: a scheduled show. It cycles its sequences (`NAME:SECONDS`, default 20) during each night's window. The bridge stores it, so it runs with no computer on. Default window: dusk to 23:00.
@@ -56,9 +58,9 @@ el.calendar.remove "2026-12-24", "Christmas"
56
58
 
57
59
  ## Sync (planning shows months ahead)
58
60
 
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`.
61
+ 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. If there's no config yet, `everlights init` writes a starter one. The format reference is `config/everlights.example.yml`.
60
62
 
61
- 1. Edit `sequences:` or `schedule:`. Rules higher in the list win nights they share.
63
+ 1. Edit `sequences:` or `schedule:`. Rules higher in the list win nights they share. For a team's games or other events in a calendar, a rule can use `ics: <feed URL>` with `match: <title text>`.
62
64
  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
65
  3. Run `everlights sync` only after they confirm.
64
66
 
@@ -72,4 +74,3 @@ Sync only changes what it created itself. Config problems abort before anything
72
74
  - Whether "dusk" shows really start at dusk. The bridge stores a 17:00 placeholder, so they may start at 17:00. Use `--start` when the exact time matters.
73
75
  - What N means for each effect.
74
76
  - Whether a calendar entry overlapping another replaces it or conflicts. Check `calendar list` afterwards.
75
- - `calendar remove` on a night that isn't an entry's last edits the event with a PUT. The API spec has it; not yet tried on the bridge.
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.2.0
4
+ version: 1.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ricky Chilcott
@@ -9,9 +9,10 @@ bindir: exe
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies: []
12
- description: 'Control EverLights permanent lights over the LAN: show colors, manage
13
- sequences, and schedule shows ahead on the bridge''s calendar. Unofficial; stdlib
14
- only.'
12
+ description: 'Control EverLights permanent lights: show colors, manage sequences,
13
+ and schedule a year of shows ahead on the bridge''s calendar from one config file,
14
+ with holidays, calendar feeds and gradients. Reaches firmware B5010+ bridges through
15
+ the EverLights cloud, older ones on the LAN. Unofficial; stdlib only.'
15
16
  email: ricky@rickychilcott.com
16
17
  executables:
17
18
  - everlights
@@ -20,8 +21,10 @@ extra_rdoc_files: []
20
21
  files:
21
22
  - LICENSE
22
23
  - README.md
24
+ - config/everlights.example.yml
23
25
  - exe/everlights
24
26
  - lib/everlights.rb
27
+ - lib/everlights/cloud.rb
25
28
  - lib/everlights/sync.rb
26
29
  - lib/everlights/web.html
27
30
  - lib/everlights/web.rb
@@ -50,5 +53,6 @@ required_rubygems_version: !ruby/object:Gem::Requirement
50
53
  requirements: []
51
54
  rubygems_version: 4.0.20
52
55
  specification_version: 4
53
- summary: Client and CLI for the EverLights Smart Lights Bridge local API
56
+ summary: Client and CLI for the EverLights v3 Smart Lights Bridge, through the cloud
57
+ or the local API
54
58
  test_files: []