-- Zigbee2MQTT Blinds - Q-SYS plugin
--
-- Controls Zigbee2MQTT covers directly through an MQTT broker.
-- Includes a small MQTT 3.1.1 client (QoS 0, no TLS) built on TcpSocket.
--
-- Topics used ( is the "Base Topic" property):
-- / state in {"position":0-100,"state":"OPEN"}
-- //availability state in (only if enabled in Zigbee2MQTT)
-- //set command out {"state":"OPEN|CLOSE|STOP"} or {"position":n}
-- //get query out (only if the device reports support)
-- /bridge/state, /bridge/devices
--
-- Position: 100 = open, 0 = closed.
-- Commands issued while offline are dropped, never queued, so that blinds do
-- not move unexpectedly on reconnect.
PluginInfo = {
Name = "Blinds~Zigbee2MQTT Blinds",
Version = "1.0.0",
BuildVersion = "1.0.0.0",
Id = "1213d568-55fe-4bb7-9500-abb7de15b253",
Author = "qsys-plugins",
Description = "Control and monitor Zigbee2MQTT blinds over MQTT",
}
local PAGES = { "Control", "Setup" }
local COLUMNS = 8 -- blinds per row on the Control page
function GetColor(props)
return { 141, 207, 244 }
end
function GetPrettyName(props)
return "Zigbee2MQTT Blinds " .. PluginInfo.Version
end
function GetPages(props)
local pages = {}
for _, name in ipairs(PAGES) do
table.insert(pages, { name = name })
end
return pages
end
function GetProperties()
return {
{ Name = "Blind Count", Type = "integer", Min = 1, Max = 32, Value = 6 },
{ Name = "Base Topic", Type = "string", Value = "zigbee2mqtt" },
{ Name = "Debug Print", Type = "enum", Choices = { "Off", "On" }, Value = "Off" },
}
end
function GetControls(props)
local n = props["Blind Count"].Value
local ctrls = {}
local function text(name, count, default, pin)
table.insert(ctrls, {
Name = name, ControlType = "Text", Count = count or 1,
DefaultValue = default, UserPin = pin ~= nil, PinStyle = pin,
})
end
local function trigger(name, count)
table.insert(ctrls, {
Name = name, ControlType = "Button", ButtonType = "Trigger",
Count = count or 1, UserPin = true, PinStyle = "Input",
})
end
local function led(name, count)
table.insert(ctrls, {
Name = name, ControlType = "Indicator", IndicatorType = "Led",
Count = count or 1, UserPin = true, PinStyle = "Output",
})
end
-- Connection
text("BrokerAddress")
table.insert(ctrls, {
Name = "BrokerPort", ControlType = "Knob", ControlUnit = "Integer",
Min = 1, Max = 65535, DefaultValue = 1883, Count = 1,
})
text("Username")
text("Password")
text("ClientId")
table.insert(ctrls, {
Name = "Enable", ControlType = "Button", ButtonType = "Toggle",
Count = 1, UserPin = true, PinStyle = "Both",
})
table.insert(ctrls, {
Name = "Status", ControlType = "Indicator",
IndicatorType = Reflect and "StatusGP" or "Status",
Count = 1, UserPin = true, PinStyle = "Output",
})
led("BridgeOnline")
-- All blinds
trigger("AllOpen")
trigger("AllStop")
trigger("AllClose")
-- Per blind
text("BlindName", n)
text("Discovered", n)
trigger("Open", n)
trigger("Stop", n)
trigger("Close", n)
table.insert(ctrls, {
Name = "Position", ControlType = "Knob", ControlUnit = "Integer",
Min = 0, Max = 100, Count = n, UserPin = true, PinStyle = "Both",
})
table.insert(ctrls, {
Name = "PositionFeedback", ControlType = "Indicator", IndicatorType = "Text",
Count = n, UserPin = true, PinStyle = "Output",
})
led("IsOpen", n)
led("IsClosed", n)
led("Available", n)
return ctrls
end
function GetControlLayout(props)
local layout, graphics = {}, {}
local n = props["Blind Count"].Value
local page = PAGES[props["page_index"].Value]
local DARK = { 60, 60, 60 }
local GREEN = { 0, 159, 60 }
local AMBER = { 242, 162, 0 }
local RED = { 188, 0, 29 }
local BLUE = { 0, 134, 237 }
-- Controls with Count = 1 have no numeric suffix.
local function key(name, i)
return n > 1 and (name .. " " .. i) or name
end
local function label(str, x, y, w, align)
table.insert(graphics, {
Type = "Label", Text = str, Position = { x, y }, Size = { w, 16 },
FontSize = 10, HTextAlign = align or "Right", Color = DARK,
})
end
local function group(str, x, y, w, h)
table.insert(graphics, {
Type = "GroupBox", Text = str, Position = { x, y }, Size = { w, h },
StrokeWidth = 1, CornerRadius = 6, FontSize = 11, HTextAlign = "Left",
})
end
local function button(pretty, legend, x, y, w, h, color)
return {
PrettyName = pretty, Style = "Button", ButtonStyle = "Trigger",
Legend = legend, Position = { x, y }, Size = { w, h },
Color = color, FontSize = 10,
}
end
local function led(pretty, x, y, color)
return {
PrettyName = pretty, Style = "Led", Position = { x, y },
Size = { 16, 16 }, Color = color,
}
end
if page == "Control" then
local TILE_W, TILE_H, GAP = 112, 292, 6
group("All Blinds", 0, 0, 348, 56)
layout["AllOpen"] = button("All~Open", "Open", 10, 22, 104, 26, GREEN)
layout["AllStop"] = button("All~Stop", "Stop", 122, 22, 104, 26, RED)
layout["AllClose"] = button("All~Close", "Close", 234, 22, 104, 26, BLUE)
for i = 1, n do
local x = ((i - 1) % COLUMNS) * (TILE_W + GAP)
local y = 62 + math.floor((i - 1) / COLUMNS) * (TILE_H + GAP)
local p = "Blind " .. i .. "~"
group("Blind " .. i, x, y, TILE_W, TILE_H)
layout[key("BlindName", i)] = {
PrettyName = p .. "Name", Style = "Text", IsReadOnly = true,
TextBoxStyle = "NoBackground", WordWrap = true, FontSize = 10,
HTextAlign = "Center", Position = { x + 4, y + 20 }, Size = { TILE_W - 8, 30 },
}
layout[key("Position", i)] = {
PrettyName = p .. "Position", Style = "Fader", Color = BLUE,
Position = { x + 8, y + 54 }, Size = { 36, 138 },
}
layout[key("PositionFeedback", i)] = {
PrettyName = p .. "Position Feedback", Style = "Text", IsReadOnly = true,
FontSize = 11, HTextAlign = "Center",
Position = { x + 50, y + 54 }, Size = { 54, 20 },
}
label("Open", x + 66, y + 84, 42, "Left")
layout[key("IsOpen", i)] = led(p .. "Is Open", x + 48, y + 84, GREEN)
label("Closed", x + 66, y + 106, 42, "Left")
layout[key("IsClosed", i)] = led(p .. "Is Closed", x + 48, y + 106, AMBER)
label("Online", x + 66, y + 128, 42, "Left")
layout[key("Available", i)] = led(p .. "Available", x + 48, y + 128, GREEN)
layout[key("Open", i)] = button(p .. "Open", "Open", x + 8, y + 200, TILE_W - 16, 26, GREEN)
layout[key("Stop", i)] = button(p .. "Stop", "Stop", x + 8, y + 230, TILE_W - 16, 26, RED)
layout[key("Close", i)] = button(p .. "Close", "Close", x + 8, y + 260, TILE_W - 16, 26, BLUE)
end
elseif page == "Setup" then
group("MQTT Broker", 0, 0, 440, 216)
local fields = {
{ "BrokerAddress", "Address" },
{ "BrokerPort", "Port" },
{ "Username", "Username" },
{ "Password", "Password" },
{ "ClientId", "Client ID (optional)" },
}
for i, f in ipairs(fields) do
local y = 2 + i * 22
label(f[2], 8, y, 120)
layout[f[1]] = {
PrettyName = "Broker~" .. f[2], Style = "Text",
Position = { 134, y }, Size = { 170, 18 }, FontSize = 10,
}
end
layout["Enable"] = {
PrettyName = "Broker~Enable", Style = "Button", ButtonStyle = "Toggle",
Legend = "Enable", Position = { 320, 24 }, Size = { 108, 28 }, Color = GREEN,
}
layout["BridgeOnline"] = led("Broker~Zigbee2MQTT Online", 320, 62, GREEN)
label("Zigbee2MQTT", 340, 62, 92, "Left")
label("Status", 8, 146, 120)
layout["Status"] = {
PrettyName = "Broker~Status", Style = "Text", IsReadOnly = true,
WordWrap = true, FontSize = 10, Position = { 134, 146 }, Size = { 294, 54 },
}
group("Blinds", 0, 222, 440, 50 + n * 22)
label("Zigbee2MQTT friendly name", 44, 242, 190, "Left")
label("Pick a discovered cover", 240, 242, 190, "Left")
for i = 1, n do
local y = 240 + i * 22
label(tostring(i), 8, y, 30)
layout[key("BlindName", i)] = {
PrettyName = "Blind " .. i .. "~Name", Style = "Text",
Position = { 44, y }, Size = { 190, 18 }, FontSize = 10,
}
layout[key("Discovered", i)] = {
PrettyName = "Blind " .. i .. "~Discovered", Style = "ComboBox",
Position = { 240, y }, Size = { 190, 18 }, FontSize = 10,
}
end
end
return layout, graphics
end
--------------------------------------------------------------------------------
-- Runtime
--------------------------------------------------------------------------------
if Controls then
local COUNT = Properties["Blind Count"].Value
local BASE = Properties["Base Topic"].Value:gsub("^%s+", ""):gsub("[%s/]+$", "")
local DEBUG = Properties["Debug Print"].Value == "On"
local KEEPALIVE = 30 -- seconds, sent to the broker
local PING_INTERVAL = 15 -- seconds
local READ_TIMEOUT = 40 -- must be longer than PING_INTERVAL
local RETRY_DELAY = 30 -- seconds, after the broker refuses us
local POSITION_DEBOUNCE = 0.4 -- seconds, so a fader drag sends one command
local POSITION_HOLD = 60 -- seconds to keep the fader on its target
local MAX_PACKET = 8 * 1024 * 1024
local STATUS = { OK = 0, COMPROMISED = 1, FAULT = 2, NOTPRESENT = 3, INITIALIZING = 5 }
-- Do not swap this for the "json" module. That module decodes by running
-- load() on the text, which is unsafe for data from the network.
local jsonLib = require("rapidjson")
local function Debug(...)
if DEBUG then print(...) end
end
local function Decode(str)
local ok, result = pcall(jsonLib.decode, str)
if ok and type(result) == "table" then return result end
return nil
end
-- Controls with Count = 1 are not arrays.
local function Ctl(name, i)
if COUNT > 1 then return Controls[name][i] end
return Controls[name]
end
local function Trim(s)
return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end
-- Globals, so that the socket and timers are not garbage collected.
Socket = nil
PingTimer = Timer.New()
RetryTimer = Timer.New()
Blinds = {}
local generation = 0 -- invalidates events from replaced sockets
local mqttUp = false
local lastError = nil
local subscribeRefused = false
local bridgeOnline = nil -- nil = not reported yet
local packetId = 0
local covers = {} -- friendly name -> { canGet = boolean }
local rxChunks, rxSize, rxNeed = {}, 0, 2
------------------------------------------------------------------------------
-- Status
------------------------------------------------------------------------------
local function SetStatus(value, message)
Controls.Status.Value = value
Controls.Status.String = message
end
local function UpdateStatus()
Controls.BridgeOnline.Boolean = mqttUp and bridgeOnline == true
for i = 1, COUNT do
local b = Blinds[i]
local up = mqttUp and bridgeOnline == true and b.name ~= "" and b.available ~= false
local seen = b.available == true or b.gotState or covers[b.name] ~= nil
Ctl("Available", i).Boolean = up and seen
end
if not Controls.Enable.Boolean then
SetStatus(STATUS.NOTPRESENT, "Disabled")
elseif lastError then
SetStatus(STATUS.FAULT, lastError)
elseif not mqttUp then
SetStatus(STATUS.INITIALIZING, "Connecting")
elseif subscribeRefused then
SetStatus(STATUS.COMPROMISED, "Broker refused a subscription - check user permissions")
elseif bridgeOnline == nil then
SetStatus(STATUS.COMPROMISED, "Connected, but nothing on " .. BASE .. "/bridge/state - check Base Topic")
elseif not bridgeOnline then
SetStatus(STATUS.COMPROMISED, "Connected, but Zigbee2MQTT is offline")
else
SetStatus(STATUS.OK, "Connected")
end
end
------------------------------------------------------------------------------
-- MQTT 3.1.1 encoding
------------------------------------------------------------------------------
local function U16(n)
return string.char(math.floor(n / 256) % 256, n % 256)
end
local function MqttString(s)
return U16(#s) .. s
end
local function Packet(header, body)
local len, encoded = #body, ""
repeat
local byte = len % 128
len = math.floor(len / 128)
if len > 0 then byte = byte + 128 end
encoded = encoded .. string.char(byte)
until len == 0
return string.char(header) .. encoded .. body
end
local function NextPacketId()
packetId = packetId % 65535 + 1
return packetId
end
local function Send(data)
if not (Socket and Socket.IsConnected) then return false end
local ok, err = pcall(function() Socket:Write(data) end)
if not ok then Debug("Write failed:", err) end
return ok
end
local function SendConnect()
local user, pass = Controls.Username.String, Controls.Password.String
local flags = 2 -- clean session
local payload = MqttString(Trim(Controls.ClientId.String))
if user ~= "" then
flags = flags + 128
payload = payload .. MqttString(user)
if pass ~= "" then -- MQTT 3.1.1 does not allow a password without a username
flags = flags + 64
payload = payload .. MqttString(pass)
end
end
Send(Packet(0x10, MqttString("MQTT") .. string.char(4, flags) .. U16(KEEPALIVE) .. payload))
end
local function Subscribe(topic)
if not mqttUp then return end
Debug("SUB", topic)
Send(Packet(0x82, U16(NextPacketId()) .. MqttString(topic) .. string.char(0)))
end
local function Unsubscribe(topic)
if not mqttUp then return end
Debug("UNSUB", topic)
Send(Packet(0xA2, U16(NextPacketId()) .. MqttString(topic)))
end
local function Publish(topic, payload)
if not mqttUp then
Debug("Dropped (offline):", topic, payload)
return false
end
Debug("TX", topic, payload)
return Send(Packet(0x30, MqttString(topic) .. payload)) -- QoS 0, not retained
end
------------------------------------------------------------------------------
-- Blinds
------------------------------------------------------------------------------
local function ValidName(name)
return name ~= "" and not name:find("[+#\0]")
end
local function BlindTopic(name)
return BASE .. "/" .. name
end
local function SubscribeBlind(name)
if not ValidName(name) then return end
Subscribe(BlindTopic(name))
Subscribe(BlindTopic(name) .. "/availability")
end
local function NameInUse(name)
for i = 1, COUNT do
if Blinds[i].name == name then return true end
end
return false
end
-- Ask for the current position, but only where the device supports it.
local function Poll(b)
local cover = covers[b.name]
if cover and cover.canGet and not b.polled then
b.polled = Publish(BlindTopic(b.name) .. "/get", '{"position":""}')
end
end
local function ClearFeedback(i)
local b = Blinds[i]
b.position, b.available, b.gotState, b.polled = nil, nil, false, false
b.target = nil
Ctl("PositionFeedback", i).String = "--"
Ctl("IsOpen", i).Boolean = false
Ctl("IsClosed", i).Boolean = false
end
local function EndHold(i)
local b = Blinds[i]
b.debounce:Stop()
b.hold:Stop()
b.pending, b.target = false, nil
end
local function SetBlindName(i, name)
local b = Blinds[i]
name = Trim(name)
if not ValidName(name) then
if name ~= "" then print("Ignored invalid blind name: " .. name) end
name = ""
end
Ctl("BlindName", i).String = name
if name == b.name then return end
EndHold(i) -- a pending move must not go to the new blind
local old = b.name
b.name = name
ClearFeedback(i)
if old ~= "" and not NameInUse(old) then
Unsubscribe(BlindTopic(old))
Unsubscribe(BlindTopic(old) .. "/availability")
end
SubscribeBlind(name) -- re-subscribing also re-sends any retained state
Poll(b)
UpdateStatus()
end
local function Command(i, state)
EndHold(i)
local b = Blinds[i]
if b.name ~= "" then
Publish(BlindTopic(b.name) .. "/set", '{"state":"' .. state .. '"}')
end
end
local function CommandAll(state)
local sent = {}
for i = 1, COUNT do
local name = Blinds[i].name
if sent[name] then
EndHold(i)
else
sent[name] = true
Command(i, state)
end
end
end
local function SyncFader(i)
local b = Blinds[i]
if b.position and not b.pending and not b.target then
Ctl("Position", i).Value = b.position
end
end
local function SendPosition(i)
local b = Blinds[i]
b.debounce:Stop()
b.pending = false
local target = math.floor(Ctl("Position", i).Value + 0.5)
local sent = b.name ~= "" and
Publish(BlindTopic(b.name) .. "/set", string.format('{"position":%d}', target))
if sent then
-- Keep the fader on its target while the blind travels.
b.target = target
b.hold:Stop()
b.hold:Start(POSITION_HOLD)
else
b.target = nil
SyncFader(i)
end
end
local function ApplyState(i, data)
local b = Blinds[i]
b.gotState = true
local pos = tonumber(data.position)
if pos then
pos = math.max(0, math.min(100, math.floor(pos + 0.5)))
b.position = pos
Ctl("PositionFeedback", i).String = pos .. "%"
-- Some motors stop 1% short of their end positions.
Ctl("IsOpen", i).Boolean = pos >= 99
Ctl("IsClosed", i).Boolean = pos <= 1
if b.target and math.abs(b.target - pos) <= 2 then
b.hold:Stop()
b.target = nil
end
SyncFader(i)
elseif b.position == nil and (data.state == "OPEN" or data.state == "CLOSE") then
Ctl("IsOpen", i).Boolean = data.state == "OPEN"
Ctl("IsClosed", i).Boolean = data.state == "CLOSE"
end
end
------------------------------------------------------------------------------
-- Incoming messages
------------------------------------------------------------------------------
-- Accepts both {"state":"online"} and the older plain "online".
local function ParseOnline(payload)
local data = Decode(payload)
local state = data and data.state or payload
if state == "online" then return true end
if state == "offline" then return false end
return nil
end
local function ParseDevices(payload)
local devices = Decode(payload)
if not devices then
Debug("Could not decode bridge/devices")
return
end
covers = {}
local names = {}
for _, device in ipairs(devices) do
local def = type(device) == "table" and device.definition
local exposes = type(def) == "table" and def.exposes
if type(exposes) == "table" and type(device.friendly_name) == "string" then
for _, expose in ipairs(exposes) do
if type(expose) == "table" and expose.type == "cover" then
local cover = covers[device.friendly_name]
if not cover then
cover = { canGet = false }
covers[device.friendly_name] = cover
table.insert(names, device.friendly_name)
end
for _, f in ipairs(type(expose.features) == "table" and expose.features or {}) do
-- "access" is a bit field, and bit 2 (value 4) means /get works.
local access = type(f) == "table" and f.name == "position" and tonumber(f.access)
if access and math.floor(access / 4) % 2 == 1 then
cover.canGet = true
end
end
end
end
end
end
table.sort(names)
for i = 1, COUNT do
Ctl("Discovered", i).Choices = names
Poll(Blinds[i])
end
Debug("Discovered covers:", #names)
end
local function OnMessage(topic, payload)
Debug("RX", topic, #payload > 200 and (#payload .. " bytes") or payload)
if topic == BASE .. "/bridge/state" then
local online = ParseOnline(payload)
if online ~= nil then bridgeOnline = online end
elseif topic == BASE .. "/bridge/devices" then
ParseDevices(payload)
else
local data
for i = 1, COUNT do
local b = Blinds[i]
if b.name ~= "" then
if topic == BlindTopic(b.name) then
data = data or Decode(payload)
if data then ApplyState(i, data) end
elseif topic == BlindTopic(b.name) .. "/availability" then
b.available = ParseOnline(payload)
end
end
end
end
UpdateStatus()
end
------------------------------------------------------------------------------
-- Connection
------------------------------------------------------------------------------
local function ResetSession()
mqttUp = false
bridgeOnline = nil
subscribeRefused = false
rxChunks, rxSize, rxNeed = {}, 0, 2
PingTimer:Stop()
for i = 1, COUNT do
local b = Blinds[i]
EndHold(i)
b.available, b.gotState, b.polled = nil, false, false
SyncFader(i)
end
end
local function CloseSocket()
generation = generation + 1
local old = Socket
Socket = nil
if old then
if mqttUp and old.IsConnected then
pcall(function() old:Write(string.char(0xE0, 0)) end) -- DISCONNECT
end
pcall(function() old:Disconnect() end)
end
ResetSession()
end
-- For errors that a quick reconnect will not fix, such as a bad login.
local function FailAndRetry(message)
print(message)
CloseSocket()
lastError = message
RetryTimer:Stop()
RetryTimer:Start(RETRY_DELAY)
UpdateStatus()
end
local CONNACK_ERRORS = {
[1] = "Broker does not support MQTT 3.1.1",
[2] = "Broker rejected the client ID - enter a unique Client ID",
[3] = "Broker unavailable",
[4] = "Bad username or password",
[5] = "Not authorized - check username and password",
}
local function OnPacket(header, body)
local kind = math.floor(header / 16)
if kind == 2 then -- CONNACK
local code = body:byte(2)
if code ~= 0 then
FailAndRetry(CONNACK_ERRORS[code] or ("Broker refused connection, code " .. tostring(code)))
return
end
mqttUp, lastError = true, nil
PingTimer:Start(PING_INTERVAL)
Subscribe(BASE .. "/bridge/state")
Subscribe(BASE .. "/bridge/devices")
local done = {}
for i = 1, COUNT do
local name = Blinds[i].name
if not done[name] then
done[name] = true
SubscribeBlind(name)
end
end
UpdateStatus()
elseif kind == 3 and mqttUp then -- PUBLISH
if #body < 2 then return end
local topicLen = body:byte(1) * 256 + body:byte(2)
local pos = 3 + topicLen
local qos = math.floor(header / 2) % 4
if qos > 0 then -- not expected, because we only subscribe at QoS 0
local id = body:sub(pos, pos + 1)
pos = pos + 2
if qos == 1 then Send(Packet(0x40, id)) end
end
OnMessage(body:sub(3, 2 + topicLen), body:sub(pos))
elseif kind == 9 then -- SUBACK
if body:byte(3) == 0x80 then
subscribeRefused = true
UpdateStatus()
end
end
-- PINGRESP and UNSUBACK need no action. Any received data resets ReadTimeout.
end
-- Returns the total packet size and the body offset, or nil if the header is
-- incomplete. The third value is true if the length field is invalid.
local function PacketSize(buf)
local len, mult = 0, 1
for i = 2, 5 do
local byte = buf:byte(i)
if not byte then return nil end
len = len + (byte % 128) * mult
if byte < 128 then return i + len, i + 1 end
mult = mult * 128
end
return nil, nil, true
end
-- Chunks are only joined once a full packet has arrived. The device list can
-- be large, and joining on every read would be slow.
local function OnData(data)
table.insert(rxChunks, data)
rxSize = rxSize + #data
if rxSize < rxNeed then return end
local buf = table.concat(rxChunks)
local gen = generation
local start = 1
rxNeed = 2
while true do
local head = buf:sub(start, start + 4)
local size, bodyAt, bad = PacketSize(head)
if bad or (size and size > MAX_PACKET) then
FailAndRetry("Invalid or oversized data from broker - check address and port")
return
end
if not size then
rxNeed = #head + 1
break
end
if #buf - start + 1 < size then
rxNeed = size
break
end
local body = buf:sub(start + bodyAt - 1, start + size - 1)
start = start + size
OnPacket(head:byte(1), body)
if gen ~= generation then return end -- the connection was closed
end
local rest = buf:sub(start)
rxChunks, rxSize = { rest }, #rest
end
local function Connect()
RetryTimer:Stop()
CloseSocket()
lastError = nil
local address = Trim(Controls.BrokerAddress.String)
if not Controls.Enable.Boolean then
UpdateStatus()
return
end
if address == "" then
lastError = "Enter the broker address"
UpdateStatus()
return
end
if BASE == "" or BASE:find("[+#]") then
lastError = "Invalid Base Topic property"
UpdateStatus()
return
end
local gen = generation
Socket = TcpSocket.New()
Socket.ReadTimeout = READ_TIMEOUT
Socket.WriteTimeout = 10
Socket.ReconnectTimeout = 5 -- TcpSocket reconnects by itself
Socket.EventHandler = function(sock, event, err)
if gen ~= generation then return end
if event == TcpSocket.Events.Connected then
Debug("TCP connected")
ResetSession()
SendConnect()
elseif event == TcpSocket.Events.Data then
local length = sock.BufferLength
if length > 0 then
local data = sock:Read(length)
if data and #data > 0 then OnData(data) end
end
return
elseif event == TcpSocket.Events.Reconnect then
Debug("TCP reconnecting")
return
else -- Closed, Error or Timeout
ResetSession()
if event == TcpSocket.Events.Timeout then
lastError = "Connection timed out - retrying"
elseif event == TcpSocket.Events.Closed then
lastError = "Connection closed by broker - retrying"
else
local detail = err and err ~= "" and (": " .. tostring(err)) or ""
lastError = "Connection failed" .. detail .. " - retrying"
end
Debug(lastError)
end
UpdateStatus()
end
UpdateStatus()
Socket:Connect(address, math.floor(Controls.BrokerPort.Value))
end
------------------------------------------------------------------------------
-- Startup
------------------------------------------------------------------------------
PingTimer.EventHandler = function()
Send(string.char(0xC0, 0)) -- PINGREQ
end
RetryTimer.EventHandler = function()
RetryTimer:Stop()
Connect()
end
for i = 1, COUNT do
local b = {
name = "", pending = false,
debounce = Timer.New(), hold = Timer.New(),
}
Blinds[i] = b
b.debounce.EventHandler = function() SendPosition(i) end
b.hold.EventHandler = function()
b.hold:Stop()
b.target = nil
SyncFader(i) -- the blind never reached its target, so show where it is
end
local name = Trim(Ctl("BlindName", i).String)
if ValidName(name) then b.name = name end
ClearFeedback(i)
Ctl("BlindName", i).EventHandler = function(c) SetBlindName(i, c.String) end
Ctl("Discovered", i).EventHandler = function(c)
if c.String ~= "" then SetBlindName(i, c.String) end
end
Ctl("Open", i).EventHandler = function() Command(i, "OPEN") end
Ctl("Stop", i).EventHandler = function() Command(i, "STOP") end
Ctl("Close", i).EventHandler = function() Command(i, "CLOSE") end
Ctl("Position", i).EventHandler = function()
b.pending = true
b.debounce:Stop()
b.debounce:Start(POSITION_DEBOUNCE)
end
end
Controls.AllOpen.EventHandler = function() CommandAll("OPEN") end
Controls.AllStop.EventHandler = function() CommandAll("STOP") end
Controls.AllClose.EventHandler = function() CommandAll("CLOSE") end
for _, name in ipairs({ "BrokerAddress", "BrokerPort", "Username", "Password", "ClientId", "Enable" }) do
Controls[name].EventHandler = Connect
end
Connect()
end