everlights 0.1.1 → 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: ee4915d68adebdaaaa5d1ea02be82d7530ebbdee06fbfd2905b73aa49fa9cf6e
4
- data.tar.gz: f6ed7abeccd0e26b23795679e3cf8dcf876b73163cd684d9ffe109ceadc8a085
3
+ metadata.gz: f14eeff731dd3d21e13f7a8cc9e80ab6654d2ef9ab40695ea581f876f3539270
4
+ data.tar.gz: ef5c19da8d2f55f9372de48752637ec345144bbd1deeeaef5e9b664c24b21093
5
5
  SHA512:
6
- metadata.gz: 011d597b5b53676084adad56466ddb9dde0fa77f8e6c6a37264078495a10959e3350a90e0d365afbcf24c4c0a3a0188b0dd3476808a1fc10bf9f63761de0daee
7
- data.tar.gz: d99fd9e1c63b2d3e70edd0e0a0ce3cc072a677f4a3c4734b65d90bcdeb45662f2f5e1f42f49eea37a9b5fbdbd6b4d59060492a1478aca51dedb7a165cdd6050a
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,13 +87,28 @@ 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.
89
97
 
98
+ ### In a browser
99
+
100
+ ```sh
101
+ everlights web # http://localhost:4567 (--port to change)
102
+ ```
103
+
104
+ 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.
105
+
106
+ 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.
107
+
108
+ **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.
109
+
110
+ 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.
111
+
90
112
  To keep the calendar topped up, run it on a schedule, for example monthly from cron:
91
113
  `0 9 1 * * cd ~/everlights && everlights sync >> config/sync.log 2>&1`
92
114
 
@@ -97,7 +119,8 @@ To only be told when it needs a sync, use `everlights sync --check`. It prints t
97
119
  ```ruby
98
120
  require "everlights"
99
121
 
100
- 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"]
101
124
 
102
125
  el.play "Hallows Eve"
103
126
  el.set "FF0000", "00FF00", effects: {twinkle: 100}
@@ -147,6 +170,19 @@ The bridge (an ESP32) serves plain JSON over HTTP on port 80, with no authentica
147
170
 
148
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.
149
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
+
150
186
  Not yet confirmed:
151
187
  - What each effect's 0–255 value does.
152
188
  - How the bridge handles overlapping calendar entries.
@@ -166,11 +202,11 @@ ruby -Ilib -e 'Dir["test/*_test.rb"].each { require "./#{_1}" }'
166
202
 
167
203
  The tests run against a fake bridge, so no hardware is needed. CI runs them on every push and pull request.
168
204
 
169
- 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.
170
206
 
171
207
  ## Credits
172
208
 
173
- 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.
174
210
 
175
211
  ## License
176
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,9 +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)
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
37
45
 
38
46
  Options:
39
47
  TXT
@@ -41,7 +49,8 @@ TXT
41
49
  opts = {effects: {}, limit: 365}
42
50
  parser = OptionParser.new do |o|
43
51
  o.banner = USAGE
44
- 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 }
45
54
  o.on("--config PATH", "config file (default $EVERLIGHTS_CONFIG, then config/everlights.yml)") { opts[:config] = _1 }
46
55
  o.on("--zone SERIAL", "limit set/play/off/clear/show to a zone (repeatable)") { (opts[:zones] ||= []) << _1 }
47
56
  o.on("--effect E[=N]", "N 0-255 (default 128): #{Everlights::EFFECTS.join(" ")}") do |e|
@@ -56,6 +65,7 @@ parser = OptionParser.new do |o|
56
65
  o.on("--yes", "confirm bridge reboot") { opts[:yes] = true }
57
66
  o.on("--dry-run", "sync: print the plan only") { opts[:dry_run] = true }
58
67
  o.on("--check", "sync: plan only, exit 2 if anything would change") { opts[:check] = true }
68
+ o.on("--port N", Integer, "web: port (default 4567)") { opts[:port] = _1 }
59
69
  o.on("--adopt", "sync: take over bridge items whose names match the config") { opts[:adopt] = true }
60
70
  end
61
71
  parser.parse!
@@ -66,15 +76,53 @@ def json(obj) = puts(JSON.pretty_generate(obj))
66
76
  begin
67
77
  config_path = opts[:config] || ENV["EVERLIGHTS_CONFIG"] || "config/everlights.yml"
68
78
  config = if File.exist?(config_path) then Everlights::Sync.load_config(config_path)
69
- 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}"
70
80
  end
71
81
  ENV["TZ"] = config["timezone"] if config&.dig("timezone")
72
- el = Everlights::Client.new(opts[:host] || ENV["EVERLIGHTS_HOST"] || config&.dig("bridge", "host"))
73
- zones = opts[:zones]
74
82
  cmd = ARGV.shift
75
83
  cmd = "#{cmd} #{ARGV.shift}" if %w[sequence calendar].include?(cmd) ||
76
84
  (cmd == "bridge" && %w[health time reboot].include?(ARGV.first))
77
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]
78
126
 
79
127
  case cmd
80
128
  when "bridge"
@@ -83,8 +131,8 @@ begin
83
131
  else
84
132
  at = ->(v) { v ? Time.parse(v).localtime.strftime("%Y-%m-%d %H:%M:%S") : "?" }
85
133
  net = b["network"] || {}
86
- puts "Bridge #{b["serial"]} firmware #{b["firmwareVersion"]}, radio #{b["radioFirmwareVersion"]}"
87
- 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"], "?")}"
88
136
  puts " cloud #{b["serverReachable"] ? "reachable" : "UNREACHABLE"}, last check-in #{at.(b["lastServerCheckin"])}"
89
137
  puts " reboots #{b["rebootCount"]}"
90
138
  b["zones"].each do |z|
@@ -95,22 +143,7 @@ begin
95
143
  end
96
144
  end
97
145
  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
- ]
146
+ checks = Everlights.health(el.status, via_cloud: el.cloud?)
114
147
  checks.each { |ok, name, text| puts "#{{info: "info", true => "ok ", false => "WARN"}[ok]} #{name.ljust(19)} #{text}" }
115
148
  exit 2 unless checks.all? { _1[0] }
116
149
  when "bridge time"
@@ -196,9 +229,8 @@ begin
196
229
  puts "removed #{name.join(" ")} on #{date}"
197
230
 
198
231
  when "sync"
199
- 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
232
+ raise Everlights::Error, "no config at #{config_path}; run `everlights init` to start one" unless config
233
+ plan = Everlights::Sync.new(el, config, state_path: Everlights::Sync.state_path(config_path), adopt: opts[:adopt]).plan
202
234
  puts plan
203
235
  if plan.empty? then nil
204
236
  elsif opts[:check] then exit 2
@@ -208,6 +240,23 @@ begin
208
240
  puts "\nApplied."
209
241
  end
210
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
+
255
+ when "web"
256
+ raise Everlights::Error, "no config at #{config_path}; run `everlights init` to start one" unless config
257
+ require_relative "../lib/everlights/web"
258
+ Everlights::Web.new(el, config_path, port: opts[:port] || 4567).start
259
+
211
260
  else abort parser.help
212
261
  end
213
262
  rescue Everlights::Error, IndexError, ArgumentError, TypeError, Date::Error, SystemCallError, Net::OpenTimeout => e
@@ -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