-- Daikin ducted air conditioning plugin for Q-SYS, for the AirBase / SkyFi Wi-Fi adapter -- (BRP15B61). Other Daikin adapters use different paths and mode numbers. -- -- Transport: plain HTTP GETs to http:///skyfi/..., one at a time. Replies are -- "ret=OK,key=value,...". There are no push updates, so the state is polled. -- -- Writes carry the whole state (power, mode, temperature and fan together, or every zone -- together). Each command therefore reads the current state, changes only what was asked -- for and writes it back, so changes made at the wall controller are kept. -- -- Nothing is sent from saved control states at startup. Commands are never retried, or -- held while offline. After a command the state is read back from the adapter. PluginInfo = { Name = "Daikin~Ducted AC (AirBase)", Version = "0.1.2", BuildVersion = "0.1.2.0", Id = "50324de7-091f-4824-8493-9381b581020f", Author = "qsys-plugins", Description = "Daikin ducted AC through the AirBase / SkyFi adapter (BRP15B61): power, mode, temperature, fan, zones and status", } local MODES = { { name = "Cool", id = "2" }, { name = "Heat", id = "1" }, { name = "Auto", id = "3" }, { name = "Dry", id = "7" }, { name = "Fan", id = "0" }, } local FANS = { { name = "Auto", legend = "Auto", rate = "0", auto = "0" }, { name = "Low", legend = "Low", rate = "1", auto = "0" }, { name = "Mid", legend = "Mid", rate = "3", auto = "0" }, { name = "High", legend = "High", rate = "5", auto = "0" }, { name = "LowAuto", legend = "Low/Auto", rate = "1", auto = "1" }, { name = "MidAuto", legend = "Mid/Auto", rate = "3", auto = "1" }, { name = "HighAuto", legend = "High/Auto", rate = "5", auto = "1" }, } function GetColor(props) return { 0, 160, 220 } end function GetPrettyName(props) return "Daikin Ducted AC\n" .. PluginInfo.Version end function GetProperties() return { { Name = "Zones", Type = "integer", Min = 0, Max = 8, Value = 8 }, -- Refuses to close the last open zone. Turn off only if the ductwork allows for it. { Name = "Keep One Zone Open", Type = "boolean", Value = true }, { Name = "Poll Interval (s)", Type = "integer", Min = 5, Max = 60, Value = 10 }, { Name = "Debug", Type = "boolean", Value = false }, } end function GetControls(props) local c = {} local function add(name, def, pin) def.Name, def.Count, def.UserPin, def.PinStyle = name, 1, pin ~= nil, pin c[#c + 1] = def end local function text(name, pin) add(name, { ControlType = "Indicator", IndicatorType = "Text" }, pin) end local function led(name) add(name, { ControlType = "Indicator", IndicatorType = "Led" }, "Output") end local function toggle(name) add(name, { ControlType = "Button", ButtonType = "Toggle" }, "Both") end add("IPAddress", { ControlType = "Text" }, "Input") add("Reconnect", { ControlType = "Button", ButtonType = "Trigger" }, "Input") add("Status", { ControlType = "Indicator", IndicatorType = "Status" }, "Output") led("Online") text("Adapter") text("LastError", "Output") text("State", "Output") add("RoomTemp", { ControlType = "Knob", ControlUnit = "Float", Min = -50, Max = 100 }, "Output") led("RoomTempValid") add("OutsideTemp", { ControlType = "Knob", ControlUnit = "Float", Min = -50, Max = 100 }, "Output") led("OutsideTempValid") led("Fault") text("FaultDetail", "Output") led("FilterSign") toggle("Power") add("Setpoint", { ControlType = "Knob", ControlUnit = "Integer", Min = 16, Max = 32 }, "Both") for _, m in ipairs(MODES) do toggle("Mode" .. m.name) end for _, f in ipairs(FANS) do toggle("Fan" .. f.name) end for i = 1, props["Zones"].Value do text("Zone" .. i .. "Name", "Output") toggle("Zone" .. i .. "On") end return c end function GetControlLayout(props) local layout, graphics = {}, {} local W, ROW, LBL = 400, 22, 110 local y = 6 local zones = props["Zones"].Value local function box(title, rows) graphics[#graphics + 1] = { Type = "GroupBox", Text = title, Fill = { 230, 240, 246 }, StrokeWidth = 1, Position = { 4, y }, Size = { W, 26 + rows * ROW } } y = y + 24 end local function label(text) graphics[#graphics + 1] = { Type = "Text", Text = text, HTextAlign = "Right", FontSize = 11, Position = { 10, y }, Size = { LBL - 14, ROW - 4 } } end local function ctl(name, pretty, x, w, style, legend) layout[name] = { PrettyName = pretty, Position = { x, y }, Size = { w, ROW - 4 }, Style = style, Legend = legend } end box("Connection", 5) label("IP Address"); ctl("IPAddress", "Setup~IP Address", LBL, 150, "Text") ctl("Reconnect", "Setup~Reconnect", LBL + 160, 70, "Button", "Reconnect"); y = y + ROW label("Status"); ctl("Status", "Status", LBL, 280); y = y + ROW label("Online"); ctl("Online", "Online", LBL, 18); y = y + ROW label("Adapter"); ctl("Adapter", "Info~Adapter", LBL, 280); y = y + ROW label("Last error"); ctl("LastError", "Last Error", LBL, 280); y = y + ROW + 8 box("AC status", 5) label("State"); ctl("State", "AC Status~State", LBL, 150); y = y + ROW label("Room (C)"); ctl("RoomTemp", "AC Status~Room Temperature", LBL, 60, "Text") ctl("RoomTempValid", "AC Status~Room Temperature Valid", LBL + 66, 18); y = y + ROW label("Outside (C)"); ctl("OutsideTemp", "AC Status~Outside Temperature", LBL, 60, "Text") ctl("OutsideTempValid", "AC Status~Outside Temperature Valid", LBL + 66, 18); y = y + ROW label("Fault"); ctl("Fault", "AC Status~Fault", LBL, 18) ctl("FaultDetail", "AC Status~Fault Detail", LBL + 24, 256); y = y + ROW label("Clean filter"); ctl("FilterSign", "AC Status~Clean Filter", LBL, 18); y = y + ROW + 8 box("Control", 5) label("Power"); ctl("Power", "Control~Power", LBL, 66, "Button", "Power"); y = y + ROW label("Set temp (C)"); ctl("Setpoint", "Control~Set Temperature", LBL, 280, "Fader"); y = y + ROW label("Mode") for i, m in ipairs(MODES) do ctl("Mode" .. m.name, "Mode~" .. m.name, LBL + (i - 1) * 56, 54, "Button", m.name) end y = y + ROW label("Fan") for i, f in ipairs(FANS) do if i == 5 then y = y + ROW end local col = i <= 4 and i - 1 or i - 4 -- each /Auto speed sits under its plain speed ctl("Fan" .. f.name, "Fan~" .. f.legend, LBL + col * 70, 68, "Button", f.legend) end y = y + ROW + 8 if zones > 0 then box("Zones", zones) end for i = 1, zones do local p, g = "Zone" .. i, "Zone " .. i .. "~" label("Zone " .. i) ctl(p .. "Name", g .. "Name", LBL, 200) ctl(p .. "On", g .. "On", LBL + 206, 74, "Button", "Open") y = y + ROW end return layout, graphics end if Controls then local ZONES = Properties["Zones"].Value local KEEP_OPEN = Properties["Keep One Zone Open"].Value local POLL_S = Properties["Poll Interval (s)"].Value local DEBUG = Properties["Debug"].Value local TIMEOUT_S, SETTLE_S, SETPOINT_S, MAX_MISSES = 10, 1, 0.5, 2 -- some replies take over 3 s local function dbg(...) if DEBUG then print("[Daikin]", ...) end end local function trim(s) return tostring(s or ""):match("^%s*(.-)%s*$") end local function decode(s) return (tostring(s or ""):gsub("%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end)) end local function split(s) -- "a;b;c", keeping empty items local t = {} for item in (decode(s) .. ";"):gmatch("([^;]*);") do t[#t + 1] = item end return t end local host = "" local generation = 0 -- bumped on every (re)connect so stale replies are ignored local online, misses = false, 0 local model = nil -- get_model_info reply local last = {} -- last replies shown: last.control, last.zones local wantMode, wantFan -- mode id / fan entry requested but not read back yet local notes = {} -- degraded conditions shown in Status local active, commands, reads = false, {}, {} local running = 0 -- commands queued or in progress local settling, adjusting = false, false local pollTimer, settleTimer, setpointTimer = Timer.New(), Timer.New(), Timer.New() local function setStatus(code, text) Controls.Status.Value = code Controls.Status.String = text or "" Controls.Online.Boolean = online end local function showStatus() if not online then return end local t = {} for _, key in ipairs({ "fault", "sensor", "zones", "info" }) do t[#t + 1] = notes[key] end setStatus(#t > 0 and 1 or 0, table.concat(t, "; ")) end -- True while the controls show a requested change that has not been read back yet. local function pending() return running > 0 or settling or adjusting end --------------------------------------------------------------------------- -- Showing the state --------------------------------------------------------------------------- local function showMode() local id = wantMode or (last.control or {}).mode for _, m in ipairs(MODES) do Controls["Mode" .. m.name].Boolean = m.id == id end end local function showFan() local s = last.control or {} local rate, auto = s.f_rate, s.f_auto or "0" if wantFan then rate, auto = wantFan.rate, wantFan.auto end for _, f in ipairs(FANS) do Controls["Fan" .. f.name].Boolean = f.rate == rate and (rate == "0" or f.auto == auto) end end local function modeName(id) for _, m in ipairs(MODES) do if m.id == id then return m.name end end return "Mode " .. tostring(id) end local function showControl() local s = last.control or {} Controls.Power.Boolean = s.pow == "1" if tonumber(s.stemp or "") then Controls.Setpoint.Value = tonumber(s.stemp) end showMode() showFan() local text = s.mode and modeName(s.mode) or "" if s.mode == "3" and s.operate and s.operate ~= "3" then text = text .. " (" .. modeName(s.operate) .. ")" end if s.pow == "0" then text = "Off" end Controls.State.String = text Controls.FilterSign.Boolean = (tonumber(s.filter_sign_info or "") or 0) ~= 0 end -- Same rules as Home Assistant: zones past the unit's zone count, or named "-", are not -- in use, whatever their on/off value says. local function zoneInUse(i, names, states) local count = tonumber(model and model.en_zone or "") return (states[i] or "") ~= "" and trim(names[i]) ~= "-" and (not count or i <= count) end local function showZones() local z = last.zones local names, states = z and split(z.zone_name) or {}, z and split(z.zone_onoff) or {} for i = 1, ZONES do local exists = zoneInUse(i, names, states) Controls["Zone" .. i .. "Name"].String = trim(names[i]) Controls["Zone" .. i .. "On"].Boolean = exists and states[i] ~= "0" Controls["Zone" .. i .. "On"].IsDisabled = z ~= nil and not exists end end -- Back to what the adapter last reported, undoing any unconfirmed change on screen. local function revert() wantMode, wantFan = nil, nil showControl() showZones() end local function modeProblem(m) if model and ((m.id == "3" and model.en_auto == "0") or (m.id == "7" and model.en_dry == "0")) then return "not supported by this unit" end end local function fanProblem(f) if model and (model.en_frate == "0" or (model.frate_steps == "2" and f.rate == "3") or (model.en_frate_auto == "0" and (f.rate == "0" or f.auto == "1"))) then return "not supported by this unit" end end local function showSupported() for _, m in ipairs(MODES) do Controls["Mode" .. m.name].IsDisabled = modeProblem(m) ~= nil end for _, f in ipairs(FANS) do Controls["Fan" .. f.name].IsDisabled = fanProblem(f) ~= nil end end local function showTemp(name, value) value = tonumber(value or "") -- "-" when there is no sensor if value then Controls[name].Value = value end Controls[name .. "Valid"].Boolean = value ~= nil end --------------------------------------------------------------------------- -- HTTP --------------------------------------------------------------------------- -- cb(reply, err, reached): reply is nil unless ret=OK; reached means the adapter answered. local function request(path, cb) local gen = generation HttpClient.Download({ Url = "http://" .. host .. "/skyfi/" .. path, Timeout = TIMEOUT_S, EventHandler = function(_, code, data, err) if gen ~= generation then return end -- basic_info can contain Wi-Fi and account details, so its reply is not printed. dbg(path, code, path == "common/basic_info" and "(reply hidden)" or data) local reply = {} for item in tostring(data or ""):gmatch("[^,\r\n]+") do local k, v = item:match("^%s*([^=]+)=(.*)$") if k then reply[k] = v end end if code == 200 and reply.ret == "OK" then cb(reply, nil, true) elseif reply.ret then cb(nil, reply.ret .. (reply.msg and " (" .. reply.msg .. ")" or ""), true) elseif code and code > 0 then cb(nil, "unexpected reply, HTTP " .. tostring(code), false) else cb(nil, "no reply" .. (err and err ~= "" and ": " .. tostring(err) or ""), false) end end, }) end -- One job at a time, commands before reads. A command's read and write are a single job. local function pump() if active then return end local job = table.remove(commands, 1) or table.remove(reads, 1) if not job then return end active = true job(function() active = false; pump() end) end local function dropCommands() local n = #commands running = running - n commands = {} return n end --------------------------------------------------------------------------- -- Polling --------------------------------------------------------------------------- local function read(path, cb) reads[#reads + 1] = function(done) request(path, function(...) cb(...); done() end) end end local function pollFailed(err) misses = misses + 1 reads = {} -- no point asking for the rest if online and misses < MAX_MISSES then if not pending() then revert() end return end online = false settling, adjusting = false, false settleTimer:Stop(); setpointTimer:Stop() if dropCommands() > 0 then Controls.LastError.String = "AC offline, command not sent" end revert() Controls.RoomTempValid.Boolean = false Controls.OutsideTempValid.Boolean = false setStatus(4, "Adapter not responding: " .. err) end local function poll() if host == "" or active or #reads > 0 or pending() then return end read("aircon/get_control_info", function(s, err) if not (s and s.pow and s.mode) then pollFailed(err or "incomplete reply"); return end misses, online = 0, true if not pending() then last.control, wantMode, wantFan = s, nil, nil showControl() end showStatus() end) if ZONES > 0 then read("aircon/get_zone_setting", function(s, err) local usable = s and s.zone_name and s.zone_onoff notes.zones = not usable and ("Zones unavailable: " .. (err or "incomplete reply")) or nil if usable and not pending() then last.zones = s end if not pending() then showZones() end showStatus() end) end read("aircon/get_sensor_info", function(s, err) notes.sensor = not s and ("Temperatures unavailable: " .. err) or nil showTemp("RoomTemp", s and s.htemp) showTemp("OutsideTemp", s and s.otemp) showStatus() end) read("common/basic_info", function(s, err) notes.info = not s and ("Fault status unavailable: " .. err) or nil if s then local t = {} for _, key in ipairs({ "err", "err_type", "err_code" }) do local v = trim(decode(s[key])) if v ~= "" and v ~= "-" and tonumber(v) ~= 0 then t[#t + 1] = key .. "=" .. v end end local detail = table.concat(t, ", ") Controls.Fault.Boolean = detail ~= "" Controls.FaultDetail.String = detail notes.fault = detail ~= "" and ("AC fault: " .. detail) or nil Controls.Adapter.String = trim(decode(s.name)) .. " (firmware " .. (s.ver or "?"):gsub("_", ".") .. ")" end showStatus() end) if not model then read("aircon/get_model_info", function(s) if s then model = s showSupported() if not pending() then showZones() end -- now that the zone count is known end end) end pump() end --------------------------------------------------------------------------- -- Commands --------------------------------------------------------------------------- settleTimer.EventHandler = function() settleTimer:Stop() settling = false poll() -- does nothing if another change is pending: that one will read back end -- Reads readPath, then writes the query from build(state), or stops at its nil, reason. local function command(what, readPath, writePath, build) running = running + 1 reads = {} -- an older poll must not run between the command and its read-back commands[#commands + 1] = function(done) local function finish(err, lost) running = running - 1 if err then -- Do not act on a backlog once an unreachable adapter returns. local dropped = lost and dropCommands() or 0 err = what .. ": " .. err .. (dropped > 0 and " (later commands dropped)" or "") end Controls.LastError.String = err or "" if running == 0 then settling = true settleTimer:Stop() settleTimer:Start(SETTLE_S) -- let the AC apply the change before reading it back end done() end request(readPath, function(state, err, reached) if not state then finish(err .. ", nothing sent", not reached); return end local query, problem = build(state) if not query then finish(problem); return end request(writePath .. "?" .. query, function(reply, writeErr, writeReached) finish(writeErr, not writeReached) end) end) end pump() end local function canSend(what, problem) if not problem and not online then problem = "AC offline, command not sent" end if not problem then return true end Controls.LastError.String = what .. ": " .. problem if not online then revert() end return false end -- change(state) edits the state, or returns a reason not to send anything. local function setControl(what, change) command(what, "aircon/get_control_info", "aircon/set_control_info", function(s) for _, key in ipairs({ "pow", "mode", "stemp", "f_rate" }) do if not s[key] then return nil, "the adapter did not report " .. key end end local problem = change(s) if problem then return nil, problem end -- Same fields as pydaikin's AirBase client. "--" means no humidity setting. return "f_airside=" .. (s.f_airside or "0") .. "&f_auto=" .. (s.f_auto or "0") .. "&f_dir=" .. (s.f_dir or "0") .. "&f_rate=" .. s.f_rate .. "&lpw=&mode=" .. s.mode .. "&pow=" .. s.pow .. "&shum=" .. (s.shum or "--") .. "&stemp=" .. s.stemp end) end -- Sends a set temperature that is still waiting for the control to stop moving. Other -- commands call this first, so everything is sent in the order it was asked for. local function sendSetpoint() setpointTimer:Stop() if not adjusting then return end adjusting = false local wanted = math.floor(Controls.Setpoint.Value + 0.5) setControl("Set temperature", function(s) if s.mode ~= "1" and s.mode ~= "2" and s.mode ~= "3" then return "not used in " .. modeName(s.mode) .. " mode" end local m = model or {} if m.en_temp_setting == "0" then return "not supported by this unit" end local coolL, coolH = tonumber(m.cool_l or "") or 16, tonumber(m.cool_h or "") or 32 local heatL, heatH = tonumber(m.heat_l or "") or 16, tonumber(m.heat_h or "") or 32 local low, high = math.max(coolL, heatL), math.min(coolH, heatH) -- Auto: valid for both if s.mode == "2" then low, high = coolL, coolH elseif s.mode == "1" then low, high = heatL, heatH end s.stemp = string.format("%d", math.floor(math.max(low, math.min(high, wanted)))) end) end setpointTimer.EventHandler = sendSetpoint Controls.Setpoint.EventHandler = function() if not canSend("Set temperature") then return end adjusting = true setpointTimer:Stop() setpointTimer:Start(SETPOINT_S) end Controls.Power.EventHandler = function(c) local on = c.Boolean if not canSend("Power") then return end sendSetpoint() setControl("Power", function(s) s.pow = on and "1" or "0" end) end for _, m in ipairs(MODES) do Controls["Mode" .. m.name].EventHandler = function(c) local what = "Mode " .. m.name -- Turning off the lit button does nothing: choose another mode instead. if not c.Boolean or not canSend(what, modeProblem(m)) then showMode(); return end sendSetpoint() wantMode, wantFan = m.id, nil showMode() setControl(what, function(s) if s.mode == m.id then return end -- Bring back the temperature and fan speed the unit keeps for this mode. s.mode = m.id s.stemp = s["dt" .. m.id] or s.stemp s.f_rate = s["dfr" .. m.id] or s.f_rate s.f_auto = s["auto" .. m.id] or s.f_auto end) end end for _, f in ipairs(FANS) do Controls["Fan" .. f.name].EventHandler = function(c) local what = "Fan " .. f.legend if not c.Boolean or not canSend(what, fanProblem(f)) then showFan(); return end sendSetpoint() wantFan = f showFan() setControl(what, function(s) s.f_rate, s.f_auto = f.rate, f.auto end) end end for i = 1, ZONES do Controls["Zone" .. i .. "On"].EventHandler = function(c) local on, what = c.Boolean, "Zone " .. i if not canSend(what) then return end sendSetpoint() command(what, "aircon/get_zone_setting", "aircon/set_zone_setting", function(s) if not (s.zone_name and s.zone_onoff) then return nil, "the adapter did not report its zones" end local names, states = split(s.zone_name), split(s.zone_onoff) if not zoneInUse(i, names, states) then return nil, "not in use on this unit" end states[i] = on and "1" or "0" local anyOpen = false for n, v in ipairs(states) do if v ~= "0" and zoneInUse(n, names, states) then anyOpen = true end end if KEEP_OPEN and not anyOpen then return nil, "not closed, it is the last open zone" end -- Names (and zone temperatures, if any) go back exactly as received, already encoded. local query = "zone_name=" .. s.zone_name .. "&zone_onoff=" .. table.concat(states, "%3b") if s.lztemp_c and s.lztemp_h then query = query .. "&lztemp_c=" .. s.lztemp_c .. "&lztemp_h=" .. s.lztemp_h end return query end) end end --------------------------------------------------------------------------- -- Connection --------------------------------------------------------------------------- function Connect() generation = generation + 1 pollTimer:Stop(); settleTimer:Stop(); setpointTimer:Stop() active, commands, reads, running = false, {}, {}, 0 settling, adjusting = false, false online, misses, model, last, notes = false, 0, nil, {}, {} revert() showSupported() showTemp("RoomTemp", nil) showTemp("OutsideTemp", nil) Controls.Fault.Boolean = false for _, name in ipairs({ "FaultDetail", "Adapter", "LastError" }) do Controls[name].String = "" end host = trim(Controls.IPAddress.String) if host == "" then setStatus(3, "Enter the adapter's IP address") return end setStatus(5, "Connecting to " .. host) pollTimer:Start(POLL_S) poll() end pollTimer.EventHandler = poll Controls.IPAddress.EventHandler = function() Connect() end Controls.Reconnect.EventHandler = function() Connect() end Connect() end