-- APC switched Rack PDU plugin for Q-SYS -- For PDUs running APC's "rpdu2g" firmware (written for the AP7920B, 8 outlets). -- -- Transport: one interactive SSH session to the PDU's command line. Commands run one at a -- time; a reply is complete once an "Ennn:" result line and then the "apc>" prompt arrive. -- -- Safety: outlets are only switched by a control change. Nothing is sent from saved control -- states at startup, and commands are never queued while offline or retried, because a -- command whose reply was lost may already have run. A rejected login is not retried -- automatically, so a wrong password cannot lock the account. PluginInfo = { Name = "APC~Switched Rack PDU", Version = "0.1.0", BuildVersion = "0.1.0.0", Id = "74777925-8774-4282-aa1d-98dad5659d31", Author = "qsys-plugins", Description = "APC switched Rack PDU (rpdu2g firmware, e.g. AP7920B): outlet control, names and load over SSH", } function GetColor(props) return { 60, 160, 80 } end function GetPrettyName(props) return "APC Rack PDU\n" .. PluginInfo.Version end function GetProperties() return { { Name = "Outlets", Type = "integer", Min = 1, Max = 24, Value = 8 }, -- "all", or a list such as "3" or "1,3,5-8". Anything invalid locks every outlet. { Name = "Controllable Outlets", Type = "string", Value = "all" }, { Name = "Poll Interval (s)", Type = "integer", Min = 2, Max = 60, Value = 5 }, { Name = "Debug", Type = "boolean", Value = false }, } end function GetControls(props) local c = { { Name = "IPAddress", ControlType = "Text", UserPin = true, PinStyle = "Input", Count = 1 }, { Name = "Username", ControlType = "Text", UserPin = false, Count = 1 }, { Name = "Password", ControlType = "Text", UserPin = false, Count = 1 }, { Name = "Reconnect", ControlType = "Button", ButtonType = "Trigger", UserPin = true, PinStyle = "Input", Count = 1 }, { Name = "Status", ControlType = "Indicator", IndicatorType = "Status", UserPin = true, PinStyle = "Output", Count = 1 }, { Name = "Online", ControlType = "Indicator", IndicatorType = "Led", UserPin = true, PinStyle = "Output", Count = 1 }, { Name = "Model", ControlType = "Indicator", IndicatorType = "Text", UserPin = false, Count = 1 }, { Name = "Current", ControlType = "Knob", ControlUnit = "Float", Min = 0, Max = 100, UserPin = true, PinStyle = "Output", Count = 1 }, { Name = "LastError", ControlType = "Indicator", IndicatorType = "Text", UserPin = true, PinStyle = "Output", Count = 1 }, } for i = 1, props["Outlets"].Value do local p = "Outlet" .. i c[#c + 1] = { Name = p .. "Name", ControlType = "Indicator", IndicatorType = "Text", UserPin = true, PinStyle = "Output", Count = 1 } c[#c + 1] = { Name = p .. "On", ControlType = "Button", ButtonType = "Toggle", UserPin = true, PinStyle = "Both", Count = 1 } c[#c + 1] = { Name = p .. "Reboot", ControlType = "Button", ButtonType = "Trigger", UserPin = true, PinStyle = "Input", Count = 1 } end return c end function GetControlLayout(props) local layout, graphics = {}, {} local W, ROW, LBL = 360, 22, 130 local y = 6 local outlets = props["Outlets"].Value local function box(title, rows) graphics[#graphics + 1] = { Type = "GroupBox", Text = title, Fill = { 230, 236, 242 }, 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) layout[name] = { PrettyName = pretty, Position = { x, y }, Size = { w, ROW - 4 }, Style = style } end box("Connection", 8) label("IP Address"); ctl("IPAddress", "Setup~IP Address", LBL, 150, "Text") ctl("Reconnect", "Setup~Reconnect", LBL + 160, 60, "Button"); layout["Reconnect"].Legend = "Reconnect"; y = y + ROW label("Username"); ctl("Username", "Setup~Username", LBL, 150, "Text"); y = y + ROW label("Password"); ctl("Password", "Setup~Password", LBL, 150, "Text"); y = y + ROW label("Status"); ctl("Status", "Status", LBL, 220); y = y + ROW label("Online"); ctl("Online", "Online", LBL, 18); y = y + ROW label("Model"); ctl("Model", "Info~Model", LBL, 220); y = y + ROW label("Load (A)"); ctl("Current", "Load~Current (A)", LBL, 80, "Text"); y = y + ROW label("Last error"); ctl("LastError", "Last Error", LBL, 220); y = y + ROW + 8 box("Outlets", outlets) for i = 1, outlets do local p, g = "Outlet" .. i, "Outlet " .. i .. "~" label("Outlet " .. i) ctl(p .. "Name", g .. "Name", LBL, 110) ctl(p .. "On", g .. "On", LBL + 114, 48, "Button") ctl(p .. "Reboot", g .. "Reboot", LBL + 166, 54, "Button"); layout[p .. "Reboot"].Legend = "Reboot" y = y + ROW end return layout, graphics end if Controls then local OUTLETS = Properties["Outlets"].Value local POLL_S = Properties["Poll Interval (s)"].Value local DEBUG = Properties["Debug"].Value local PORT, RECONNECT_S, LOGIN_S, REPLY_S = 22, 10, 20, 10 local function dbg(...) if DEBUG then print("[APC]", ...) end end local function trim(s) return tostring(s or ""):match("^%s*(.-)%s*$") end -- Global so the garbage collector never collects it mid-session. ApcSsh = nil local generation = 0 -- bumped on every (re)connect so stale callbacks are ignored local ready = false -- logged in and the first prompt has been seen local rx = "" local queue, current = {}, nil local known = {} -- outlet -> last state the PDU reported local inFlight = {} -- outlet -> number of commands not yet answered local reconnectTimer, pollTimer, watchdog = Timer.New(), Timer.New(), Timer.New() local function setStatus(code, text) Controls.Status.Value = code Controls.Status.String = text or "" Controls.Online.Boolean = (code == 0 or code == 1) end -- Returns a set of outlet numbers, or nil if the text is invalid. local function parseOutlets(text) text = trim(text):lower() local set = {} if text == "all" then for i = 1, OUTLETS do set[i] = true end return set end for item in (text .. ","):gmatch("([^,]*),") do item = trim(item) local a, b = item:match("^(%d+)%s*%-%s*(%d+)$") if not a then a = item:match("^%d+$"); b = a end a, b = tonumber(a or ""), tonumber(b or "") if not a or a < 1 or b > OUTLETS or a > b then return nil end for i = a, b do set[i] = true end end return set end local allowed = parseOutlets(Properties["Controllable Outlets"].Value) if not allowed then allowed = {} Controls.LastError.String = "Controllable Outlets is invalid: all outlets locked" end local function showKnown(i) Controls["Outlet" .. i .. "On"].Boolean = known[i] == true end --------------------------------------------------------------------------- -- Connection --------------------------------------------------------------------------- local function dropConnection() generation = generation + 1 ready, rx, queue, current, inFlight = false, "", {}, nil, {} pollTimer:Stop() watchdog:Stop() local s = ApcSsh ApcSsh = nil if s then pcall(function() s:Disconnect() end) end for i = 1, OUTLETS do showKnown(i) end -- undo any toggle the PDU never confirmed end local function fail(text) dbg(text) dropConnection() setStatus(4, text) reconnectTimer:Stop() reconnectTimer:Start(RECONNECT_S) end --------------------------------------------------------------------------- -- Command queue --------------------------------------------------------------------------- local function sendNext() if not ready or current or #queue == 0 then return end current = table.remove(queue, 1) rx = "" dbg("->", current.cmd) watchdog:Stop() watchdog:Start(REPLY_S) -- CR only, which is what the Enter key sends on a terminal. local ok, err = pcall(function() ApcSsh:Write(current.cmd .. "\r") end) if not ok then fail("Write failed: " .. tostring(err)) end end -- cb(ok, body, result): body is the text after the result line, e.g. result "E000: Success". local function enqueue(cmd, cb, urgent) local item = { cmd = cmd, cb = cb, urgent = urgent } if urgent then -- ahead of polls, but after earlier outlet commands local pos = 1 while queue[pos] and queue[pos].urgent do pos = pos + 1 end table.insert(queue, pos, item) else queue[#queue + 1] = item end sendNext() end local function onStatus(ok, body, result) if not ok then setStatus(1, "olStatus: " .. result) return end local found = 0 for line in body:gmatch("[^\n]+") do -- "3: BGM Amplifier: On". A "*" after the state is accepted in case one is shown. local n, name, state = line:match("^%s*(%d+):%s*(.-):%s*(%a+)%s*%*?%s*$") n, state = tonumber(n or ""), state and state:lower() if n and n >= 1 and n <= OUTLETS and (state == "on" or state == "off") then found = found + 1 Controls["Outlet" .. n .. "Name"].String = name known[n] = state == "on" -- This reply may predate a command that is still waiting. if not inFlight[n] then showKnown(n) end end end if found == OUTLETS then setStatus(0, "") else setStatus(1, string.format("PDU reported %d of %d outlets", found, OUTLETS)) end end local function onCurrent(ok, body) local amps = ok and body:match("%d+:%s*([%d%.]+)%s*A") amps = amps and tonumber(amps) if amps then Controls.Current.Value = amps end end local function poll() if current or #queue > 0 then return end enqueue("olStatus all", onStatus) enqueue("phReading 1 current", onCurrent) end local function onReady() ready = true rx = "" watchdog:Stop() dbg("logged in") enqueue("olStatus all", onStatus) enqueue("phReading 1 current", onCurrent) enqueue("prodInfo", function(ok, body) local model = ok and body:match("Model:%s*([^\n]+)") if model then Controls.Model.String = trim(model) end end) pollTimer:Start(POLL_S) end local function onData(data) rx = rx .. data local text = "\n" .. rx:gsub("\27%[[%d;?]*%a", ""):gsub("\r\n", "\n"):gsub("\r", "\n") if not text:lower():match("\n%s*apc>%s*$") then return end if not ready then onReady(); return end if not current then rx = ""; return end -- A prompt with no result line is left over from before this command: keep waiting. local result, rest = text:match("\n%s*(E%d%d%d:[^\n]*)(.*)$") if not result then return end local done = current current, rx = nil, "" watchdog:Stop() result = trim(result) local body = rest:gsub("\n[^\n]*$", "") -- drop the prompt dbg("<-", done.cmd, result) done.cb(result:sub(1, 4) == "E000", body, result) sendNext() end function Connect() reconnectTimer:Stop() dropConnection() local host = trim(Controls.IPAddress.String) local user, pass = trim(Controls.Username.String), Controls.Password.String or "" if host == "" or user == "" or pass == "" then setStatus(3, "Enter the IP address, username and password") return end setStatus(5, "Connecting to " .. host) local gen = generation local s = Ssh.New() ApcSsh = s s.IsInteractive = true s.ReconnectTimeout = 0 -- reconnects are handled here, so a bad login is not repeated local function guard(fn) return function(...) if gen == generation then fn(...) end end end s.Connected = guard(function() setStatus(5, "Waiting for the prompt") end) s.Data = guard(function(sock) local n = sock.BufferLength local data = n > 0 and sock:Read(n) if data then onData(data) end end) s.LoginFailed = guard(function() dropConnection() setStatus(2, "Login failed: check the details, then press Reconnect") end) s.Closed = guard(function() fail("Disconnected") end) s.Error = guard(function(_, err) fail("Connection error: " .. tostring(err)) end) s.Timeout = guard(function() fail("Connection timed out") end) watchdog:Start(LOGIN_S) local ok, err = pcall(function() s:Connect(host, PORT, user, pass) end) if not ok then fail("Connect failed: " .. tostring(err)) end end reconnectTimer.EventHandler = function() Connect() end pollTimer.EventHandler = poll watchdog.EventHandler = function() fail(current and ("No reply to " .. current.cmd) or "No prompt from the PDU") end --------------------------------------------------------------------------- -- Control handlers --------------------------------------------------------------------------- local function outletCommand(i, verb) local problem if not allowed[i] then problem = "locked by Controllable Outlets" elseif not ready then problem = "PDU offline, command not sent" end if problem then Controls.LastError.String = string.format("Outlet %d: %s", i, problem) showKnown(i) return end inFlight[i] = (inFlight[i] or 0) + 1 enqueue(verb .. " " .. i, function(ok, _, result) inFlight[i] = inFlight[i] > 1 and inFlight[i] - 1 or nil Controls.LastError.String = ok and "" or string.format("Outlet %d %s: %s", i, verb, result) enqueue("olStatus all", onStatus) -- show what the PDU actually did end, true) end for i = 1, OUTLETS do Controls["Outlet" .. i .. "On"].EventHandler = function(c) outletCommand(i, c.Boolean and "olOn" or "olOff") end Controls["Outlet" .. i .. "Reboot"].EventHandler = function() outletCommand(i, "olReboot") end end for _, name in ipairs({ "IPAddress", "Username", "Password", "Reconnect" }) do Controls[name].EventHandler = function() Connect() end end Connect() end