1 contributor
module.exports = function(RED) {
function Z2MSNZB05PNode(config) {
RED.nodes.createNode(this, config);
var node = this;
node.site = normalizeToken(config.site || config.mqttSite || "");
node.location = normalizeToken(config.location || config.mqttRoom || "");
node.accessory = normalizeLegacyDeviceId(normalizeToken(config.accessory || config.mqttSensor || ""));
node.batteryLowThreshold = parseNumber(config.batteryLowThreshold, 20, 0);
node.bootstrapDeadlineMs = 10000;
node.hkCache = Object.create(null);
node.startTimer = null;
node.bootstrapTimer = null;
node.lastMsgContext = null;
node.stats = {
controls: 0,
last_inputs: 0,
value_inputs: 0,
availability_inputs: 0,
hk_updates: 0,
errors: 0
};
node.subscriptionState = {
started: false,
lastSubscribed: false,
valueSubscribed: false,
availabilitySubscribed: false
};
node.bootstrapState = {
finalized: false,
waterLeak: false,
battery: false
};
node.sensorState = {
active: false,
site: node.site || "",
location: node.location || "",
deviceId: node.accessory || "",
leakKnown: false,
leak: false,
batteryKnown: false,
battery: null,
batteryLowKnown: false,
batteryLow: false,
tamperedKnown: false,
tampered: false
};
function parseNumber(value, fallback, min) {
var n = Number(value);
if (!Number.isFinite(n)) return fallback;
if (typeof min === "number" && n < min) return fallback;
return n;
}
function asBool(value) {
if (typeof value === "boolean") return value;
if (typeof value === "number") return value !== 0;
if (typeof value === "string") {
var v = value.trim().toLowerCase();
if (v === "true" || v === "1" || v === "on" || v === "yes" || v === "online") return true;
if (v === "false" || v === "0" || v === "off" || v === "no" || v === "offline") return false;
}
return null;
}
function asNumber(value) {
if (typeof value === "number" && isFinite(value)) return value;
if (typeof value === "string") {
var trimmed = value.trim();
if (!trimmed) return null;
var parsed = Number(trimmed);
if (isFinite(parsed)) return parsed;
}
return null;
}
function clamp(n, min, max) {
return Math.max(min, Math.min(max, n));
}
function normalizeToken(value) {
if (value === undefined || value === null) return "";
return String(value).trim();
}
function normalizeLegacyDeviceId(value) {
return value;
}
function signature(value) {
return JSON.stringify(value);
}
function shouldPublish(cacheKey, payload) {
var sig = signature(payload);
if (node.hkCache[cacheKey] === sig) return false;
node.hkCache[cacheKey] = sig;
return true;
}
function cloneBaseMsg(msg) {
if (!msg || typeof msg !== "object") return {};
var out = {};
if (typeof msg.topic === "string") out.topic = msg.topic;
if (msg._msgid) out._msgid = msg._msgid;
return out;
}
function buildSubscriptionTopic(stream) {
return [
node.site,
"home",
node.location,
"+",
node.accessory,
stream
].join("/");
}
function buildSubscribeMsgs() {
return [
{
action: "subscribe",
topic: buildSubscriptionTopic("last"),
qos: 2,
rh: 0,
rap: true
},
{
action: "subscribe",
topic: buildSubscriptionTopic("value"),
qos: 2,
rh: 0,
rap: true
},
{
action: "subscribe",
topic: buildSubscriptionTopic("availability"),
qos: 2,
rh: 0,
rap: true
}
];
}
function buildUnsubscribeLastMsg(reason) {
return {
action: "unsubscribe",
topic: buildSubscriptionTopic("last"),
reason: reason
};
}
function statusText(prefix) {
var state = node.subscriptionState.lastSubscribed ? "cold" : (node.subscriptionState.started ? "live" : "idle");
var device = node.sensorState.deviceId || node.accessory || "?";
return [
prefix || state,
device,
"l:" + node.stats.last_inputs,
"v:" + node.stats.value_inputs,
"a:" + node.stats.availability_inputs,
"hk:" + node.stats.hk_updates
].join(" ");
}
function setNodeStatus(prefix, fill, shape) {
node.status({
fill: fill || (node.stats.errors ? "red" : (node.subscriptionState.lastSubscribed ? "yellow" : (node.sensorState.active ? "green" : "yellow"))),
shape: shape || "dot",
text: statusText(prefix)
});
}
function noteError(text, msg) {
node.stats.errors += 1;
node.warn(text);
node.status({ fill: "red", shape: "ring", text: text });
if (msg) node.debug(msg);
}
function makeHomeKitMsg(baseMsg, payload) {
var out = RED.util.cloneMessage(baseMsg || {});
out.payload = payload;
return out;
}
function clearBootstrapTimer() {
if (!node.bootstrapTimer) return;
clearTimeout(node.bootstrapTimer);
node.bootstrapTimer = null;
}
function buildStatusFields() {
return {
StatusActive: !!node.sensorState.active,
StatusFault: node.sensorState.active ? 0 : 1,
StatusLowBattery: node.sensorState.batteryLow ? 1 : 0,
StatusTampered: node.sensorState.tampered ? 1 : 0
};
}
function buildLeakMsg(baseMsg) {
if (!node.sensorState.leakKnown) return null;
var payload = buildStatusFields();
payload.LeakDetected = node.sensorState.leak ? 1 : 0;
if (!shouldPublish("hk:leak", payload)) return null;
node.stats.hk_updates += 1;
return makeHomeKitMsg(baseMsg, payload);
}
function buildBatteryMsg(baseMsg) {
if (!node.sensorState.batteryKnown && !node.sensorState.batteryLowKnown) return null;
var batteryLevel = node.sensorState.batteryKnown
? clamp(Math.round(Number(node.sensorState.battery)), 0, 100)
: (node.sensorState.batteryLow ? 1 : 100);
var payload = {
ChargingState: 2,
BatteryLevel: batteryLevel,
StatusLowBattery: node.sensorState.batteryLow ? 1 : 0
};
if (!shouldPublish("hk:battery", payload)) return null;
node.stats.hk_updates += 1;
return makeHomeKitMsg(baseMsg, payload);
}
function clearSnapshotCache() {
delete node.hkCache["hk:leak"];
delete node.hkCache["hk:battery"];
}
function buildBootstrapOutputs(baseMsg) {
clearSnapshotCache();
return [
buildLeakMsg(baseMsg),
buildBatteryMsg(baseMsg)
];
}
function unsubscribeLast(reason, send) {
if (!node.subscriptionState.lastSubscribed) return null;
node.subscriptionState.lastSubscribed = false;
node.stats.controls += 1;
var controlMsg = buildUnsubscribeLastMsg(reason);
if (typeof send === "function") {
send([null, null, controlMsg]);
}
return controlMsg;
}
function markBootstrapSatisfied(capability) {
if (capability === "water_leak" && node.sensorState.leakKnown) {
node.bootstrapState.waterLeak = true;
} else if ((capability === "battery" || capability === "battery_low") && (node.sensorState.batteryKnown || node.sensorState.batteryLowKnown)) {
node.bootstrapState.battery = true;
}
}
function isBootstrapComplete() {
return node.bootstrapState.waterLeak && node.bootstrapState.battery;
}
function finalizeBootstrap(reason, send) {
if (node.bootstrapState.finalized) return false;
if (!node.subscriptionState.lastSubscribed) return false;
node.bootstrapState.finalized = true;
clearBootstrapTimer();
send = send || function(msgs) { node.send(msgs); };
var outputs = buildBootstrapOutputs(cloneBaseMsg(node.lastMsgContext));
var controlMsg = unsubscribeLast(reason);
send([outputs[0], outputs[1], controlMsg]);
setNodeStatus("live");
return true;
}
function parseTopic(topic) {
if (typeof topic !== "string") return null;
var tokens = topic.split("/").map(function(token) {
return token.trim();
}).filter(function(token) {
return !!token;
});
if (tokens.length !== 6) return null;
if (tokens[1] !== "home") return null;
if (tokens[5] !== "value" && tokens[5] !== "last" && tokens[5] !== "availability") {
return { ignored: true };
}
if ((node.site && tokens[0] !== node.site) || (node.location && tokens[2] !== node.location) || (node.accessory && tokens[4] !== node.accessory)) {
return { ignored: true };
}
return {
site: tokens[0],
location: tokens[2],
capability: tokens[3],
deviceId: tokens[4],
stream: tokens[5]
};
}
function extractValue(stream, payload) {
if (stream === "last" && payload && typeof payload === "object" && !Array.isArray(payload) && Object.prototype.hasOwnProperty.call(payload, "value")) {
return payload.value;
}
return payload;
}
function updateBatteryLowFromThreshold() {
if (!node.sensorState.batteryKnown || node.sensorState.batteryLowKnown) return;
node.sensorState.batteryLow = Number(node.sensorState.battery) <= node.batteryLowThreshold;
}
function processAvailability(baseMsg, value) {
var active = asBool(value);
if (active === null) return [null, null];
node.sensorState.active = active;
node.lastMsgContext = cloneBaseMsg(baseMsg);
return [
buildLeakMsg(baseMsg),
buildBatteryMsg(baseMsg)
];
}
function processCapability(baseMsg, parsed, value) {
var leakMsg = null;
var batteryMsg = null;
node.sensorState.active = true;
node.sensorState.site = parsed.site;
node.sensorState.location = parsed.location;
node.sensorState.deviceId = parsed.deviceId;
node.lastMsgContext = cloneBaseMsg(baseMsg);
if (parsed.capability === "water_leak") {
var leak = asBool(value);
if (leak === null) return [null, null];
node.sensorState.leakKnown = true;
node.sensorState.leak = leak;
leakMsg = buildLeakMsg(baseMsg);
} else if (parsed.capability === "battery") {
var battery = asNumber(value);
if (battery === null) return [null, null];
node.sensorState.batteryKnown = true;
node.sensorState.battery = clamp(Math.round(battery), 0, 100);
updateBatteryLowFromThreshold();
batteryMsg = buildBatteryMsg(baseMsg);
leakMsg = buildLeakMsg(baseMsg);
} else if (parsed.capability === "battery_low") {
var batteryLow = asBool(value);
if (batteryLow === null) return [null, null];
node.sensorState.batteryLowKnown = true;
node.sensorState.batteryLow = batteryLow;
batteryMsg = buildBatteryMsg(baseMsg);
leakMsg = buildLeakMsg(baseMsg);
} else if (parsed.capability === "tamper") {
var tampered = asBool(value);
if (tampered === null) return [null, null];
node.sensorState.tamperedKnown = true;
node.sensorState.tampered = tampered;
leakMsg = buildLeakMsg(baseMsg);
batteryMsg = buildBatteryMsg(baseMsg);
} else {
return [null, null];
}
return [leakMsg, batteryMsg];
}
function startSubscriptions() {
if (node.subscriptionState.started) return;
if (!node.site || !node.location || !node.accessory) {
noteError("missing site, location or accessory");
return;
}
node.subscriptionState.started = true;
node.subscriptionState.lastSubscribed = true;
node.subscriptionState.valueSubscribed = true;
node.subscriptionState.availabilitySubscribed = true;
clearBootstrapTimer();
node.bootstrapTimer = setTimeout(function() {
finalizeBootstrap("bootstrap-timeout");
}, node.bootstrapDeadlineMs);
node.stats.controls += 1;
node.send([null, null, buildSubscribeMsgs()]);
setNodeStatus("cold");
}
node.on("input", function(msg, send, done) {
send = send || function() { node.send.apply(node, arguments); };
try {
var parsed = parseTopic(msg && msg.topic);
if (!parsed) {
noteError("invalid topic");
if (done) done();
return;
}
if (parsed.ignored) {
if (done) done();
return;
}
var value = extractValue(parsed.stream, msg.payload);
var controlMsg = null;
var outputs;
if (parsed.stream === "last") {
node.stats.last_inputs += 1;
outputs = processCapability(msg, parsed, value);
markBootstrapSatisfied(parsed.capability);
} else if (parsed.stream === "value") {
node.stats.value_inputs += 1;
outputs = processCapability(msg, parsed, value);
markBootstrapSatisfied(parsed.capability);
} else {
node.stats.availability_inputs += 1;
outputs = processAvailability(msg, value);
}
send([
outputs[0],
outputs[1],
controlMsg
]);
setNodeStatus();
if (done) done();
} catch (err) {
node.stats.errors += 1;
node.status({ fill: "red", shape: "ring", text: "error: " + err.message });
if (done) done(err);
else node.error(err, msg);
}
});
node.on("close", function() {
clearBootstrapTimer();
if (node.startTimer) {
clearTimeout(node.startTimer);
node.startTimer = null;
}
});
node.startTimer = setTimeout(startSubscriptions, 250);
node.status({ fill: "grey", shape: "ring", text: "starting" });
}
RED.nodes.registerType("snzb-05p-homekit-adapter", Z2MSNZB05PNode);
};