Repository navigation
Expand file tree
/
Copy pathdriver.lua
More file actions
691 lines (608 loc) · 23.7 KB
/
Copy pathdriver.lua
File metadata and controls
691 lines (608 loc) · 23.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
--[[
================================================================================
AirGradient Air Quality Monitor - Control4 Driver
================================================================================
Uses the AirGradient LOCAL API only (no cloud dependency):
GET /measures/current -> all sensor readings
GET /config -> device configuration
PUT /config -> change device configuration
Reference: https://github.com/airgradienthq/arduino/blob/master/docs/local-server.md
NOTES ON THIS FILE
------------------
This is written using the Lua idioms common to published Control4 drivers
(C4:urlGet / C4:urlPut async callbacks, C4:AddTimer / OnTimerExpired,
C4:UpdateProperty, C4:FireEvent, C4:SendToProxy, ExecuteCommand,
OnPropertyChanged). Control4's SDK reference is login-gated, so if any
function signature below throws in the Driver Editor's Lua console
(e.g. AddTimer/urlGet argument order on your SDK version), open the
built-in Lua Reference in Composer Pro / Driver Editor and adjust that
one call - the surrounding logic does not need to change.
================================================================================
]]--
-- ============================================================
-- CONSTANTS
-- ============================================================
-- Confirmed against a real, currently-working thermostatV2 driver (Finite
-- Labs' ESPHome Climate driver). PROXY_BINDING matches proxybindingid="5001".
-- TEMPERATURE_OUTPUT_BINDING/HUMIDITY_OUTPUT_BINDING match the separate
-- Temperature (id=5010) and Humidity (id=5012) output connections in driver.xml.
local PROXY_BINDING = 5001
local TEMPERATURE_OUTPUT_BINDING = 5010
local HUMIDITY_OUTPUT_BINDING = 5012
-- Control4's real timer API is numeric: C4:AddTimer(delay, units, repeating)
-- RETURNS a numeric timer ID; C4:KillTimer(idTimer) and the OnTimerExpired(idTimer)
-- callback both take that same number. There is no such thing as a named timer -
-- you track which purpose each returned ID belongs to yourself.
local gPollTimerId = nil
local gRetryTimerId = nil
local DEFAULT_POLL_SECONDS = 10
local MAX_CONSECUTIVE_FAILURES = 3
-- Runtime state
local LastGood = {} -- last successfully parsed /measures/current table
local ConsecutiveFailures = 0
local SensorOnline = nil -- nil = unknown, true/false once known
local AlertState = {
pm25 = false,
co2 = false,
tvoc = false,
nox = false,
}
-- ============================================================
-- MINIMAL JSON DECODER (self-contained, no external dependency)
-- ============================================================
-- AirGradient responses are flat/shallow JSON objects, but this
-- handles nested objects/arrays too (used by /config's "corrections").
local function JsonDecode(str)
local pos = 1
local len = #str
local function skipWhitespace()
while pos <= len do
local c = str:sub(pos, pos)
if c == " " or c == "\t" or c == "\n" or c == "\r" then
pos = pos + 1
else
break
end
end
end
local parseValue -- forward declaration
local function parseString()
pos = pos + 1 -- skip opening quote
local startPos = pos
local out = {}
while pos <= len do
local c = str:sub(pos, pos)
if c == '"' then
pos = pos + 1
return table.concat(out)
elseif c == "\\" then
local nextC = str:sub(pos + 1, pos + 1)
if nextC == "n" then out[#out+1] = "\n"
elseif nextC == "t" then out[#out+1] = "\t"
elseif nextC == "r" then out[#out+1] = "\r"
elseif nextC == '"' then out[#out+1] = '"'
elseif nextC == "\\" then out[#out+1] = "\\"
elseif nextC == "/" then out[#out+1] = "/"
elseif nextC == "u" then
local hex = str:sub(pos + 2, pos + 5)
local code = tonumber(hex, 16) or 63
out[#out+1] = (code < 128) and string.char(code) or "?"
pos = pos + 4
else
out[#out+1] = nextC
end
pos = pos + 2
else
out[#out+1] = c
pos = pos + 1
end
end
return table.concat(out)
end
local function parseNumber()
local startPos = pos
while pos <= len do
local c = str:sub(pos, pos)
if c:match("[%d%.%-%+eE]") then
pos = pos + 1
else
break
end
end
return tonumber(str:sub(startPos, pos - 1))
end
local function parseObject()
pos = pos + 1 -- skip {
local obj = {}
skipWhitespace()
if str:sub(pos, pos) == "}" then
pos = pos + 1
return obj
end
while true do
skipWhitespace()
local key = parseString()
skipWhitespace()
pos = pos + 1 -- skip :
skipWhitespace()
obj[key] = parseValue()
skipWhitespace()
local c = str:sub(pos, pos)
if c == "," then
pos = pos + 1
elseif c == "}" then
pos = pos + 1
break
else
break
end
end
return obj
end
local function parseArray()
pos = pos + 1 -- skip [
local arr = {}
skipWhitespace()
if str:sub(pos, pos) == "]" then
pos = pos + 1
return arr
end
while true do
skipWhitespace()
arr[#arr+1] = parseValue()
skipWhitespace()
local c = str:sub(pos, pos)
if c == "," then
pos = pos + 1
elseif c == "]" then
pos = pos + 1
break
else
break
end
end
return arr
end
parseValue = function()
skipWhitespace()
local c = str:sub(pos, pos)
if c == "{" then
return parseObject()
elseif c == "[" then
return parseArray()
elseif c == '"' then
return parseString()
elseif str:sub(pos, pos + 3) == "true" then
pos = pos + 4
return true
elseif str:sub(pos, pos + 4) == "false" then
pos = pos + 5
return false
elseif str:sub(pos, pos + 3) == "null" then
pos = pos + 4
return nil
else
return parseNumber()
end
end
local ok, result = pcall(function()
skipWhitespace()
return parseValue()
end)
if ok then
return result
else
return nil
end
end
local function JsonEncode(tbl)
-- Minimal encoder, sufficient for the flat config PUT bodies this driver sends
local parts = {}
for k, v in pairs(tbl) do
local valStr
if type(v) == "string" then
valStr = '"' .. v:gsub('"', '\\"') .. '"'
elseif type(v) == "boolean" then
valStr = tostring(v)
elseif type(v) == "number" then
valStr = tostring(v)
elseif type(v) == "table" then
valStr = JsonEncode(v)
else
valStr = "null"
end
parts[#parts+1] = '"' .. k .. '":' .. valStr
end
return "{" .. table.concat(parts, ",") .. "}"
end
-- ============================================================
-- LOGGING
-- ============================================================
local function DebugLog(msg)
if Properties and Properties["Debug Logging"] == "On" then
C4:DebugLog("[AirGradient] " .. tostring(msg))
end
end
local function ErrorLog(msg)
C4:ErrorLog("[AirGradient] " .. tostring(msg))
end
-- ============================================================
-- HOST / URL HELPERS
-- ============================================================
local function GetBaseUrl()
local host = Properties and Properties["Host or IP Address"] or ""
host = host:gsub("^%s+", ""):gsub("%s+$", "")
if host == "" then
return nil
end
if not host:match("^https?://") then
host = "http://" .. host
end
return host
end
-- ============================================================
-- PROPERTY / UI HELPERS
-- ============================================================
local function SafeUpdateProperty(name, value)
if value == nil then return end
C4:UpdateProperty(name, tostring(value))
end
local function CelsiusToFahrenheit(c)
return (c * 9 / 5) + 32
end
-- Threshold get with numeric fallback
local function GetThreshold(propName, default)
local v = tonumber(Properties and Properties[propName])
return v or default
end
-- ============================================================
-- EXTRAS TAB (thermostatV2 "Extras" screen in Navigator)
-- ============================================================
-- The only confirmed object type for this XML (from a real driver and a
-- Control4 forum post) is type="list" - a selectable dropdown. There's no
-- confirmed plain read-only "label" type, so each sensor is shown as a
-- single-item list (its only option is the current reading). It's a workable
-- display, not a perfect fit for continuously-updating numbers - worth
-- checking how this actually looks/behaves once installed.
local function XmlEscape(s)
s = tostring(s)
s = s:gsub("&", "&"):gsub("<", "<"):gsub(">", ">"):gsub('"', """)
return s
end
local function ExtrasListObject(id, label, valueText)
valueText = valueText or "--"
return '<object type="list" id="' .. id .. '" label="' .. XmlEscape(label)
.. '" command="EXTRAS_NOOP" value="' .. XmlEscape(valueText) .. '">'
.. '<list maxselections="1" minselections="1">'
.. '<item text="' .. XmlEscape(valueText) .. '" value="' .. XmlEscape(valueText) .. '"/>'
.. '</list></object>'
end
local LastExtrasXml = nil
-- Deliberately uses the calibrated/index readings, not the raw/uncalibrated
-- ones (tvocRaw, noxRaw) or the uncompensated PM2.5 - per the request to
-- show users the calibrated sensors here, not the raw ones.
local function PushExtrasDisplay(pm25Compensated, pm01, pm10, co2, tvocIndex, noxIndex)
local parts = {}
parts[#parts+1] = ExtrasListObject("pm25", "PM2.5 (ug/m3)", pm25Compensated and tostring(pm25Compensated))
parts[#parts+1] = ExtrasListObject("pm10", "PM10 (ug/m3)", pm10 and tostring(pm10))
parts[#parts+1] = ExtrasListObject("pm01", "PM1.0 (ug/m3)", pm01 and tostring(pm01))
parts[#parts+1] = ExtrasListObject("co2", "CO2 (ppm)", co2 and tostring(co2))
parts[#parts+1] = ExtrasListObject("tvoc", "TVOC Index", tvocIndex and tostring(tvocIndex))
parts[#parts+1] = ExtrasListObject("nox", "NOx Index", noxIndex and tostring(noxIndex))
local xml = '<extras_setup><extra><section label="Air Quality">'
.. table.concat(parts) .. '</section></extra></extras_setup>'
if xml ~= LastExtrasXml then
LastExtrasXml = xml
pcall(function() C4:SendToProxy(PROXY_BINDING, "EXTRAS_SETUP_CHANGED", {XML = xml}, "NOTIFY") end)
end
end
-- ============================================================
-- ALERT EVALUATION (fires Programming events with hysteresis)
-- ============================================================
local function EvaluateAlert(key, value, highThreshold, lowThreshold, alertEventName, normalEventName)
if value == nil then return end
local wasAlert = AlertState[key]
if not wasAlert and value >= highThreshold then
AlertState[key] = true
C4:FireEvent(alertEventName)
DebugLog(alertEventName .. " fired (value=" .. tostring(value) .. ")")
elseif wasAlert and value <= lowThreshold then
AlertState[key] = false
C4:FireEvent(normalEventName)
DebugLog(normalEventName .. " fired (value=" .. tostring(value) .. ")")
end
end
-- ============================================================
-- APPLY MEASUREMENT DATA
-- ============================================================
local function ApplyMeasurements(data)
if type(data) ~= "table" then
ErrorLog("ApplyMeasurements: invalid data")
return
end
LastGood = data
ConsecutiveFailures = 0
if SensorOnline ~= true then
SensorOnline = true
C4:FireEvent("SENSOR_ONLINE")
pcall(function() C4:SendToProxy(PROXY_BINDING, "ONLINE_CHANGED", {STATE = true}, "NOTIFY") end)
end
local useCompensated = (Properties["Use Compensated Values"] ~= "No")
local unitIsF = (Properties["Temperature Display Unit"] == "Fahrenheit")
local temp_c = useCompensated and (data.atmpCompensated or data.atmp) or data.atmp
local hum = useCompensated and (data.rhumCompensated or data.rhum) or data.rhum
-- PM2.5 correction (EPA 2021 etc.) can round small real readings toward 0,
-- so this now respects the same toggle as temp/humidity instead of always
-- preferring the compensated value regardless of the property setting.
local pm25 = useCompensated and (data.pm02Compensated or data.pm02) or data.pm02
local pm01 = data.pm01 -- no compensated variant documented for PM1.0
local pm10 = data.pm10 -- no compensated variant documented for PM10
local co2 = data.rco2
local tvoc = data.tvocIndex
local nox = data.noxIndex
local wifi = data.wifi
-- ---- Properties (visible in Composer Pro + usable in Programming "Device Properties") ----
SafeUpdateProperty("PM1.0 (ug/m3)", pm01)
SafeUpdateProperty("PM2.5 (ug/m3)", pm25)
SafeUpdateProperty("PM2.5 Compensated (ug/m3)", data.pm02Compensated)
SafeUpdateProperty("PM10 (ug/m3)", pm10)
SafeUpdateProperty("CO2 (ppm)", co2)
SafeUpdateProperty("Temperature (C)", data.atmp)
SafeUpdateProperty("Temperature Compensated (C)", data.atmpCompensated)
SafeUpdateProperty("Temperature (Display)", temp_c and (unitIsF and CelsiusToFahrenheit(temp_c) or temp_c))
SafeUpdateProperty("Humidity (%)", data.rhum)
SafeUpdateProperty("Humidity Compensated (%)", data.rhumCompensated)
SafeUpdateProperty("TVOC Index", tvoc)
SafeUpdateProperty("TVOC Raw", data.tvocRaw)
SafeUpdateProperty("NOx Index", nox)
SafeUpdateProperty("NOx Raw", data.noxRaw)
SafeUpdateProperty("WiFi Signal (dBm)", wifi)
SafeUpdateProperty("Firmware Version", data.firmware)
SafeUpdateProperty("Model", data.model)
SafeUpdateProperty("Serial Number", data.serialno)
SafeUpdateProperty("Boot Count", data.bootCount)
SafeUpdateProperty("LED Mode", data.ledMode)
-- ---- Thermostat proxy (Navigator display: temperature + humidity) ----
-- Confirmed commands (from a real, working thermostatV2 driver): the main
-- proxy binding takes *_CHANGED notifications, and each output connection
-- (Temperature/Humidity) separately takes VALUE_CHANGED so Programming/other
-- drivers bound to those connections see the value too.
-- Always sends Celsius - Navigator's F/C display follows Composer Pro's
-- system-wide temperature unit setting, not a per-driver property.
if temp_c then
pcall(function()
C4:SendToProxy(PROXY_BINDING, "TEMPERATURE_CHANGED", {TEMPERATURE = tostring(temp_c), SCALE = "C"}, "NOTIFY")
C4:SendToProxy(TEMPERATURE_OUTPUT_BINDING, "VALUE_CHANGED", {
CELSIUS = tostring(temp_c),
FAHRENHEIT = tostring(CelsiusToFahrenheit(temp_c)),
})
end)
end
if hum then
local humRounded = tostring(math.floor(hum + 0.5))
pcall(function()
C4:SendToProxy(PROXY_BINDING, "HUMIDITY_CHANGED", {HUMIDITY = humRounded}, "NOTIFY")
C4:SendToProxy(HUMIDITY_OUTPUT_BINDING, "VALUE_CHANGED", {VALUE = humRounded})
end)
end
-- ---- Threshold-based Programming events ----
EvaluateAlert("pm25", pm25,
GetThreshold("PM2.5 Alert Threshold (ug/m3)", 35),
GetThreshold("PM2.5 Clear Threshold (ug/m3)", 25),
"PM25_ALERT", "PM25_NORMAL")
EvaluateAlert("co2", co2,
GetThreshold("CO2 Alert Threshold (ppm)", 1000),
GetThreshold("CO2 Clear Threshold (ppm)", 800),
"CO2_ALERT", "CO2_NORMAL")
EvaluateAlert("tvoc", tvoc,
GetThreshold("TVOC Alert Threshold", 300),
GetThreshold("TVOC Clear Threshold", 200),
"TVOC_ALERT", "TVOC_NORMAL")
EvaluateAlert("nox", nox,
GetThreshold("NOx Alert Threshold", 5),
GetThreshold("NOx Clear Threshold", 2),
"NOX_ALERT", "NOX_NORMAL")
PushExtrasDisplay(data.pm02Compensated or pm25, pm01, pm10, co2, tvoc, nox)
C4:FireEvent("DATA_REFRESHED")
end
-- ============================================================
-- FAILURE HANDLING
-- ============================================================
local function HandlePollFailure(reason)
ConsecutiveFailures = ConsecutiveFailures + 1
ErrorLog("Poll failed (" .. tostring(ConsecutiveFailures) .. "): " .. tostring(reason))
if ConsecutiveFailures >= MAX_CONSECUTIVE_FAILURES and SensorOnline ~= false then
SensorOnline = false
C4:FireEvent("SENSOR_OFFLINE")
pcall(function() C4:SendToProxy(PROXY_BINDING, "ONLINE_CHANGED", {STATE = false}, "NOTIFY") end)
end
end
-- ============================================================
-- POLLING
-- ============================================================
-- ============================================================
-- POLLING
-- ============================================================
-- Confirmed real signatures (from Control4's own public drivers-common-public
-- source): C4:urlGet(url, headers, cacheBool, callbackFn, flags) and
-- C4:urlPut(url, data, headers, cacheBool, callbackFn, flags), both returning
-- a numeric ticket. The callback receives (ticketId, strData, responseCode,
-- tHeaders, strError). Passing a specific callback function per call (rather
-- than a single global dispatcher) avoids needing to track tickets/URLs by hand.
function PollAirGradient()
local base = GetBaseUrl()
if not base then
HandlePollFailure("No Host/IP configured")
return
end
local url = base .. "/measures/current"
DebugLog("GET " .. url)
C4:urlGet(url, {}, false, OnMeasuresResponse, {})
end
function OnMeasuresResponse(ticketId, strData, responseCode, tHeaders, strError)
if strError ~= nil or responseCode ~= 200 then
HandlePollFailure("HTTP " .. tostring(responseCode) .. " err=" .. tostring(strError))
return
end
local decoded = JsonDecode(strData)
if decoded then
ApplyMeasurements(decoded)
else
HandlePollFailure("JSON parse error on /measures/current")
end
end
function PollConfig()
local base = GetBaseUrl()
if not base then return end
C4:urlGet(base .. "/config", {}, false, OnConfigResponse, {})
end
function OnConfigResponse(ticketId, strData, responseCode, tHeaders, strError)
if strError ~= nil or responseCode ~= 200 then
ErrorLog("Config GET failed: HTTP " .. tostring(responseCode) .. " err=" .. tostring(strError))
return
end
local decoded = JsonDecode(strData)
if decoded then
DebugLog("Config GET succeeded")
SafeUpdateProperty("Config: Country", decoded.country)
SafeUpdateProperty("Config: PM Standard", decoded.pmStandard)
SafeUpdateProperty("Config: LED Bar Mode", decoded.ledBarMode)
SafeUpdateProperty("Config: Display Brightness", decoded.displayBrightness)
SafeUpdateProperty("Config: LED Bar Brightness", decoded.ledBarBrightness)
end
end
function OnConfigPutResponse(ticketId, strData, responseCode, tHeaders, strError)
if strError ~= nil or (responseCode ~= 200 and responseCode ~= 204) then
ErrorLog("Config PUT failed: HTTP " .. tostring(responseCode) .. " err=" .. tostring(strError))
else
DebugLog("Config PUT succeeded")
-- Refresh measurements + config shortly after a successful change (one-shot timer)
if gRetryTimerId then gRetryTimerId = C4:KillTimer(gRetryTimerId) end
gRetryTimerId = C4:AddTimer(2, "SECONDS", false)
end
end
local function PutConfig(tParams)
local base = GetBaseUrl()
if not base then
ErrorLog("Cannot PUT config - no Host/IP configured")
return
end
local url = base .. "/config"
local body = JsonEncode(tParams)
DebugLog("PUT " .. url .. " body=" .. body)
C4:urlPut(url, body, {["Content-Type"] = "application/json"}, false, OnConfigPutResponse, {})
end
-- ============================================================
-- TIMER DISPATCH
-- ============================================================
-- Director calls this with just the numeric timer ID - no name is passed, so
-- we compare against the IDs we saved when each timer was created.
function OnTimerExpired(idTimer)
if idTimer == gPollTimerId then
PollAirGradient()
PollConfig()
-- repeating timer (see RestartPolling) re-fires on its own; nothing to re-add here
elseif idTimer == gRetryTimerId then
gRetryTimerId = nil
PollAirGradient()
PollConfig()
end
end
local function RestartPolling()
if gPollTimerId then
gPollTimerId = C4:KillTimer(gPollTimerId)
end
local interval = tonumber(Properties["Polling Interval (seconds)"]) or DEFAULT_POLL_SECONDS
if interval < 3 then interval = 3 end
gPollTimerId = C4:AddTimer(interval, "SECONDS", true) -- repeating timer
-- Kick off an immediate poll too, don't wait for the first interval
PollAirGradient()
end
-- ============================================================
-- DRIVER LIFECYCLE
-- ============================================================
function OnDriverInit()
DebugLog("OnDriverInit")
end
local function SendInitialCapabilities()
-- This driver's capabilities are fixed (sensor-only, no heat/cool/setpoints),
-- unlike the ESPHome reference driver which discovers them dynamically per
-- device - but the same notification pattern is sent once here in case the
-- thermostatV2 proxy expects an active runtime push in addition to the
-- static driver.xml <capabilities> block.
pcall(function()
C4:SendToProxy(PROXY_BINDING, "ALLOWED_HVAC_MODES_CHANGED", {MODES = "Off"}, "NOTIFY")
C4:SendToProxy(PROXY_BINDING, "DYNAMIC_CAPABILITIES_CHANGED", {HAS_HUMIDITY = true, HAS_EXTRAS = true}, "NOTIFY")
end)
end
function OnDriverLateInit()
DebugLog("OnDriverLateInit")
ConsecutiveFailures = 0
SensorOnline = nil
SendInitialCapabilities()
RestartPolling()
PollConfig()
end
function OnDriverDestroyed()
if gPollTimerId then gPollTimerId = C4:KillTimer(gPollTimerId) end
if gRetryTimerId then gRetryTimerId = C4:KillTimer(gRetryTimerId) end
end
-- ============================================================
-- PROPERTY CHANGES (Composer Pro "Properties" tab)
-- ============================================================
function OnPropertyChanged(strProperty)
DebugLog("Property changed: " .. tostring(strProperty))
if strProperty == "Host or IP Address" or strProperty == "Polling Interval (seconds)" then
RestartPolling()
end
end
-- ============================================================
-- LUA_ACTIONS (Programming "Actions" / Composer Pro commands)
-- ============================================================
function ExecuteCommand(strCommand, tParams)
DebugLog("ExecuteCommand: " .. tostring(strCommand))
if strCommand == "REFRESH_NOW" then
PollAirGradient()
elseif strCommand == "CALIBRATE_CO2" then
PutConfig({co2CalibrationRequested = true})
elseif strCommand == "TEST_LED_BAR" then
PutConfig({ledBarTestRequested = true})
elseif strCommand == "SET_LED_BAR_MODE" then
-- tParams.MODE expected: "co2" | "pm" | "iaqs" | "off"
local mode = tParams and tParams.MODE
if mode then PutConfig({ledBarMode = mode}) end
elseif strCommand == "SET_DISPLAY_BRIGHTNESS" then
-- tParams.LEVEL expected: 0-100
local level = tonumber(tParams and tParams.LEVEL)
if level then PutConfig({displayBrightness = level}) end
elseif strCommand == "SET_LED_BAR_BRIGHTNESS" then
local level = tonumber(tParams and tParams.LEVEL)
if level then PutConfig({ledBarBrightness = level}) end
elseif strCommand == "SET_TEMPERATURE_UNIT" then
-- tParams.UNIT expected: "c" | "f"
local unit = tParams and tParams.UNIT
if unit then PutConfig({temperatureUnit = unit}) end
else
DebugLog("Unhandled command: " .. tostring(strCommand))
end
end
-- Some DriverWorks versions dispatch declared <command> entries through a
-- global LUA_ACTION table (function name = command name) rather than through
-- ExecuteCommand. Both are wired to the same logic so either convention works.
LUA_ACTION = LUA_ACTION or {}
LUA_ACTION["REFRESH_NOW"] = function(tParams) ExecuteCommand("REFRESH_NOW", tParams) end
LUA_ACTION["CALIBRATE_CO2"] = function(tParams) ExecuteCommand("CALIBRATE_CO2", tParams) end
LUA_ACTION["TEST_LED_BAR"] = function(tParams) ExecuteCommand("TEST_LED_BAR", tParams) end
LUA_ACTION["SET_LED_BAR_MODE"] = function(tParams) ExecuteCommand("SET_LED_BAR_MODE", tParams) end
LUA_ACTION["SET_DISPLAY_BRIGHTNESS"] = function(tParams) ExecuteCommand("SET_DISPLAY_BRIGHTNESS", tParams) end
LUA_ACTION["SET_LED_BAR_BRIGHTNESS"] = function(tParams) ExecuteCommand("SET_LED_BAR_BRIGHTNESS", tParams) end
LUA_ACTION["SET_TEMPERATURE_UNIT"] = function(tParams) ExecuteCommand("SET_TEMPERATURE_UNIT", tParams) end
-- ============================================================
-- PROXY COMMAND PASSTHROUGH (e.g. if UI sends thermostat commands
-- back to the driver - this is a sensor-only monitor so these are
-- accepted but no-ops other than logging).
-- ============================================================
function ReceivedFromProxy(idBinding, strCommand, tParams)
DebugLog("ReceivedFromProxy binding=" .. tostring(idBinding) .. " cmd=" .. tostring(strCommand))
-- Sensor-only: no HVAC equipment to actually control, so nothing to forward.
end