{
 "apiVersion": "1.3",
 "files": [
  {
   "content": "-- ==== src/version.lua ====\n-- Copyright (C) 2026 ArtiLED B.V. All Rights Reserved.\n-- ArtiCONTROL for Fibaro Home Center 3: start ArtiCONTROL activities, favourites and rooms from Fibaro.\n-- Proprietary software of ArtiLED B.V.; ArtiLED resellers may adapt it for their own installations.\n-- Not for redistribution.\n\nQA_VERSION = '0.1.2'\n\n-- tools/pack.py --dry-run turns this on: every command is logged and nothing is sent to the Control.\nDRY_RUN = false\n\n-- The marker other software tests for (the Control's Quick App page, and the ArtiLED Hub's Fibaro\n-- light picker, which must never offer these devices). Set on the parent and on every child as\n-- properties.manufacturer and properties.model. Never change these strings.\nARTICONTROL_MANUFACTURER = 'ArtiLED B.V.'\nARTICONTROL_MODEL = 'ArtiCONTROL Quick App'\n\n-- tools/pack.py --name-prefix: prepended to the names of new children (dev fixtures only).\nNAME_PREFIX = ''\n\n-- ==== src/units.lua ====\n-- Copyright (C) 2026 ArtiLED B.V. All Rights Reserved.\n--\n-- PURE: the Control's units, the way the webapp, the UC remote and the ArtiCONTROL Homey app see them.\n-- A port of the Homey app's lib/units.js (itself a port of the Control's app/includes/units.php,\n-- app_unit_record and app_units_from_lists). Keep them in step: they must agree on what a room is and\n-- whether it is on. No HC3 calls here; tests/test_units.lua runs it on plain tables.\n--\n-- A UNIT is every zone, plus every room WITHOUT zones. Hidden ones (disabled = 1) are left out.\n-- A zone whose room is gone is still a unit. A room and a zone with the same number are different units:\n-- the kind is always part of the key.\n--\n-- !! STATE COMES ONLY FROM /rooms AND /zones (plan rev 2 section 4). /activities is inventory: names,\n-- ids, rename and removal - never running state.\n\nArtiUnits = {}\n\nlocal function int(v)\n  local n = tonumber(v)\n  if not n then return 0 end\n  return n >= 0 and math.floor(n) or math.ceil(n)\nend\nArtiUnits.int = int\n\nlocal function str(v)\n  if v == nil or v == json.null then return '' end\n  return tostring(v)\nend\n\n-- One unit record from a /rooms or /zones row (app_unit_record).\n-- !! The Off activity IS an activity: running it makes it the unit's active activity, and that means\n-- OFF, not on. A start in progress shows the STARTING activity, and the unit is on unless the Off\n-- activity is the one starting. Zero active = Off.\nfunction ArtiUnits.record(kind, row, caption)\n  local active = int(row.active_activity)\n  local off = int(row.off_activity)\n  local on = active > 0 and active ~= off\n  local activityName = str(row.activity_name)\n  local starting = int(row.starting_activity)\n  if starting > 0 then\n    on = starting ~= off\n    active = starting\n    activityName = str(row.starting_name)\n  end\n  local status\n  if on and activityName ~= '' then\n    status = activityName .. (starting > 0 and ' - Starting...' or '')\n  else\n    status = starting > 0 and 'Off - Starting...' or 'Off'\n  end\n  return {\n    kind = kind,\n    id = int(row.id),\n    name = str(row.name),\n    caption = str(caption),\n    on = on,\n    status = status,\n    activity = on and active or 0,\n    -- The activity that runs or starts, Off included (the Activity switch compares against it).\n    current = active,\n    activity_name = on and activityName or '',\n    starting = starting > 0 and starting or 0,\n    on_activity = int(row.on_activity),\n    off_activity = off,\n  }\nend\n\n-- The units of one Control, in Control order (app_units_from_lists).\nfunction ArtiUnits.fromLists(rooms, zones)\n  local byRoom = {}\n  for _, z in ipairs(zones or {}) do\n    local rid = int(z.room_id)\n    byRoom[rid] = byRoom[rid] or {}\n    table.insert(byRoom[rid], z)\n  end\n  local units, placed = {}, {}\n  for _, r in ipairs(rooms or {}) do\n    local mine = byRoom[int(r.id)] or {}\n    if #mine > 0 then\n      for _, z in ipairs(mine) do\n        placed[int(z.id)] = true\n        if int(z.disabled) == 0 then units[#units + 1] = ArtiUnits.record('zone', z, r.name) end\n      end\n    elseif int(r.disabled) == 0 then\n      units[#units + 1] = ArtiUnits.record('room', r)\n    end\n  end\n  -- A zone whose room is gone (or 0) is still a unit: it must not vanish.\n  for _, z in ipairs(zones or {}) do\n    if not placed[int(z.id)] and int(z.disabled) == 0 then units[#units + 1] = ArtiUnits.record('zone', z, '') end\n  end\n  return units\nend\n\n-- Where a bound unit stands in a fresh read of the lists:\n--   'ok', record   it is a unit\n--   'hidden'       it exists but is hidden on the Control\n--   'gone'         deleted, or (a room) it now has zones\nfunction ArtiUnits.lookup(rooms, zones, kind, id)\n  local wanted = int(id)\n  if kind == 'zone' then\n    for _, z in ipairs(zones or {}) do\n      if int(z.id) == wanted then\n        if int(z.disabled) ~= 0 then return 'hidden' end\n        local caption = ''\n        for _, r in ipairs(rooms or {}) do\n          if int(r.id) == int(z.room_id) then caption = r.name end\n        end\n        return 'ok', ArtiUnits.record('zone', z, caption)\n      end\n    end\n    return 'gone'\n  end\n  for _, r in ipairs(rooms or {}) do\n    if int(r.id) == wanted then\n      for _, z in ipairs(zones or {}) do\n        if int(z.room_id) == wanted then return 'gone' end\n      end\n      if int(r.has_zones) == 1 then return 'gone' end\n      if int(r.disabled) ~= 0 then return 'hidden' end\n      return 'ok', ArtiUnits.record('room', r)\n    end\n  end\n  return 'gone'\nend\n\n-- The API argument for a unit: {zone = id} or {room = id}.\nfunction ArtiUnits.arg(kind, id)\n  if kind == 'zone' then return { zone = int(id) } end\n  return { room = int(id) }\nend\n\n-- 'zone:3' / 'room:5'\nfunction ArtiUnits.key(kind, id)\n  return tostring(kind) .. ':' .. tostring(int(id))\nend\n\n-- What a unit can START: its enabled activities, its Off activity included (Michel 2026-10-25). A room\n-- unit drops rows that belong to a zone (/activities {room} can carry them).\nfunction ArtiUnits.sources(kind, activities)\n  local out = {}\n  for _, a in ipairs(activities or {}) do\n    if int(a.id) > 0 and not (kind == 'room' and int(a.zone_id) > 0) then out[#out + 1] = a end\n  end\n  return out\nend\n\n-- A room or zone with nothing but its Off activity has nothing On can start: never offered.\nfunction ArtiUnits.usable(unit, activities)\n  for _, a in ipairs(ArtiUnits.sources(unit.kind, activities)) do\n    if int(a.id) ~= int(unit.off_activity) then return true end\n  end\n  return false\nend\n\n-- Default names (Michel Q3): a zone takes its own name when unique on this Control, otherwise\n-- \"<Room> <Zone>\"; a room unit takes the room's name. Returns key -> name.\nfunction ArtiUnits.defaultNames(units)\n  local count = {}\n  local function low(s) return (tostring(s or ''):gsub('^%s+', ''):gsub('%s+$', '')):lower() end\n  for _, u in ipairs(units) do count[low(u.name)] = (count[low(u.name)] or 0) + 1 end\n  local names = {}\n  for _, u in ipairs(units) do\n    local clash = (count[low(u.name)] or 0) > 1\n    local name = u.name\n    if u.kind == 'zone' and clash and u.caption ~= '' then name = u.caption .. ' ' .. u.name end\n    if name == '' then name = u.kind .. ' ' .. tostring(u.id) end\n    names[ArtiUnits.key(u.kind, u.id)] = name\n  end\n  return names\nend\n\n-- A Control's identity is its /alive ident, never its address. It only counts when it is QUALIFIED:\n-- non-empty and not all zeros. A box that cannot say who it is is not signed in to.\nfunction ArtiUnits.qualifiedIdent(v)\n  if type(v) ~= 'string' and type(v) ~= 'number' then return '' end\n  local s = (tostring(v):gsub('^%s+', ''):gsub('%s+$', ''))\n  if s == '' or s:match('^[0:%.%-%s]*$') then return '' end\n  return s\nend\n\n-- ==== src/rules.lua ====\n-- Copyright (C) 2026 ArtiLED B.V. All Rights Reserved.\n--\n-- PURE: what a child IS (its binding), which request an HC3 action becomes, and what a reply means.\n-- No HC3 calls here; tests/test_rules.lua runs it on plain tables.\n--\n-- !! ON AND OFF START ACTIVITIES. A Room child's On = the unit's On activity, Off = its Off activity,\n-- exactly the webapp's room switch. NEVER /activity stop: the Off activity is what switches a room off.\n--\n-- Child kinds and their binding (plan rev 2 section 5, Mycroft 8638 HCF-D2 / 8643):\n--   room       ident, unitKind ('room' | 'zone'), unitId\n--   activity   ident, unitKind, unitId, activityId                      (a pulse button)\n--   switch     ident, unitKind, unitId, onId, offId                     (stateful)\n--   favourite  ident, unitKind, unitId, activityId, play, match, title  (a pulse button)\n-- A binding is written once at creation and NEVER retargeted to another item.\n\nArtiRules = {}\n\nlocal int = ArtiUnits.int\n\nArtiRules.KINDS = { room = true, activity = true, switch = true, favourite = true }\n\n-- Play states inside a valid success reply that mean the favourite did not play (DOC #107). Any other\n-- state (sent, attached, accepted, unconfirmed, skipped) passes: a start is not proof of playback.\nArtiRules.PLAY_FAILED = { failed = true, unresolved = true, discarded = true }\n\nlocal function s(v)\n  if v == nil or v == json.null then return '' end\n  return tostring(v)\nend\n\n-- The identity a favourite is matched by, from the play object /activity_favorites handed out:\n--   movie   kind + title_id (+ copy)\n--   HEOS    source + key (the SLOT) AND title together: another favourite in the same slot is not this one\n--   music   kind + source + key\n-- nil when the play carries none of these: such an item is not offered (no common id is invented).\nfunction ArtiRules.matchIdentity(play)\n  if type(play) ~= 'table' then return nil end\n  if s(play.kind) == 'movie' then\n    if s(play.title_id) == '' then return nil end\n    return { kind = 'movie', title_id = s(play.title_id), copy = s(play.copy) }\n  end\n  if s(play.source) == '' or s(play.key) == '' then return nil end\n  local m = { kind = s(play.kind) ~= '' and s(play.kind) or 'music', source = s(play.source), key = s(play.key) }\n  if m.source == 'heos_favorite' then m.title = s(play.title) end\n  return m\nend\n\nfunction ArtiRules.matchKey(m)\n  if type(m) ~= 'table' then return '' end\n  if m.kind == 'movie' then return 'movie|' .. s(m.title_id) .. '|' .. s(m.copy) end\n  return s(m.kind) .. '|' .. s(m.source) .. '|' .. s(m.key) .. (m.source == 'heos_favorite' and ('|' .. s(m.title)) or '')\nend\n\n-- Is the bound favourite in a SUCCESSFULLY read list? (A failed read never reaches here: unknown.)\nfunction ArtiRules.favouriteIn(spec, items)\n  local want = ArtiRules.matchKey(spec.match)\n  if want == '' then return false end\n  for _, it in ipairs(type(items) == 'table' and items or {}) do\n    if type(it) == 'table' and ArtiRules.matchKey(ArtiRules.matchIdentity(it.play)) == want then return true end\n  end\n  return false\nend\n\nlocal function unitOk(b)\n  return (b.unitKind == 'room' or b.unitKind == 'zone') and int(b.unitId) > 0\nend\n\nfunction ArtiRules.validSpec(b)\n  if type(b) ~= 'table' or not ArtiRules.KINDS[b.kind] then return false end\n  if ArtiUnits.qualifiedIdent(b.ident) == '' or not unitOk(b) then return false end\n  if b.kind == 'room' then return true end\n  if b.kind == 'activity' then return int(b.activityId) > 0 end\n  if b.kind == 'switch' then return int(b.onId) > 0 and int(b.offId) > 0 end\n  if b.kind == 'favourite' then\n    return int(b.activityId) > 0 and type(b.play) == 'table' and ArtiRules.matchKey(b.match) ~= ''\n      and ArtiRules.matchKey(ArtiRules.matchIdentity(b.play)) == ArtiRules.matchKey(b.match)\n  end\n  return false\nend\n\n-- One child per key: the duplicate rule of plan section 5.\nfunction ArtiRules.key(b)\n  local base = b.ident .. '|' .. b.kind .. '|' .. ArtiUnits.key(b.unitKind, b.unitId)\n  if b.kind == 'activity' then return base .. '|' .. int(b.activityId) end\n  if b.kind == 'switch' then return base .. '|' .. int(b.onId) .. '|' .. int(b.offId) end\n  if b.kind == 'favourite' then return base .. '|' .. int(b.activityId) .. '|' .. ArtiRules.matchKey(b.match) end\n  return base\nend\n\nlocal function start(id)\n  return { endpoint = 'activity', data = { action = 'start', activity = int(id) } }\nend\nArtiRules.start = start\n\n-- The request for an HC3 action on a child, decided with the unit's current record (nil when unknown).\n-- Returns req | nil, why, kind where kind = 'ignore' (nothing to do, not an error) or 'refuse'.\nfunction ArtiRules.command(spec, action, record, shownOn)\n  if spec.kind == 'room' then\n    if action == 'toggle' then\n      if not record then return nil, 'State not known yet: nothing sent', 'refuse' end\n      action = record.on and 'turnOff' or 'turnOn'\n    end\n    if action ~= 'turnOn' and action ~= 'turnOff' then return nil, 'Not supported', 'refuse' end\n    if not record then return nil, 'Room not known on the ArtiCONTROL yet: nothing sent', 'refuse' end\n    local on = action == 'turnOn'\n    local id = on and record.on_activity or record.off_activity\n    if int(id) <= 0 then\n      return nil, (on and 'No On activity for ' or 'No Off activity for ') .. record.name .. ': nothing sent', 'refuse'\n    end\n    return start(id)\n  end\n  if spec.kind == 'activity' or spec.kind == 'favourite' then\n    -- A pulse: every turnOn is sent (repeats and the Off activity included), turnOff does nothing.\n    if action == 'turnOff' then return nil, '', 'ignore' end\n    if action ~= 'turnOn' and action ~= 'toggle' then return nil, 'Not supported', 'refuse' end\n    if spec.kind == 'activity' then return start(spec.activityId) end\n    -- The play object exactly as /activity_favorites gave it: never rebuilt from labels.\n    return { endpoint = 'activity', data = { action = 'start', activity = int(spec.activityId), play = spec.play } }\n  end\n  if spec.kind == 'switch' then\n    if action == 'toggle' then action = shownOn and 'turnOff' or 'turnOn' end\n    if action == 'turnOn' then return start(spec.onId) end\n    if action == 'turnOff' then return start(spec.offId) end\n    return nil, 'Not supported', 'refuse'\n  end\n  return nil, 'Not linked', 'refuse'\nend\n\n-- What a successful /activity reply means for the request that was sent (Mycroft 8645 HCF-S4): nil =\n-- accepted, else the text to show. The documented acceptance shapes (Control api/activity.php):\n--   start by id            {activity = <that id>, action = 'start', ...}\n--   start by name (House)  {name, activities = [...], started, action = 'start'}\n--   start with a play      {activity, action = 'start', play = {state = <word>, ...}}\n-- A play state failed / unresolved / discarded is a failure; sent / attached / accepted / unconfirmed\n-- (and any other word the Control documents later) is accepted - a start is not proof of playback. A reply\n-- that does not have the shape of the request's acceptance is UNKNOWN, never promoted to accepted.\nfunction ArtiRules.acceptance(req, data)\n  local unknown = 'Unknown - the ArtiCONTROL\\'s answer could not be read (it may have started)'\n  if type(data) ~= 'table' or type(req) ~= 'table' or type(req.data) ~= 'table' then return unknown end\n  if s(data.action) ~= 'start' then return unknown end\n  if req.data.name ~= nil then\n    if type(data.activities) ~= 'table' then return unknown end\n    return nil\n  end\n  if tonumber(data.activity) == nil or int(data.activity) ~= int(req.data.activity) then return unknown end\n  if req.data.play ~= nil then\n    local play = data.play\n    if type(play) ~= 'table' or type(play.state) ~= 'string' or play.state == '' then\n      return 'Unknown - the ArtiCONTROL did not say whether the favourite plays'\n    end\n    if ArtiRules.PLAY_FAILED[play.state] then return 'The favourite did not play (' .. play.state .. ')' end\n  end\n  return nil\nend\n\n-- Kept for callers that only have the data: the play-state part of acceptance.\nfunction ArtiRules.playFailure(data)\n  local play = type(data) == 'table' and data.play or nil\n  local st = type(play) == 'table' and s(play.state) or ''\n  if ArtiRules.PLAY_FAILED[st] then return 'The favourite did not play (' .. st .. ')' end\n  return nil\nend\n\n-- startActivity(id or name): an explicit whole-number id goes as `activity`, anything else as `name`\n-- (Control api/activity.php: data.name = a House start resolved on the Control; data.activity is cast to\n-- an integer, so a name sent there would start activity 0) - HCF-S2. nil for an empty argument.\nfunction ArtiRules.startByIdOrName(v)\n  if type(v) == 'number' and v == math.floor(v) and v > 0 then return start(v) end\n  local t = tostring(v == nil and '' or v):gsub('^%s+', ''):gsub('%s+$', '')\n  if t == '' then return nil end\n  if t:match('^%d+$') and tonumber(t) > 0 then return start(tonumber(t)) end\n  return { endpoint = 'activity', data = { action = 'start', name = t } }\nend\n\n-- The Activity switch's real state: on while its On activity runs or starts, off when anything else runs\n-- or starts, or the unit is off.\nfunction ArtiRules.switchOn(spec, record)\n  return int(record.current) > 0 and int(record.current) == int(spec.onId)\nend\n\n-- A favourite's display name (title, then the API's subtitle when there is one).\nfunction ArtiRules.favouriteLabel(it)\n  local t = s(it.title)\n  local sub = s(it.subtitle)\n  local typ = s(it.type)\n  local extra = (typ ~= '' and typ or '') .. ((typ ~= '' and sub ~= '') and ', ' or '') .. sub\n  return t .. (extra ~= '' and (' (' .. extra .. ')') or '')\nend\n\n-- ==== src/control.lua ====\n-- Copyright (C) 2026 ArtiLED B.V. All Rights Reserved.\n--\n-- The ArtiCONTROL API as the Homey app and the UC remote speak it: HTTP POST to\n-- http://<control>/api/<endpoint>, form-encoded, with `token` and `data` (JSON). A reply is\n-- {success: 1, data: {...}}; error 2 means the token was refused. /alive is unauthenticated.\n--\n-- !! THE QUEUE CONTRACT - the ArtiLED Hub Quick App's (ArtiLED_Hub_Fibaro src/hub.lua), carried over:\n--   - ONE request in flight; the Control is never stacked with requests.\n--   - Two FIFO lanes. When the wire is free the oldest COMMAND goes first, then the oldest READ.\n--     Commands keep their order among themselves and only overtake reads that are WAITING.\n--   - No retry, no replay. A failure is reported to the caller and forgotten.\n--   - At most MAX_COMMANDS waiting commands; one more is refused at once, never dropped silently.\n--   - Every item carries the connection GENERATION it was queued under (and its child id). A transport\n--     failure, a refused token, a different ident or a re-connect bumps the generation: every WAITING\n--     item is dropped and its caller told \"not sent\". A reply that comes back under an older generation,\n--     or for a removed child, is NOT PUBLISHED: its caller still gets ONE terminal callback, code\n--     'retired' with no data, so whoever waits for it (a poll, a batch) can finish - but nothing from it\n--     may be written anywhere (Mycroft 8645 HCF-S1: completion is not publication).\n--   - A success reply without a data object is MALFORMED (code 'malformed'), never an empty success:\n--     the caller decides what an unreadable result means (HCF-S4).\n--   - A COMMAND that was ON THE WIRE and lost its reply is reported \"unknown - may have been sent\",\n--     never \"not sent\": a request already written cannot be taken back.\n--   - SET GATE: no command is admitted until the parent has verified the Control's identity in this\n--     generation (verify()). Before that a command is refused at once, never parked for later.\n--   - Every command is DECIDED AT DISPATCH (build()), after the commands before it completed: the child's\n--     binding and the unit's record are checked again then. Nothing to send -> reported, never sent.\n--   - DRY_RUN (src/version.lua) is checked at the WIRE, right before the HTTP request, for every endpoint\n--     that changes something on the Control. No route around it exists.\n\nArtiControl = {}\nArtiControl.__index = ArtiControl\n\nArtiControl.TIMEOUT_MS = 20000\nArtiControl.MAX_COMMANDS = 20\n\n-- Endpoints that change something on the Control.\nArtiControl.SET_ENDPOINTS = { activity = true, button = true, command = true }\n\nlocal function urlencode(s)\n  return (tostring(s):gsub('[^%w%-%._~]', function(c)\n    return string.format('%%%02X', string.byte(c))\n  end))\nend\nArtiControl.urlencode = urlencode\n\n-- JSON for the `data` field. An empty Lua table must go as {} (an object), never [].\nlocal function encodeData(d)\n  if type(d) ~= 'table' or next(d) == nil then return '{}' end\n  return json.encode(d)\nend\nArtiControl.encodeData = encodeData\n\nlocal function body(token, data)\n  return 'token=' .. urlencode(token) .. '&data=' .. urlencode(encodeData(data))\nend\n\nlocal function trim(s)\n  return (tostring(s or ''):gsub('^%s+', ''):gsub('%s+$', ''))\nend\n\n-- log(text): where the client reports dry-run requests, drops and late replies.\nfunction ArtiControl.new(ip, token, log)\n  local self = setmetatable({}, ArtiControl)\n  self.ip = trim(ip)\n  self.token = token or ''\n  self.log = log or function() end\n  self.commands = {}\n  self.reads = {}\n  self.inflight = nil\n  self.gen = 1\n  self.verified = false\n  self.removed = {}\n  self.http = net.HTTPClient()\n  return self\nend\n\nfunction ArtiControl:url(endpoint)\n  return 'http://' .. self.ip .. '/api/' .. endpoint\nend\n\nlocal function safecall(self, cb, ...)\n  local ok, err = pcall(cb, ...)\n  if not ok then self.log('ArtiCONTROL: callback error: ' .. tostring(err)) end\nend\n\n-- The connection was lost or changed: drop every WAITING item, close the SET gate.\nfunction ArtiControl:bump(reason)\n  self.gen = self.gen + 1\n  self.verified = false\n  local waiting = {}\n  for _, j in ipairs(self.commands) do waiting[#waiting + 1] = j end\n  for _, j in ipairs(self.reads) do waiting[#waiting + 1] = j end\n  self.commands, self.reads = {}, {}\n  for _, j in ipairs(waiting) do\n    if j.command then self.log('ArtiCONTROL: not sent (' .. reason .. '): ' .. j.label) end\n    safecall(self, j.cb, false, 'not sent: ' .. reason, 'dropped')\n  end\nend\n\n-- Point the client at another address (a re-connect or a verified move). A new generation: nothing that\n-- was waiting for the old address is sent to the new one.\nfunction ArtiControl:moveTo(ip, reason)\n  self:bump(reason or 'the ArtiCONTROL address changed')\n  self.ip = trim(ip)\nend\n\n-- The parent verified the Control's ident in THIS generation: commands may be admitted.\nfunction ArtiControl:verify(gen)\n  if gen ~= nil and gen ~= self.gen then return false end\n  self.verified = true\n  return true\nend\n\n-- A child was removed: its waiting commands are dropped; a reply already on its way is ignored.\nfunction ArtiControl:dropChild(childId)\n  self.removed[childId] = true\n  local keep = {}\n  for _, j in ipairs(self.commands) do\n    if j.child == childId then\n      self.log('ArtiCONTROL: not sent (device removed): ' .. j.label)\n      safecall(self, j.cb, false, 'not sent: device removed', 'dropped')\n    else\n      keep[#keep + 1] = j\n    end\n  end\n  self.commands = keep\nend\n\nfunction ArtiControl:_finish(job, ok, data, code)\n  self.inflight = nil\n  if job.gen ~= self.gen or (job.child ~= nil and self.removed[job.child]) then\n    self.log('ArtiCONTROL: late reply not published for /api/' .. tostring(job.endpoint))\n    safecall(self, job.cb, false, job.command and 'unknown - superseded after it was sent' or 'superseded',\n      'retired', job.seq, job.req, job.gen)\n  else\n    -- A command that was written and then lost its reply: the Control may have acted on it.\n    if not ok and job.command and (code == 'unreachable' or code == 'http') then\n      data, code = 'unknown - may have been sent (' .. tostring(data) .. ')', 'unknown'\n    end\n    safecall(self, job.cb, ok, data, code, job.seq, job.req, job.gen)\n    if not ok and (code == 'unreachable' or code == 'http' or code == 'unknown' or code == 'auth') and job.gen == self.gen then\n      self:bump(code == 'auth' and 'ArtiCONTROL login no longer valid' or 'ArtiCONTROL not reachable')\n    end\n  end\n  self:_dispatch()\nend\n\nfunction ArtiControl:_dispatch()\n  if self.inflight then return end\n  local job = table.remove(self.commands, 1) or table.remove(self.reads, 1)\n  if not job then return end\n\n  if job.build then\n    local req, why, kind = job.build()\n    if not req then\n      safecall(self, job.cb, false, why or 'not sent', kind or 'skipped', nil, nil, job.gen)\n      return self:_dispatch()\n    end\n    job.req, job.endpoint, job.data = req, req.endpoint, req.data\n    job.body = body(self.token, req.data)\n  end\n\n  -- !! THE DRY-RUN BOUNDARY. Nothing that changes the Control passes this line under DRY_RUN.\n  if DRY_RUN and ArtiControl.SET_ENDPOINTS[job.endpoint] then\n    self.log('ArtiCONTROL DRY-RUN, not sent: /api/' .. job.endpoint .. ' ' .. encodeData(job.data))\n    safecall(self, job.cb, false, 'dry-run: nothing was sent', 'dry-run', nil, job.req, job.gen)\n    return self:_dispatch()\n  end\n\n  self.inflight = job\n  self.seq = (self.seq or 0) + 1\n  job.seq = self.seq\n  local finished = false\n  local function done(ok, data, code)\n    if finished then return end\n    finished = true\n    self:_finish(job, ok, data, code)\n  end\n  self.http:request(self:url(job.endpoint), {\n    options = {\n      method = job.method,\n      headers = { ['Content-Type'] = 'application/x-www-form-urlencoded', ['Accept'] = 'application/json' },\n      data = job.body,\n      timeout = ArtiControl.TIMEOUT_MS,\n    },\n    success = function(resp)\n      if not resp or tonumber(resp.status) ~= 200 then\n        return done(false, 'HTTP ' .. tostring(resp and resp.status), 'http')\n      end\n      local okj, parsed = pcall(json.decode, resp.data or '')\n      if not okj or type(parsed) ~= 'table' then\n        return done(false, 'not an ArtiCONTROL reply', 'http')\n      end\n      if tonumber(parsed.success) ~= 1 then\n        local code = tonumber(parsed.error) or 0\n        return done(false, tostring(parsed.error_text or 'ArtiCONTROL error'),\n          (code == 2 and job.endpoint ~= 'login') and 'auth' or ('error' .. tostring(code)), parsed.data)\n      end\n      if type(parsed.data) ~= 'table' then\n        return done(false, 'the ArtiCONTROL\\'s reply had no readable result', 'malformed')\n      end\n      return done(true, parsed.data)\n    end,\n    error = function(err)\n      return done(false, 'not reachable: ' .. tostring(err), 'unreachable')\n    end,\n  })\nend\n\n-- A read. cb(ok, dataOrError, code, seq, req, gen)\nfunction ArtiControl:read(endpoint, data, cb)\n  self.reads[#self.reads + 1] = { endpoint = endpoint, data = data, method = 'POST',\n    body = body(self.token, data), cb = cb or function() end, gen = self.gen }\n  self:_dispatch()\nend\n\n-- A command for one child (or nil for a parent action), decided at dispatch: build() -> req or\n-- nil, why, kind. cb(ok, dataOrError, code, seq, req, gen). Refused at once when the SET gate is closed\n-- or the command lane is full.\nfunction ArtiControl:command(childId, label, build, cb)\n  cb = cb or function() end\n  if not self.verified then\n    self.log('ArtiCONTROL: not sent (ArtiCONTROL not verified yet): ' .. label)\n    return cb(false, 'not sent: ArtiCONTROL not verified yet', 'refused')\n  end\n  if #self.commands >= ArtiControl.MAX_COMMANDS then\n    self.log('ArtiCONTROL: not sent (too many commands waiting): ' .. label)\n    return cb(false, 'not sent: too many commands waiting', 'refused')\n  end\n  self.commands[#self.commands + 1] = { label = label, build = build, method = 'POST', command = true,\n    cb = cb, gen = self.gen, child = childId, endpoint = label }\n  self:_dispatch()\nend\n\n-- Unauthenticated: {name, ident}. A read, at the head of the read lane.\nfunction ArtiControl:alive(cb)\n  table.insert(self.reads, 1, { endpoint = 'alive', method = 'GET', cb = cb, gen = self.gen })\n  self:_dispatch()\nend\n\n-- Username + password -> the Control's stable token. No token is sent; the password is never stored.\nfunction ArtiControl:login(user, pass, cb)\n  local b = 'data=' .. urlencode(json.encode({ username = user, password = pass }))\n  table.insert(self.reads, 1, { endpoint = 'login', method = 'POST', body = b, gen = self.gen,\n    cb = function(ok, data, code)\n      if ok and type(data.token) == 'string' and data.token ~= '' then return cb(true, data.token) end\n      if ok then return cb(false, 'the ArtiCONTROL accepted the login but returned no token', 'error') end\n      return cb(false, data, code)\n    end })\n  self:_dispatch()\nend\n\n-- ==== src/child.lua ====\n-- Copyright (C) 2026 ArtiLED B.V. All Rights Reserved.\n--\n-- One ArtiCONTROL room, activity, activity switch or favourite as an HC3 device (all\n-- com.fibaro.binarySwitch). The child is deliberately thin: it shows what the parent tells it and hands\n-- every HC3 action to the parent, which owns the connection, the queue and the binding. What the child\n-- IS comes from its binding (spec), kept by the parent - never from its name or its HC3 type.\n--\n--   room       on/off = the unit's real state; the log line says what runs (\"Netflix\", \"Off - Starting...\")\n--   activity   a PULSE: on for 1 s after the Control accepted the start, then off on its own, whatever\n--   favourite  the activity does. Running state is shown on the Room child and the parent, never here.\n--   switch     stateful: on while its On activity runs or starts. For 20 s after a press only a report\n--              that agrees with the press is DISPLAYED - display only, it never holds back a command.\n\nclass 'ArtiChild'(QuickAppChild)\n\nArtiChild.PULSE_MS = 1000\nArtiChild.OPTIMISTIC_S = 20\n\nfunction ArtiChild:__init(device)\n  QuickAppChild.__init(self, device)\n  self.shown = {}\nend\n\n-- Set a property only when it changed: HC3 records every update in the device history.\nfunction ArtiChild:show(name, value)\n  if value == nil then return end\n  if self.shown[name] == value then return end\n  self.shown[name] = value\n  self:updateProperty(name, value)\nend\n\n-- Unavailable: dead + reason. The values stay as they were - an unreachable room is never \"off\".\nfunction ArtiChild:showDead(reason)\n  self:show('dead', true)\n  self:show('deadReason', reason)\n  self:show('log', reason)\nend\n\nfunction ArtiChild:showAlive()\n  self:show('dead', false)\n  self:show('deadReason', '')\nend\n\nfunction ArtiChild:note(text)\n  self:show('log', text)\nend\n\n-- A command that failed stays readable on the log line for a while: the next poll's status line must not\n-- wipe the reason away a second later.\nArtiChild.FAIL_HOLD_S = 30\nfunction ArtiChild:failed(text, now)\n  self.failHoldUntil = now + ArtiChild.FAIL_HOLD_S\n  self:note(text)\nend\n\nfunction ArtiChild:status(text, now)\n  if text == nil or (self.failHoldUntil and now and now < self.failHoldUntil) then return end\n  self.failHoldUntil = nil\n  self:note(text)\nend\n\n-- A Room child: the unit record from ArtiUnits.record.\nfunction ArtiChild:applyRoom(record, now)\n  self:showAlive()\n  self.record = record\n  self:show('value', record.on)\n  self:show('state', record.on)\n  self:status(record.status, now)\nend\n\n-- An Activity switch: on = its On activity runs or starts.\nfunction ArtiChild:applySwitch(on, now, status)\n  self:showAlive()\n  if self.optimisticUntil and now < self.optimisticUntil and on ~= self.cmdState then\n    return                                              -- display reconciliation only\n  end\n  self.optimisticUntil = nil\n  self.shownOn = on\n  self:show('value', on)\n  self:show('state', on)\n  self:status(status, now)\nend\n\n-- An Activity or Favourite button: only availability; the value is the pulse's alone.\nfunction ArtiChild:applyButton(status, now)\n  self:showAlive()\n  if not self.pulsing then\n    self:show('value', false)\n    self:show('state', false)\n  end\n  self:status(status, now)\nend\n\n-- The Control accepted a start from this button: on for a moment, then off again on its own.\nfunction ArtiChild:pulse()\n  self.pulsing = (self.pulsing or 0) + 1\n  local mine = self.pulsing\n  self.shown.value, self.shown.state = nil, nil\n  self:show('value', true)\n  self:show('state', true)\n  setTimeout(function()\n    if self.pulsing ~= mine then return end            -- a newer press runs its own pulse\n    self.pulsing = nil\n    if self.removed then return end\n    self:show('value', false)\n    self:show('state', false)\n  end, ArtiChild.PULSE_MS)\nend\n\n-- An Activity switch press was accepted by the Control.\nfunction ArtiChild:afterSwitch(on, now)\n  self.cmdState = on\n  self.optimisticUntil = now + ArtiChild.OPTIMISTIC_S\n  self.shownOn = on\n  self:show('value', on)\n  self:show('state', on)\nend\n\n-- HC3 actions. Each one goes to the parent, which decides and queues (src/parent.lua).\nfunction ArtiChild:turnOn() self.parent:childAction(self, 'turnOn') end\nfunction ArtiChild:turnOff() self.parent:childAction(self, 'turnOff') end\nfunction ArtiChild:toggle() self.parent:childAction(self, 'toggle') end\n\n-- ==== src/follow.lua ====\n-- Copyright (C) 2026 ArtiLED B.V. All Rights Reserved.\n--\n-- Automatic address follow - ONLY where the Control's announcements reach the HC3 (Michel's owner\n-- decision, 2026-10-25, plan rev 2 section 5): \"Control has an interface in Homey's network but doesn't\n-- announce there by default ... in our network we have a dedicated ArtiLED VLAN\". Where nothing is heard\n-- the installer re-connects: change ControlIP on the parent (same ident = every child stays bound).\n--\n-- The Control announces itself on UDP 50081: fna349fn|ident|type|ip|name. The parent moves only when ALL\n-- of these hold (control-ha-integration.md section 4.3):\n--   - the current connection is UNHEALTHY (a healthy Control never moves),\n--   - the packet's ident is the bound ident,\n--   - /alive at the new address answers that ident AND the saved token works there,\n--   - there is ONE claimant: two new addresses for the ident within 5 minutes = no move,\n--   - nothing newer happened meanwhile (the connection generation is the one the check started under).\n-- The candidate address is the packet's SENDER; the advertised IP is only a fallback (the discovery\n-- service keeps announcing the address it read at its start).\n-- !! Whether a Quick App can listen on UDP at all is unproved on HC3 (test T0b). If it cannot, this\n-- stays off and re-connect is the path everywhere; nothing else depends on it.\n\nArtiFollow = {}\nArtiFollow.PORT = 50081\nArtiFollow.TOKEN = 'fna349fn'\nArtiFollow.CLAIM_WINDOW_S = 300\nArtiFollow.CHECK_EVERY_S = 30\n\nfunction ArtiFollow.parse(data)\n  local tok, ident, typ, ip, name = tostring(data or ''):match('^([^|]*)|([^|]*)|([^|]*)|([^|]*)|?(.*)$')\n  if tok ~= ArtiFollow.TOKEN then return nil end\n  ident = ArtiUnits.qualifiedIdent(ident)\n  if ident == '' then return nil end\n  return { ident = ident, type = typ, ip = ip, name = name }\nend\n\nfunction ArtiFollow.start(qa)\n  if qa.follow then return end\n  qa.follow = { claims = {}, checked = {} }\n  if not net.UDPSocket then\n    qa:debug('ArtiCONTROL: address follow off (no UDP on this HC3): re-connect by changing ControlIP')\n    return\n  end\n  local ok, err = pcall(function()\n    local sock = net.UDPSocket({ broadcast = true, timeout = 0 })\n    sock:bind('0.0.0.0', ArtiFollow.PORT)\n    qa.follow.sock = sock\n    local function listen()\n      sock:receive({\n        success = function(data, fromIp)\n          pcall(ArtiFollow.heard, qa, data, fromIp, os.time())\n          listen()\n        end,\n        error = function()\n          setTimeout(listen, 5000)\n        end,\n      })\n    end\n    listen()\n  end)\n  if not ok then\n    qa.follow.sock = nil\n    qa:debug('ArtiCONTROL: address follow off (' .. tostring(err) .. '): re-connect by changing ControlIP')\n  end\nend\n\n-- One announcement heard. now = seconds.\nfunction ArtiFollow.heard(qa, data, fromIp, now)\n  local a = ArtiFollow.parse(data)\n  if not a or not qa.control then return end\n  local ident = qa:internalStorageGet('controlIdent')\n  if type(ident) ~= 'string' or ident == '' or a.ident ~= ident then return end\n  local candidate = (fromIp and fromIp ~= '') and fromIp or a.ip\n  if candidate == '' or candidate == qa.control.ip then return end\n  local f = qa.follow\n  f.claims[candidate] = now\n  for ip, t in pairs(f.claims) do\n    if now - t > ArtiFollow.CLAIM_WINDOW_S then f.claims[ip] = nil end\n  end\n  if not qa.unhealthy then return end                 -- a healthy Control never moves\n  local n = 0\n  for _ in pairs(f.claims) do n = n + 1 end\n  if n > 1 then\n    qa:status('Two addresses claim this ArtiCONTROL: not following - change ControlIP to re-connect')\n    return\n  end\n  if f.checked[candidate] and now - f.checked[candidate] < ArtiFollow.CHECK_EVERY_S then return end\n  f.checked[candidate] = now\n  local epoch = qa.control.gen\n  local token = qa:internalStorageGet('controlToken') or ''\n  local probe = ArtiControl.new(candidate, token, function(t) qa:debug(t) end)\n  probe:alive(function(ok, d)\n    if not ok or type(d) ~= 'table' or ArtiUnits.qualifiedIdent(d.ident) ~= ident then return end\n    probe:read('version', {}, function(ok2, _, code)\n      if not ok2 then\n        if code == 'auth' then qa:status('The ArtiCONTROL moved to ' .. candidate .. ': sign in again on the parent') end\n        return\n      end\n      -- !! Commit only if nothing newer happened meanwhile (a re-connect, another move, a recovery).\n      local claims = 0\n      for _ in pairs(f.claims) do claims = claims + 1 end\n      if qa.control.gen ~= epoch or not qa.unhealthy or claims > 1 then return end\n      qa:debug('ArtiCONTROL: following the ArtiCONTROL to ' .. candidate)\n      qa:setVariable('ControlIP', candidate)\n      qa:connect()                                     -- a new generation; published only after /alive\n    end)\n  end)\nend\n\n-- ==== src/parent.lua ====\n-- Copyright (C) 2026 ArtiLED B.V. All Rights Reserved.\n--\n-- The parent: one per ArtiCONTROL. It holds the connection, the bindings of its children, the poll loop\n-- and the selection view. Plan: /opt/workflow/artiled/plans/control-fibaro-quick-app.md (rev 2,\n-- Mycroft DESIGN PASS 8643).\n--\n-- !! RULES THAT MUST SURVIVE EVERY CHANGE\n--   - onInit only READS. Starting, restarting or updating the Quick App never starts an activity.\n--   - Children are re-bound with initChildDevices and NEVER deleted or recreated here: their HC3 ids are\n--     what the customer's Fibaro scenes point at.\n--   - A child is bound by Control ident + kind + unit (+ activity / pair / favourite identity) in the\n--     parent's internal storage, written once, never retargeted. A child without a valid binding is shown\n--     dead, never guessed. A different Control at ControlIP is never adopted.\n--   - Unreachable / refused token -> children dead, values untouched, nothing replayed. A FAILED\n--     inventory read is unknown: it never makes a child \"removed\".\n--   - GENERATION OWNERSHIP: every reply is applied only under the connection generation it was asked in.\n--     A reconnect or move bumps the generation, so an older qualification, poll or command reply can never\n--     publish state or connection settings over a newer one.\n\nQuickApp.POLL_S = 5\nQuickApp.INVENTORY_EVERY = 12          -- ticks (60 s): identity, activities, favourites, removed children\nQuickApp.EARLY_POLLS_MS = { 1000, 3000 }\nQuickApp.RETRY_S = 30\n\nQuickApp.CHILD_CLASSES = { ['com.fibaro.binarySwitch'] = ArtiChild }\n\nlocal int = ArtiUnits.int\n\n-- Seconds; a function so host tests can drive the clock.\nQuickApp.clock = os.time\nlocal function now()\n  return QuickApp.clock()\nend\n\nlocal function trim(s)\n  return (tostring(s or ''):gsub('^%s+', ''):gsub('%s+$', ''))\nend\n\n-- ---------------------------------------------------------------------------------------------------\n-- Start\n\nfunction QuickApp:onInit()\n  self:debug('ArtiCONTROL Quick App ' .. QA_VERSION .. (DRY_RUN and ' (DRY-RUN: no command is sent)' or ''))\n  self.tick = 0\n  self.ui = {}\n  self.inv = { activities = {}, favourites = {} }    -- last SUCCESSFUL inventory reads\n  self.records = {}                                   -- unit key -> record, from the last good poll\n\n  self:updateProperty('manufacturer', ARTICONTROL_MANUFACTURER)\n  self:updateProperty('model', ARTICONTROL_MODEL)\n  self.bindings = self:loadBindings()\n  self.unclassified = self:loadUnclassified()\n  self:initChildDevices(QuickApp.CHILD_CLASSES)\n  local live = {}\n  for id, child in pairs(self.childDevices or {}) do\n    live[tostring(id)] = true\n    self:bindChild(child)\n  end\n  local pruned = false\n  for id in pairs(self.bindings) do\n    if not live[id] then self.bindings[id] = nil; pruned = true end\n  end\n  if pruned then self:saveBindings() end\n\n  self:status('Starting...')\n  self:initView()\n  self:connect()\nend\n\nfunction QuickApp:bindChild(child)\n  child.parent = self\n  child:show('manufacturer', ARTICONTROL_MANUFACTURER)\n  child:show('model', ARTICONTROL_MODEL)\n  local b = self.bindings[tostring(child.id)]\n  if b and ArtiRules.validSpec(b) then\n    child.spec = b\n  else\n    child.spec = nil\n    child:showDead('Not linked to an ArtiCONTROL item')\n  end\nend\n\nfunction QuickApp:loadBindings()\n  local raw = self:internalStorageGet('bindings')\n  if type(raw) == 'table' then return raw end\n  if type(raw) == 'string' and raw ~= '' then\n    local ok, t = pcall(json.decode, raw)\n    if ok and type(t) == 'table' then return t end\n  end\n  return {}\nend\n\nfunction QuickApp:saveBindings()\n  self:internalStorageSet('bindings', json.encode(self.bindings))\nend\n\n-- ---------------------------------------------------------------------------------------------------\n-- !! NOT A LIGHT (Mycroft 8645 HCF-S3). The HC3 makes every binarySwitch a Light by default, and then a\n-- Fibaro \"all lights off\" would start Off activities. The role is asked for at creation and, when the HC3\n-- did not take it there, written once more - and only a READ-BACK of deviceRole = 'Other' counts. A child\n-- the HC3 would not mark stays INERT (shown dead, every command refused) and is retried on each inventory\n-- tick; it is never deleted or recreated (scenes may already use it). Once marked, the customer decides.\nQuickApp.INERT = 'Not set up: the HC3 did not mark it as not-a-light - nothing is sent'\nQuickApp.ROLE = { deviceRole = 'Other', categories = { 'other' } }\n\nfunction QuickApp:loadUnclassified()\n  local raw = self:internalStorageGet('unclassified')\n  local ok, t = pcall(json.decode, type(raw) == 'string' and raw or '{}')\n  return (ok and type(t) == 'table') and t or {}\nend\n\nfunction QuickApp:roleIsOther(id)\n  local ok, dev = pcall(api.get, '/devices/' .. tostring(id))\n  return ok and type(dev) == 'table' and type(dev.properties) == 'table' and dev.properties.deviceRole == 'Other'\nend\n\n-- true when the HC3 confirms the child is not a light (it already was, or the write took).\nfunction QuickApp:classify(id)\n  if self:roleIsOther(id) then return true end\n  local ok, _, status = pcall(api.put, '/devices/' .. tostring(id), { properties = QuickApp.ROLE })\n  status = tonumber(status)\n  if not ok or not status or status < 200 or status > 299 then return false end\n  return self:roleIsOther(id)\nend\n\nfunction QuickApp:setUnclassified(id, inert)\n  self.unclassified[tostring(id)] = inert or nil\n  self:internalStorageSet('unclassified', json.encode(self.unclassified))\nend\n\nfunction QuickApp:retryClassification()\n  for id in pairs(self.unclassified) do\n    local child = self.childDevices and self.childDevices[tonumber(id)]\n    if not child then\n      self:setUnclassified(id, false)                   -- removed meanwhile\n    elseif self:classify(id) then\n      self:setUnclassified(id, false)\n      child.badReason = nil\n      self:debug('ArtiCONTROL: device ' .. id .. ' is now marked not-a-light; it works')\n    end\n  end\nend\n\nfunction QuickApp:var(name)\n  return trim(self:getVariable(name))\nend\n\nfunction QuickApp:status(text)\n  self.statusText = text\n  local line = 'ArtiCONTROL ' .. QA_VERSION .. (DRY_RUN and ' DRY-RUN' or '') .. ' - ' .. text\n  pcall(function() self:updateView('lblStatus', 'text', line) end)\n  self:updateProperty('log', text)\nend\n\nfunction QuickApp:eachChild(fn)\n  for id, child in pairs(self.childDevices or {}) do fn(child, id) end\nend\n\n-- Connection loss: every bound child dead with the reason; bindings and values are kept.\nfunction QuickApp:allDead(reason)\n  self.connDead = reason\n  self:eachChild(function(child)\n    if child.spec then child:showDead(reason) end\n  end)\nend\n\nfunction QuickApp:connected()\n  return self.control and self.control.verified and not self.foreign and not self.authFailed\nend\n\n-- ---------------------------------------------------------------------------------------------------\n-- Connect: identity first, then credentials. Nothing is sent to a Control whose ident does not match.\n\nfunction QuickApp:connect()\n  local ip = self:var('ControlIP')\n  if ip == '' then\n    return self:status('Fill in ControlIP, and ControlUser + ControlPassword (or ControlToken), under Variables')\n  end\n  if not self.control then\n    self.control = ArtiControl.new(ip, self:internalStorageGet('controlToken') or '', function(t) self:debug(t) end)\n  elseif self.control.ip ~= ip then\n    self.control:moveTo(ip, 'ControlIP changed')\n  end\n  local gen = self.control.gen\n  self:checkIdentity(gen, function(ok, retired)\n    if retired then return end                         -- a newer connect owns the connection now\n    if not ok then return self:retryLater() end\n    self:credentials(gen)\n  end)\n  if ArtiFollow then ArtiFollow.start(self) end\nend\n\nfunction QuickApp:retryLater()\n  if self.retryPending then return end\n  self.retryPending = true\n  setTimeout(function()\n    self.retryPending = false\n    self:connect()\n  end, QuickApp.RETRY_S * 1000)\nend\n\n-- cb(true) when /alive answers with the stored ident (or, before the first sign-in, a qualified one).\n-- cb(ok, retired): retired = the check belonged to an older generation - finished, but nothing applied.\nfunction QuickApp:checkIdentity(gen, cb)\n  self.control:alive(function(ok, data, code)\n    if code == 'retired' or gen ~= self.control.gen then return cb(false, true) end   -- never applied\n    local ident = ok and type(data) == 'table' and ArtiUnits.qualifiedIdent(data.ident) or ''\n    if ident == '' then\n      self.unhealthy = true\n      self:status('ArtiCONTROL not reachable at ' .. self.control.ip)\n      self:allDead('ArtiCONTROL not reachable')\n      return cb(false)\n    end\n    local stored = self:internalStorageGet('controlIdent')\n    if type(stored) == 'string' and stored ~= '' and stored ~= ident then\n      -- !! Never adopt another Control: the same activity ids would silently retarget every child.\n      self:foreignControl()\n      return cb(false)\n    end\n    self.foreign = false\n    self.seenIdent = ident\n    self.controlName = tostring(data.name or 'ArtiCONTROL')\n    return cb(true)\n  end)\nend\n\nfunction QuickApp:credentials(gen)\n  local token = self:var('ControlToken')\n  local user, pass = self:var('ControlUser'), self:var('ControlPassword')\n  if token ~= '' then return self:tryToken(gen, token, 'ControlToken') end\n  if user ~= '' and pass ~= '' then\n    return self.control:login(user, pass, function(ok, t)\n      if gen ~= self.control.gen then return end\n      if not ok then\n        self:status('The ArtiCONTROL refused this login: check ControlUser and ControlPassword')\n        return self:allDead('ArtiCONTROL login refused')\n      end\n      self:tryToken(gen, t, 'ControlPassword')\n    end)\n  end\n  local stored = self:internalStorageGet('controlToken')\n  if type(stored) == 'string' and stored ~= '' then return self:tryToken(gen, stored, nil) end\n  self:status('Fill in ControlUser + ControlPassword (or ControlToken) under Variables')\nend\n\n-- A token is kept only once it WORKS (/version answers with it), and only by the generation that asked.\nfunction QuickApp:tryToken(gen, token, clearVar)\n  self.control.token = token\n  self.control:read('version', {}, function(ok, data, code)\n    if gen ~= self.control.gen then return end            -- superseded: publish nothing\n    if not ok then\n      if code == 'auth' then\n        self.authFailed = true\n        self:status('ArtiCONTROL login no longer valid: fill in ControlUser and ControlPassword again')\n        return self:allDead('ArtiCONTROL login no longer valid: sign in again on the parent')\n      end\n      self.unhealthy = true\n      self:status('ArtiCONTROL not reachable at ' .. self.control.ip)\n      self:allDead('ArtiCONTROL not reachable')\n      return self:retryLater()\n    end\n    -- Hidden from the REST API (third argument). The password itself is never stored.\n    self:internalStorageSet('controlToken', token, true)\n    if not self:internalStorageGet('controlIdent') then\n      self:internalStorageSet('controlIdent', self.seenIdent, true)\n    end\n    if clearVar then self:setVariable(clearVar, '') end\n    self.authFailed = false\n    self.connDead = nil\n    self.controlVersion = tostring(data.version or '?')\n    self.control:verify(gen)\n    self.unhealthy = false\n    self:status(self.controlName .. ' - ' .. self.controlVersion .. ' - connected')\n    self:startPolling()\n  end)\nend\n\n-- A different Control answers at ControlIP: drop all waiting work, close the SET gate, stop.\nfunction QuickApp:foreignControl()\n  if self.foreign then return end\n  self.foreign = true\n  self.control:bump('a different ArtiCONTROL answers at ' .. self.control.ip)\n  self:status('A different ArtiCONTROL answers at ' .. self.control.ip .. ': nothing is sent to it')\n  self:allDead('This is a different ArtiCONTROL')\nend\n\n-- ---------------------------------------------------------------------------------------------------\n-- Poll\n\nfunction QuickApp:startPolling()\n  if self.polling then return end\n  self.polling = true\n  local function loop()\n    self:pollTick()\n    setTimeout(loop, QuickApp.POLL_S * 1000)\n  end\n  loop()\nend\n\nfunction QuickApp:earlyPolls()\n  for _, ms in ipairs(QuickApp.EARLY_POLLS_MS) do\n    setTimeout(function() self:pollTick(true) end, ms)\n  end\nend\n\n-- What the children need: activity lists per unit, favourite lists per activity.\nfunction QuickApp:needs()\n  local need = { units = {}, favourites = {} }\n  self:eachChild(function(child)\n    local s = child.spec\n    if not s then return end\n    if s.kind ~= 'room' then need.units[ArtiUnits.key(s.unitKind, s.unitId)] = { kind = s.unitKind, id = s.unitId } end\n    if s.kind == 'favourite' then need.favourites[int(s.activityId)] = true end\n  end)\n  return need\nend\n\n-- Children the customer deleted by hand: drop them, their bindings and their waiting commands. Checked\n-- against the BINDINGS, not only childDevices (the SDK takes a deleted child out of childDevices itself).\nfunction QuickApp:pruneRemovedChildren()\n  local ok, devices = pcall(api.get, '/devices?parentId=' .. tostring(self.id))\n  if not ok or type(devices) ~= 'table' then return end\n  local present = {}\n  for _, d in ipairs(devices) do present[tostring(d.id)] = true end\n  local gone = {}\n  for id in pairs(self.bindings) do\n    if not present[id] then gone[#gone + 1] = id end\n  end\n  for id in pairs(self.childDevices or {}) do\n    if not present[tostring(id)] and not self.bindings[tostring(id)] then gone[#gone + 1] = tostring(id) end\n  end\n  for _, id in ipairs(gone) do\n    self:debug('ArtiCONTROL: child ' .. id .. ' was removed in the HC3; forgetting it')\n    local child = self.childDevices and self.childDevices[tonumber(id)]\n    if child then child.removed = true end\n    if self.control then self.control:dropChild(tonumber(id)) end\n    if self.childDevices then self.childDevices[tonumber(id)] = nil end\n    self.bindings[id] = nil\n  end\n  if #gone > 0 then self:saveBindings() end\nend\n\n-- !! POLL OWNERSHIP (Mycroft 8645 HCF-S1). A poll holds self.busy = {gen = <generation>} while its reads\n-- run; only THAT poll's completion may release it. A poll of an older generation no longer blocks: the next\n-- tick retires it and starts its own, and the old one's late completion clears nothing of the new one.\n-- Completion and publication stay separate: a retired poll finishes, but publishes nothing.\nfunction QuickApp:pollBusy()\n  local b = self.busy\n  if not b then return false end\n  if b.gen ~= self.control.gen then self.busy = nil; return false end   -- superseded: retired\n  return true\nend\n\nfunction QuickApp:releasePoll(mine)\n  if self.busy == mine then self.busy = nil end\nend\n\nfunction QuickApp:pollTick(force)\n  if not self.control or self.foreign or self.authFailed or self:pollBusy() then return end\n  if not force then self.tick = self.tick + 1 end\n  local inventory = (self.tick % QuickApp.INVENTORY_EVERY) == 1\n\n  -- After a lost connection (generation bump) commands stay refused until /alive matches again.\n  if not self.control.verified then\n    local gen = self.control.gen\n    local mine = { gen = gen }\n    self.busy = mine\n    return self:checkIdentity(gen, function(ok, retired)\n      self:releasePoll(mine)\n      if ok and not retired and self:internalStorageGet('controlToken') then\n        self:tryToken(gen, self:internalStorageGet('controlToken'), nil)\n      end\n    end)\n  end\n\n  if inventory then\n    self:pruneRemovedChildren()\n    self:retryClassification()\n  end\n  local need = self:needs()\n  local gen = self.control.gen\n  local results, pending, failed = { activities = {}, favourites = {} }, 0, nil\n  local mine = { gen = gen }\n  local function finishOne()\n    pending = pending - 1\n    if pending == 0 then\n      self:releasePoll(mine)\n      self:applyTick(gen, results, failed, inventory)\n    end\n  end\n  -- 'retired' and 'dropped' finish a read without saying anything about the Control: the failure that\n  -- caused them is reported by the request that met it.\n  local function noteFail(code)\n    if code ~= 'retired' and code ~= 'dropped' then failed = failed or code or 'malformed' end\n  end\n  self.busy = mine\n  local function want(fn) pending = pending + 1; fn() end\n  want(function()\n    self.control:read('rooms', {}, function(ok, d, code)\n      if ok and type(d.rooms) == 'table' then results.rooms = d.rooms elseif ok then noteFail('malformed') else noteFail(code) end\n      finishOne()\n    end)\n  end)\n  want(function()\n    self.control:read('zones', {}, function(ok, d, code)\n      if ok and type(d.zones) == 'table' then results.zones = d.zones elseif ok then noteFail('malformed') else noteFail(code) end\n      finishOne()\n    end)\n  end)\n  if inventory then\n    -- !! The identity is judged the MOMENT /alive answers: commands overtake waiting reads, so a later\n    -- check would let one reach another Control.\n    want(function()\n      self.control:alive(function(ok, d)\n        if ok and gen == self.control.gen and type(d) == 'table'\n          and ArtiUnits.qualifiedIdent(d.ident) ~= self:internalStorageGet('controlIdent') then\n          self:foreignControl()\n        end\n        finishOne()\n      end)\n    end)\n    for key, u in pairs(need.units) do\n      want(function()\n        self.control:read('activities', ArtiUnits.arg(u.kind, u.id), function(ok, d)\n          -- A failed or malformed read is UNKNOWN: it never proves removal.\n          if ok and type(d.activities) == 'table' then results.activities[key] = d.activities end\n          finishOne()\n        end)\n      end)\n    end\n    for aid in pairs(need.favourites) do\n      want(function()\n        self.control:read('activity_favorites', { activity = aid }, function(ok, d, code)\n          if ok and type(d.items) == 'table' then results.favourites[aid] = d.items\n          elseif code == 'error7' then\n            -- Error 7 is the Control's documented answer \"this activity plays nothing that has favourites\"\n            -- (ArtiControlAPI /activity_favorites): a successful statement that the list is empty. Any OTHER\n            -- failure (error 5 \"could not be read now\", transport, malformed) is unknown and keeps the list.\n            results.favourites[aid] = {}\n          end\n          finishOne()\n        end)\n      end)\n    end\n  end\nend\n\nlocal function activityIn(list, id)\n  for _, a in ipairs(list or {}) do\n    if int(a.id) == int(id) then return a end\n  end\n  return nil\nend\n\nfunction QuickApp:applyTick(gen, results, failed, inventory)\n  if self.foreign then return end\n  -- !! Generation ownership: a tick asked under an older connection publishes no STATE. Its failure may\n  -- still say the connection is down - but only while no newer generation has been verified since.\n  if gen ~= self.control.gen and (not failed or self.control.verified) then return end\n  if failed then\n    if failed == 'auth' then\n      self.authFailed = true\n      self:status('ArtiCONTROL login no longer valid: fill in ControlUser and ControlPassword again')\n      return self:allDead('ArtiCONTROL login no longer valid: sign in again on the parent')\n    end\n    self.unhealthy = true\n    self:status('ArtiCONTROL not reachable at ' .. self.control.ip)\n    return self:allDead('ArtiCONTROL not reachable')\n  end\n  -- A poll whose reads were dropped (no failure of its own) has no complete picture: publish nothing.\n  if type(results.rooms) ~= 'table' or type(results.zones) ~= 'table' then return end\n  self.unhealthy = false\n  self.connDead = nil\n  self:status(self.controlName .. ' - ' .. tostring(self.controlVersion or '?') .. ' - connected')\n\n  -- Keep only SUCCESSFUL inventory reads; a failed one leaves the last known list in place.\n  for key, list in pairs(results.activities) do self.inv.activities[key] = list end\n  for aid, list in pairs(results.favourites) do self.inv.favourites[aid] = list end\n  self.lists = { rooms = results.rooms, zones = results.zones }\n\n  local t = now()\n  self:eachChild(function(child)\n    local s = child.spec\n    if not s then return end\n    if self.unclassified[tostring(child.id)] then\n      child.badReason = QuickApp.INERT\n      return child:showDead(QuickApp.INERT)\n    end\n    local st, record = ArtiUnits.lookup(results.rooms, results.zones, s.unitKind, s.unitId)\n    local ukey = ArtiUnits.key(s.unitKind, s.unitId)\n    if st ~= 'ok' then\n      self.records[ukey] = nil\n      child.badReason = st == 'hidden' and 'Hidden on the ArtiCONTROL' or 'No longer a room or zone on the ArtiCONTROL'\n      return child:showDead(child.badReason)\n    end\n    self.records[ukey] = record\n    if s.kind == 'room' then\n      child.badReason = nil\n      return child:applyRoom(record, t)\n    end\n    local acts = self.inv.activities[ukey]\n    local reason = nil\n    if acts then\n      local src = ArtiUnits.sources(s.unitKind, acts)\n      if s.kind == 'switch' then\n        if not activityIn(src, s.onId) or not activityIn(src, s.offId) then\n          reason = 'Its activities are no longer in ' .. record.name\n        end\n      elseif not activityIn(src, s.activityId) then\n        reason = 'No longer an activity of ' .. record.name\n      end\n      if not reason and s.kind == 'favourite' then\n        local favs = self.inv.favourites[int(s.activityId)]\n        if favs and not ArtiRules.favouriteIn(s, favs) then\n          local a = activityIn(src, s.activityId)\n          reason = 'No longer in the favourites of ' .. tostring(a and a.name or 'this activity')\n        elseif not favs then\n          reason = child.goneReason                    -- never read yet / unknown: keep the last verdict\n        end\n      end\n    else\n      reason = child.goneReason                        -- inventory unknown: keep the last verdict\n    end\n    child.goneReason = reason\n    child.badReason = reason\n    if reason then return child:showDead(reason) end\n    if s.kind == 'switch' then\n      child:applySwitch(ArtiRules.switchOn(s, record), t, record.status)\n    else\n      child:applyButton(record.status, t)\n    end\n  end)\nend\n\n-- ---------------------------------------------------------------------------------------------------\n-- Commands from children\n\nlocal function outcomeNote(code, err)\n  if code == 'unknown' then return 'Unknown - may have been sent (no reply from the ArtiCONTROL)' end\n  if code == 'retired' then return 'Unknown - the connection changed after it was sent' end\n  if code == 'malformed' then return 'Unknown - the ArtiCONTROL\\'s answer could not be read (it may have started)' end\n  if code == 'dry-run' then return 'DRY-RUN: nothing was sent' end\n  return tostring(err)\nend\n\nfunction QuickApp:childAction(child, action)\n  local spec = child.spec\n  if not spec then return child:note('Not linked to an ArtiCONTROL item: nothing sent') end\n  -- A pulse's turnOff does nothing (the button springs back by itself).\n  if (spec.kind == 'activity' or spec.kind == 'favourite') and action == 'turnOff' then return end\n  if not self.control then return child:note('Not sent: the ArtiCONTROL is not set up') end\n  if self.unclassified[tostring(child.id)] then return child:note('Not sent: ' .. QuickApp.INERT) end\n  local label = action .. ' on device ' .. tostring(child.id)\n  self.control:command(child.id, label, function()\n    -- !! Decided AT DISPATCH: the binding and the unit are checked again after every earlier command.\n    if child.removed or not child.spec then return nil, 'not sent: device removed', 'skipped' end\n    if self.connDead then return nil, 'not sent: ' .. self.connDead, 'skipped' end\n    if self.unclassified[tostring(child.id)] then return nil, 'not sent: ' .. QuickApp.INERT, 'skipped' end\n    if child.badReason then return nil, 'not sent: ' .. child.badReason, 'skipped' end\n    local record = self.records[ArtiUnits.key(spec.unitKind, spec.unitId)]\n    local req, why, kind = ArtiRules.command(spec, action, record, child.shownOn)\n    if not req then return nil, why, kind == 'ignore' and 'ignored' or 'skipped' end\n    return req\n  end, function(ok, data, code, _, req)\n    -- A superseded command's late completion publishes nothing on the child (its connection is gone).\n    if child.removed or code == 'retired' then return end\n    if not ok then\n      if code ~= 'ignored' then child:failed(outcomeNote(code, data), now()) end\n      return\n    end\n    local refusal = ArtiRules.acceptance(req, data)\n    if refusal then return child:failed(refusal, now()) end\n    if spec.kind == 'activity' or spec.kind == 'favourite' then\n      child:pulse()\n    elseif spec.kind == 'switch' then\n      child:afterSwitch(req and req.data and int(req.data.activity) == int(spec.onId), now())\n    end\n    self:earlyPolls()\n  end)\nend\n\n-- ---------------------------------------------------------------------------------------------------\n-- Parent actions for Fibaro scenes: fibaro.call(<parent id>, 'allRoomsOff')\n\n-- Every unit's Off activity, as the webapp house switch. A unit without an Off activity is skipped and\n-- named. Reported per unit - never as \"all off\": a start is not proof the room is physically off.\nfunction QuickApp:allRoomsOff(cb)\n  cb = cb or function() end\n  local function report(text)\n    self:updateInfo(text)\n    self:updateProperty('log', text)\n    self:debug('ArtiCONTROL allRoomsOff: ' .. text)\n    cb(text)\n  end\n  if not self:connected() then return report('Not connected to the ArtiCONTROL: nothing sent') end\n  self.control:read('rooms', {}, function(ok, r)\n    if not ok or type(r.rooms) ~= 'table' then return report('The ArtiCONTROL did not answer: nothing sent') end\n    self.control:read('zones', {}, function(ok2, z)\n      if not ok2 or type(z.zones) ~= 'table' then return report('The ArtiCONTROL did not answer: nothing sent') end\n      local units = ArtiUnits.fromLists(r.rooms, z.zones)\n      local names = ArtiUnits.defaultNames(units)\n      local sent, failedList, skipped, pending = 0, {}, {}, 0\n      local function finish()\n        local parts = { 'Off sent to ' .. sent .. ' room' .. (sent == 1 and '' or 's') }\n        if #failedList > 0 then parts[#parts + 1] = #failedList .. ' failed: ' .. table.concat(failedList, ', ') end\n        if #skipped > 0 then parts[#parts + 1] = 'no Off activity: ' .. table.concat(skipped, ', ') end\n        report(table.concat(parts, '; '))\n      end\n      for _, u in ipairs(units) do\n        local name = names[ArtiUnits.key(u.kind, u.id)]\n        if int(u.off_activity) <= 0 then\n          skipped[#skipped + 1] = name\n        else\n          pending = pending + 1\n          self.control:command(nil, 'allRoomsOff ' .. name, function() return ArtiRules.start(u.off_activity) end,\n            function(okc, data, code, _, req)\n              local why = okc and ArtiRules.acceptance(req, data) or (not okc and outcomeNote(code, data)) or nil\n              if not why then sent = sent + 1 else failedList[#failedList + 1] = name .. ' (' .. why .. ')' end\n              pending = pending - 1\n              if pending == 0 then finish(); self:earlyPolls() end\n            end)\n        end\n      end\n      if pending == 0 then finish() end\n    end)\n  end)\nend\n\n-- fibaro.call(<parent id>, 'startActivity', 12)  or  ..., 'Watch Netflix')\nfunction QuickApp:startActivity(idOrName, cb)\n  cb = cb or function() end\n  local function report(text) self:updateInfo(text); self:debug('ArtiCONTROL startActivity: ' .. text); cb(text) end\n  if not self:connected() then return report('Not connected to the ArtiCONTROL: nothing sent') end\n  local req = ArtiRules.startByIdOrName(idOrName)\n  if not req then return report('Which activity? Give its id or name') end\n  local what = tostring(req.data.activity or req.data.name)\n  self.control:command(nil, 'startActivity ' .. what, function() return req end, function(ok, data, code, _, sent)\n    local why = ok and ArtiRules.acceptance(sent, data) or (not ok and outcomeNote(code, data)) or nil\n    if why then return report(what .. ': ' .. why) end\n    report('Started ' .. what .. (req.data.name and (' (' .. tostring(#data.activities) .. ' activit' .. (#data.activities == 1 and 'y' or 'ies') .. ')') or ''))\n    self:earlyPolls()\n  end)\nend\n\nfunction QuickApp:refresh()\n  self:pollTick(true)\nend\n\n-- ---------------------------------------------------------------------------------------------------\n-- Adding a child: the installer's deliberate choice, from the view (Add) or as an action.\n--   kind 'room'      addEntity('room', 'zone:3')\n--   kind 'activity'  addEntity('activity', 'zone:3', 41)\n--   kind 'switch'    addEntity('switch', 'zone:3', 41, 12)      (off defaults to the unit's Off activity)\n--   kind 'favourite' addEntity('favourite', 'zone:3', 41, nil, '<match key>')\n\nfunction QuickApp:addEntity(kind, unitKeyStr, activityId, offId, favKey, cb)\n  cb = cb or function() end\n  local function fail(text)\n    self:updateInfo(text)\n    self:debug('ArtiCONTROL addEntity: ' .. text)\n    cb(false, text)\n  end\n  if not self:connected() then return fail('Not connected to the ArtiCONTROL') end\n  local uk, uid = tostring(unitKeyStr or ''):match('^(%a+):(%d+)$')\n  if (uk ~= 'room' and uk ~= 'zone') or not ArtiRules.KINDS[kind] then return fail('Choose what to add, and a room or zone') end\n  local ident = self:internalStorageGet('controlIdent')\n  local spec = { ident = ident, kind = kind, unitKind = uk, unitId = int(uid) }\n\n  self.control:read('rooms', {}, function(ok, r)\n    if not ok or type(r.rooms) ~= 'table' then return fail('The ArtiCONTROL did not answer') end\n    self.control:read('zones', {}, function(ok2, z)\n      if not ok2 or type(z.zones) ~= 'table' then return fail('The ArtiCONTROL did not answer') end\n      local st, record = ArtiUnits.lookup(r.rooms, z.zones, uk, uid)\n      if st ~= 'ok' then return fail('That room or zone is not on the ArtiCONTROL (or hidden)') end\n      local names = ArtiUnits.defaultNames(ArtiUnits.fromLists(r.rooms, z.zones))\n      local unitName = names[ArtiUnits.key(uk, uid)] or record.name\n      self.control:read('activities', ArtiUnits.arg(uk, uid), function(ok3, a)\n        if not ok3 or type(a.activities) ~= 'table' then return fail('The ArtiCONTROL did not answer') end\n        local src = ArtiUnits.sources(uk, a.activities)\n        if not ArtiUnits.usable(record, a.activities) then return fail(unitName .. ' has nothing but its Off activity') end\n        local name\n        if kind == 'room' then\n          name = unitName\n        elseif kind == 'activity' then\n          local act = activityIn(src, activityId)\n          if not act then return fail('That activity is not in ' .. unitName) end\n          spec.activityId = int(act.id)\n          name = tostring(act.name) .. ' in ' .. unitName\n        elseif kind == 'switch' then\n          local on = activityIn(src, activityId)\n          local offAct = activityIn(src, (offId ~= nil and offId ~= '') and offId or record.off_activity)\n          if not on then return fail('Choose the activity the switch turns on') end\n          if not offAct then return fail(unitName .. ' has no Off activity: choose what the switch turns off') end\n          if int(on.id) == int(offAct.id) then return fail('On and off must be different activities') end\n          spec.onId, spec.offId = int(on.id), int(offAct.id)\n          name = tostring(on.name) .. (int(offAct.id) ~= int(record.off_activity) and ('/' .. tostring(offAct.name)) or '')\n        end\n        local function create()\n          -- !! Re-checked HERE, after the asynchronous reads: two Adds of the same item can both pass an\n          -- earlier check before either creates a device.\n          if not ArtiRules.validSpec(spec) then return fail('Not a valid choice') end\n          local key = ArtiRules.key(spec)\n          for cid, b in pairs(self.bindings) do\n            if ArtiRules.validSpec(b) and ArtiRules.key(b) == key then\n              return fail('Already added (device ' .. tostring(cid) .. ')')\n            end\n          end\n          local devName = NAME_PREFIX .. name\n          local child = self:createChildDevice({ name = devName, type = 'com.fibaro.binarySwitch',\n            initialProperties = { deviceRole = QuickApp.ROLE.deviceRole, categories = QuickApp.ROLE.categories },\n            initialInterfaces = {} }, ArtiChild)\n          if not child then return fail('The HC3 did not create the device') end\n          -- Not a lamp (see NOT A LIGHT above): only a confirmed role makes the child usable.\n          local marked = self:classify(child.id)\n          if not marked then self:setUnclassified(child.id, true) end\n          self.bindings[tostring(child.id)] = spec\n          self:saveBindings()\n          self:bindChild(child)\n          if marked then\n            self:updateInfo('Added ' .. devName .. ' (device ' .. tostring(child.id) .. ')')\n          else\n            child.badReason = QuickApp.INERT\n            child:showDead(QuickApp.INERT)\n            self:updateInfo('Added but NOT usable: ' .. devName .. ' (device ' .. tostring(child.id)\n              .. ') - the HC3 did not mark it as not-a-light, so nothing is sent; tried again every minute')\n          end\n          self:debug('ArtiCONTROL: added ' .. key .. ' as ' .. tostring(child.id) .. (marked and '' or ' (INERT: role not set)'))\n          setTimeout(function() self:pollTick(true) end, 500)\n          cb(true, child.id, not marked and 'inert' or nil)\n        end\n        if kind ~= 'favourite' then return create() end\n        local act = activityIn(src, activityId)\n        if not act then return fail('That activity is not in ' .. unitName) end\n        self.control:read('activity_favorites', { activity = int(act.id) }, function(ok4, f)\n          if not ok4 or type(f.items) ~= 'table' then return fail('The favourites of ' .. tostring(act.name) .. ' could not be read') end\n          for _, it in ipairs(f.items) do\n            local m = ArtiRules.matchIdentity(it.play)\n            if m and ArtiRules.matchKey(m) == favKey then\n              spec.activityId = int(act.id)\n              spec.play = it.play                    -- verbatim: never rebuilt from labels\n              spec.match = m\n              spec.title = tostring(it.title or '')\n              name = tostring(it.title or 'Favourite') .. ' in ' .. unitName\n              return create()\n            end\n          end\n          fail('That favourite is no longer in ' .. tostring(act.name))\n        end)\n      end)\n    end)\n  end)\nend\n\n-- ==== src/view.lua ====\n-- Copyright (C) 2026 ArtiLED B.V. All Rights Reserved.\n--\n-- The parent's view: the installer picks what to add, one item at a time - never a bulk import.\n-- The same view as the ArtiLED Hub Quick App (Michel 2026-10-26): Kind, then ONE list with everything\n-- of that kind, then Add.\n--   lblStatus   Control name - version - connected / what is wrong\n--   selKind     Room / Activity / Activity switch / Favourite\n--   selItem     everything of that kind, over every usable room and zone:\n--                 Room             \"Kitchen\"\n--                 Activity         \"Netflix in Cinewall\" (Off included)\n--                 Activity switch  \"Netflix in Cinewall\" (off = that room's or zone's Off activity)\n--                 Favourite        \"Jazz - Sonos in Kitchen\" (only activities whose player has favourites)\n--   btnAdd / btnRefresh / lblInfo\n-- The layout is in view/view.json (packed into the .fqa); an in-place code update does not change it.\n--\n-- An option's value carries everything Add needs: '<kind>#<unit key>#<activity id>#<favourite key>'\n-- (empty fields where the kind has none), e.g. 'favourite#zone:3#43#music|sonos_favorite|Jazz'.\n\nlocal KINDS = {\n  { text = 'Room', type = 'option', value = 'room' },\n  { text = 'Activity', type = 'option', value = 'activity' },\n  { text = 'Activity switch', type = 'option', value = 'switch' },\n  { text = 'Favourite', type = 'option', value = 'favourite' },\n}\n\nlocal function selected(event)\n  local v = event and event.values and event.values[1]\n  if type(v) == 'table' then v = v[1] end\n  return v\nend\n\nfunction QuickApp:updateInfo(text)\n  pcall(function() self:updateView('lblInfo', 'text', text) end)\nend\n\n-- The ONE place a select's options are written.\nfunction QuickApp:setOptions(name, options)\n  pcall(function() self:updateView(name, 'options', options) end)\nend\n\nfunction QuickApp:initView()\n  self:setOptions('selKind', KINDS)\n  self:setOptions('selItem', {})\n  local n = 0\n  for _ in pairs(self.childDevices or {}) do n = n + 1 end\n  self:updateInfo(n .. ' ArtiCONTROL device(s). Choose a kind, then what to add.')\nend\n\n-- !! SELECTION OWNERSHIP (Mycroft 8645 HCF-S5). The queue serialises requests, not the installer's choices:\n-- a reply can arrive after another kind was chosen. Every kind choice (and Refresh) bumps ui.epoch and\n-- empties the list at once; each read captures the epoch it was asked under, and its reply - success OR\n-- failure - publishes nothing when the epoch has moved on. ui.items holds the values of the list that is\n-- shown now; Add takes nothing that is not in it.\nfunction QuickApp:choose()\n  self.ui = self.ui or {}\n  self.ui.epoch = (self.ui.epoch or 0) + 1\n  local e = self.ui.epoch\n  return function() return self.ui and self.ui.epoch == e end\nend\n\nlocal function itemValue(kind, unitKey, activityId, favKey)\n  return kind .. '#' .. unitKey .. '#' .. (activityId and tostring(activityId) or '') .. '#' .. (favKey or '')\nend\n\n-- -> kind, unit key, activity id (number or nil), favourite key (or nil)\nlocal function parseItem(v)\n  local kind, unit, act, fav = tostring(v or ''):match('^(%a+)#(%a+:%d+)#(%d*)#(.*)$')\n  if not kind then return nil end\n  return kind, unit, tonumber(act), (fav ~= '' and fav or nil)\nend\n\n-- Grouped by room or zone, then activity, then favourite (the list reads as the house does).\nlocal function sortItems(out)\n  table.sort(out, function(a, b)\n    for i = 1, 3 do\n      local x, y = (a.sort[i] or ''):lower(), (b.sort[i] or ''):lower()\n      if x ~= y then return x < y end\n    end\n    return a.value < b.value\n  end)\n  local opts = {}\n  for _, o in ipairs(out) do opts[#opts + 1] = { text = o.text, type = 'option', value = o.value } end\n  return opts\nend\n\nlocal function activityIn(list, id)\n  for _, a in ipairs(list or {}) do\n    if ArtiUnits.int(a.id) == ArtiUnits.int(id) then return a end\n  end\n  return nil\nend\n\nlocal DONE = {\n  room = { 'Choose the room or zone, then Add', 'No room or zone has an activity to start' },\n  activity = { 'Choose the activity, then Add (repeat for each one you want)', 'No activity to add' },\n  switch = { 'Choose what the switch turns on (it turns off with the Off activity of that room or zone), then Add',\n    'No room or zone has an activity and an Off activity' },\n  favourite = { 'Choose the favourite, then Add (repeat for each one you want)', 'No activity has favourites' },\n}\n\n-- Kind chosen: read the rooms and zones, then /activities per unit (\"usable\" and the activities), then for\n-- a Favourite /activity_favorites once per activity; publish the one list when every read has answered.\nfunction QuickApp:onKind(event)\n  self.ui = { kind = selected(event), epoch = self.ui and self.ui.epoch }\n  local kind = self.ui.kind\n  local current = self:choose()\n  self:setOptions('selItem', {})\n  if not DONE[kind] then return self:updateInfo('Choose a kind') end\n  if not self:connected() then return self:updateInfo('Not connected to the ArtiCONTROL') end\n  local out, unread = {}, 0\n  local function publish()\n    self.ui.items = {}\n    for _, o in ipairs(out) do self.ui.items[o.value] = true end\n    self:setOptions('selItem', sortItems(out))\n    local text = DONE[kind][#out > 0 and 1 or 2]\n    if unread > 0 then text = text .. ' (' .. unread .. ' room(s) or zone(s) did not answer: Refresh lists)' end\n    self:updateInfo(text)\n  end\n  self.control:read('rooms', {}, function(ok, r)\n    if not current() then return end\n    if not ok or type(r.rooms) ~= 'table' then return self:updateInfo('The ArtiCONTROL did not answer') end\n    self.control:read('zones', {}, function(ok2, z)\n      if not current() then return end\n      if not ok2 or type(z.zones) ~= 'table' then return self:updateInfo('The ArtiCONTROL did not answer') end\n      local units = ArtiUnits.fromLists(r.rooms, z.zones)\n      local names = ArtiUnits.defaultNames(units)\n      local pending = #units\n      if pending == 0 then return self:updateInfo('The ArtiCONTROL has no rooms or zones') end\n      local acts = {}                                -- {key, name, activity} for a Favourite\n      local function favourites()\n        -- One /activity_favorites read per activity; error 7 / empty / unreadable: left out.\n        local left = #acts\n        if left == 0 then return publish() end\n        for _, a in ipairs(acts) do\n          local id = ArtiUnits.int(a.activity.id)\n          local actName = tostring(a.activity.name or a.activity.id)\n          self.control:read('activity_favorites', { activity = id }, function(ok4, f)\n            if not current() then return end\n            if ok4 and type(f.items) == 'table' then\n              for _, it in ipairs(f.items) do\n                local m = type(it) == 'table' and ArtiRules.matchIdentity(it.play)\n                if m then\n                  local label = ArtiRules.favouriteLabel(it)\n                  out[#out + 1] = { text = label .. ' - ' .. actName .. ' in ' .. a.name,\n                    value = itemValue('favourite', a.key, id, ArtiRules.matchKey(m)), sort = { a.name, actName, label } }\n                end\n              end\n            end\n            left = left - 1\n            if left == 0 then publish() end\n          end)\n        end\n      end\n      for _, u in ipairs(units) do\n        local key = ArtiUnits.key(u.kind, u.id)\n        self.control:read('activities', ArtiUnits.arg(u.kind, u.id), function(ok3, a)\n          if not current() then return end\n          if not ok3 or type(a.activities) ~= 'table' then\n            unread = unread + 1\n          elseif ArtiUnits.usable(u, a.activities) then\n            local name = names[key]\n            local src = ArtiUnits.sources(u.kind, a.activities)\n            if kind == 'room' then\n              out[#out + 1] = { text = name, value = itemValue('room', key), sort = { name } }\n            else\n              local off = activityIn(src, u.off_activity)\n              for _, act in ipairs(src) do\n                local actName = tostring(act.name or act.id)\n                local id = ArtiUnits.int(act.id)\n                if kind == 'activity' then\n                  out[#out + 1] = { text = actName .. ' in ' .. name, value = itemValue('activity', key, id), sort = { name, actName } }\n                elseif kind == 'switch' then\n                  -- Off = the unit's Off activity: a unit without one, and the Off activity itself, make no switch.\n                  if off and id ~= ArtiUnits.int(off.id) then\n                    out[#out + 1] = { text = actName .. ' in ' .. name, value = itemValue('switch', key, id), sort = { name, actName } }\n                  end\n                else\n                  acts[#acts + 1] = { key = key, name = name, activity = act }\n                end\n              end\n            end\n          end\n          pending = pending - 1\n          if pending == 0 then\n            if kind == 'favourite' then return favourites() end\n            publish()\n          end\n        end)\n      end\n    end)\n  end)\nend\n\n-- An item is taken only from the list that is shown now, for the kind that is chosen now.\nfunction QuickApp:onItem(event)\n  local v = selected(event)\n  local ui = self.ui or {}\n  if v == nil or not ui.items or not ui.items[v] or parseItem(v) ~= ui.kind then\n    ui.item = nil\n    return self:updateInfo('That is not in the current list: choose again (or Refresh lists)')\n  end\n  ui.item = v\nend\n\nfunction QuickApp:onAdd()\n  local ui = self.ui or {}\n  if not ui.kind then return self:updateInfo('Choose a kind first') end\n  if not ui.item or not ui.items or not ui.items[ui.item] then return self:updateInfo('Choose what to add first') end\n  local kind, unit, activityId, favKey = parseItem(ui.item)\n  if kind ~= ui.kind then return self:updateInfo('Choose what to add first') end\n  if kind == 'room' then return self:addEntity('room', unit) end\n  if kind == 'activity' then return self:addEntity('activity', unit, activityId) end\n  if kind == 'switch' then return self:addEntity('switch', unit, activityId, nil) end   -- off = the unit's Off\n  return self:addEntity('favourite', unit, activityId, nil, favKey)\nend\n\nfunction QuickApp:onRefresh()\n  if self.ui and self.ui.kind then return self:onKind({ values = { self.ui.kind } }) end\n  self:initView()\nend\n",
   "isMain": true,
   "isOpen": true,
   "name": "main",
   "type": "lua"
  }
 ],
 "initialInterfaces": [
  "quickAppChild"
 ],
 "initialProperties": {
  "apiVersion": "1.3",
  "quickAppVariables": [
   {
    "name": "ControlIP",
    "value": ""
   },
   {
    "name": "ControlUser",
    "value": ""
   },
   {
    "name": "ControlPassword",
    "value": ""
   },
   {
    "name": "ControlToken",
    "value": ""
   }
  ],
  "typeTemplateInitialized": true,
  "uiCallbacks": [
   {
    "callback": "onKind",
    "eventType": "onToggled",
    "name": "selKind"
   },
   {
    "callback": "onItem",
    "eventType": "onToggled",
    "name": "selItem"
   },
   {
    "callback": "onAdd",
    "eventType": "onReleased",
    "name": "btnAdd"
   },
   {
    "callback": "",
    "eventType": "onLongPressDown",
    "name": "btnAdd"
   },
   {
    "callback": "",
    "eventType": "onLongPressReleased",
    "name": "btnAdd"
   },
   {
    "callback": "onRefresh",
    "eventType": "onReleased",
    "name": "btnRefresh"
   },
   {
    "callback": "",
    "eventType": "onLongPressDown",
    "name": "btnRefresh"
   },
   {
    "callback": "",
    "eventType": "onLongPressReleased",
    "name": "btnRefresh"
   }
  ],
  "uiView": [
   {
    "components": [
     {
      "name": "lblStatus",
      "style": {
       "weight": "1.00"
      },
      "text": "ArtiCONTROL",
      "type": "label",
      "visible": true
     }
    ],
    "style": {
     "weight": "1.0"
    },
    "type": "horizontal"
   },
   {
    "components": [
     {
      "eventBinding": {
       "onToggled": [
        {
         "params": {
          "actionName": "UIAction",
          "args": [
           "onToggled",
           "selKind",
           "$event.value"
          ]
         },
         "type": "deviceAction"
        }
       ]
      },
      "name": "selKind",
      "options": [],
      "selectionType": "single",
      "style": {
       "weight": "1.00"
      },
      "text": "Kind",
      "type": "select",
      "values": [],
      "visible": true
     }
    ],
    "style": {
     "weight": "1.0"
    },
    "type": "horizontal"
   },
   {
    "components": [
     {
      "eventBinding": {
       "onToggled": [
        {
         "params": {
          "actionName": "UIAction",
          "args": [
           "onToggled",
           "selItem",
           "$event.value"
          ]
         },
         "type": "deviceAction"
        }
       ]
      },
      "name": "selItem",
      "options": [],
      "selectionType": "single",
      "style": {
       "weight": "1.00"
      },
      "text": "Add",
      "type": "select",
      "values": [],
      "visible": true
     }
    ],
    "style": {
     "weight": "1.0"
    },
    "type": "horizontal"
   },
   {
    "components": [
     {
      "eventBinding": {
       "onLongPressDown": [
        {
         "params": {
          "actionName": "UIAction",
          "args": [
           "onLongPressDown",
           "btnAdd"
          ]
         },
         "type": "deviceAction"
        }
       ],
       "onLongPressReleased": [
        {
         "params": {
          "actionName": "UIAction",
          "args": [
           "onLongPressReleased",
           "btnAdd"
          ]
         },
         "type": "deviceAction"
        }
       ],
       "onReleased": [
        {
         "params": {
          "actionName": "UIAction",
          "args": [
           "onReleased",
           "btnAdd"
          ]
         },
         "type": "deviceAction"
        }
       ]
      },
      "name": "btnAdd",
      "style": {
       "weight": "0.50"
      },
      "text": "Add",
      "type": "button",
      "visible": true
     },
     {
      "eventBinding": {
       "onLongPressDown": [
        {
         "params": {
          "actionName": "UIAction",
          "args": [
           "onLongPressDown",
           "btnRefresh"
          ]
         },
         "type": "deviceAction"
        }
       ],
       "onLongPressReleased": [
        {
         "params": {
          "actionName": "UIAction",
          "args": [
           "onLongPressReleased",
           "btnRefresh"
          ]
         },
         "type": "deviceAction"
        }
       ],
       "onReleased": [
        {
         "params": {
          "actionName": "UIAction",
          "args": [
           "onReleased",
           "btnRefresh"
          ]
         },
         "type": "deviceAction"
        }
       ]
      },
      "name": "btnRefresh",
      "style": {
       "weight": "0.50"
      },
      "text": "Refresh lists",
      "type": "button",
      "visible": true
     }
    ],
    "style": {
     "weight": "1.0"
    },
    "type": "horizontal"
   },
   {
    "components": [
     {
      "name": "lblInfo",
      "style": {
       "weight": "1.00"
      },
      "text": "",
      "type": "label",
      "visible": true
     }
    ],
    "style": {
     "weight": "1.0"
    },
    "type": "horizontal"
   }
  ],
  "useUiView": true,
  "userDescription": "ArtiCONTROL: High End Intelligent Control",
  "viewLayout": {
   "$jason": {
    "body": {
     "header": {
      "style": {
       "height": "0"
      },
      "title": "quickApp_device"
     },
     "sections": {
      "items": [
       {
        "components": [
         {
          "name": "lblStatus",
          "style": {
           "weight": "1.00"
          },
          "text": "ArtiCONTROL",
          "type": "label",
          "visible": true
         },
         {
          "style": {
           "weight": "0.5"
          },
          "type": "space"
         }
        ],
        "style": {
         "weight": "1.2"
        },
        "type": "vertical"
       },
       {
        "components": [
         {
          "name": "selKind",
          "options": [],
          "selectionType": "single",
          "style": {
           "weight": "1.00"
          },
          "text": "Kind",
          "type": "select",
          "values": [],
          "visible": true
         },
         {
          "style": {
           "weight": "0.5"
          },
          "type": "space"
         }
        ],
        "style": {
         "weight": "1.2"
        },
        "type": "vertical"
       },
       {
        "components": [
         {
          "name": "selItem",
          "options": [],
          "selectionType": "single",
          "style": {
           "weight": "1.00"
          },
          "text": "Add",
          "type": "select",
          "values": [],
          "visible": true
         },
         {
          "style": {
           "weight": "0.5"
          },
          "type": "space"
         }
        ],
        "style": {
         "weight": "1.2"
        },
        "type": "vertical"
       },
       {
        "components": [
         {
          "components": [
           {
            "name": "btnAdd",
            "style": {
             "weight": "0.50"
            },
            "text": "Add",
            "type": "button",
            "visible": true
           },
           {
            "name": "btnRefresh",
            "style": {
             "weight": "0.50"
            },
            "text": "Refresh lists",
            "type": "button",
            "visible": true
           }
          ],
          "style": {
           "weight": "1.2"
          },
          "type": "horizontal"
         },
         {
          "style": {
           "weight": "0.5"
          },
          "type": "space"
         }
        ],
        "style": {
         "weight": "1.2"
        },
        "type": "vertical"
       },
       {
        "components": [
         {
          "name": "lblInfo",
          "style": {
           "weight": "1.00"
          },
          "text": "",
          "type": "label",
          "visible": true
         },
         {
          "style": {
           "weight": "0.5"
          },
          "type": "space"
         }
        ],
        "style": {
         "weight": "1.2"
        },
        "type": "vertical"
       }
      ]
     }
    },
    "head": {
     "title": "quickApp_device"
    }
   }
  }
 },
 "name": "ArtiCONTROL",
 "type": "com.fibaro.deviceController"
}
