1 contributor
module.exports = function(RED) {
function Z2MSNZB04PNode(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 = normalizeToken(config.accessory || config.mqttSensor || "");
node.sensorUsage = normalizeToken(config.sensorUsage || "door-window");
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,
contact: false,
battery: false,
secondaryContact: false
};
node.sensorState = {
active: false,
site: node.site || "",
location: node.location || "",
deviceId: node.accessory || "",
contactKnown: false,
contact: true,
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 normalizeToken(value) {
if (value === undefined || value === null) return "";
return String(value).trim();
}
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 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 clearBootstrapTimer() {
if (!node.bootstrapTimer) return;
clearTimeout(node.bootstrapTimer);
node.bootstrapTimer = null;
}
function makeHomeKitMsg(baseMsg, payload) {
var out = RED.util.cloneMessage(baseMsg || {});
out.payload = payload;
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 || "?";
var usage = node.sensorUsage === "contact"
? "contact"
: (node.sensorUsage === "dual-contact" ? "dual-contact" : "door/window");
return [prefix || state, usage, 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 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 buildContactMsg(baseMsg) {
if (!node.sensorState.contactKnown) return null;
var payload = buildStatusFields();
payload.ContactSensorState = node.sensorState.contact ? 0 : 1;
if (!shouldPublish("hk:contact", payload)) return null;
node.stats.hk_updates += 1;
return makeHomeKitMsg(baseMsg, payload);
}
function buildSecondaryContactMsg(baseMsg) {
if (node.sensorUsage !== "dual-contact") return null;
if (!node.sensorState.tamperedKnown) return null;
var payload = buildStatusFields();
payload.ContactSensorState = node.sensorState.tampered ? 0 : 1;
if (!shouldPublish("hk:secondary-contact", 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 = {
StatusLowBattery: node.sensorState.batteryLow ? 1 : 0,
BatteryLevel: batteryLevel,
ChargingState: 2
};
if (!shouldPublish("hk:battery", payload)) return null;
node.stats.hk_updates += 1;
return makeHomeKitMsg(baseMsg, payload);
}
function clearSnapshotCache() {
delete node.hkCache["hk:contact"];
delete node.hkCache["hk:battery"];
delete node.hkCache["hk:secondary-contact"];
}
function buildBootstrapOutputs(baseMsg) {
clearSnapshotCache();
return [buildContactMsg(baseMsg), buildSecondaryContactMsg(baseMsg), buildBatteryMsg(baseMsg)];
}
function unsubscribeLast(reason) {
if (!node.subscriptionState.lastSubscribed) return null;
node.subscriptionState.lastSubscribed = false;
node.stats.controls += 1;
return buildUnsubscribeLastMsg(reason);
}
function markBootstrapSatisfied(capability) {
if (capability === "contact" && node.sensorState.contactKnown) {
node.bootstrapState.contact = true;
} else if ((capability === "battery" || capability === "battery_low") && (node.sensorState.batteryKnown || node.sensorState.batteryLowKnown)) {
node.bootstrapState.battery = true;
} else if (capability === "tamper" && node.sensorUsage === "dual-contact" && node.sensorState.tamperedKnown) {
node.bootstrapState.secondaryContact = true;
}
}
function bootstrapReady() {
if (!node.bootstrapState.contact || !node.bootstrapState.battery) return false;
if (node.sensorUsage === "dual-contact") return node.bootstrapState.secondaryContact;
return true;
}
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], outputs[2], 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, null];
node.sensorState.active = active;
node.lastMsgContext = cloneBaseMsg(baseMsg);
return [buildContactMsg(baseMsg), buildSecondaryContactMsg(baseMsg), buildBatteryMsg(baseMsg)];
}
function processCapability(baseMsg, parsed, value) {
var contactMsg = null;
var secondaryContactMsg = 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 === "contact") {
var contact = asBool(value);
if (contact === null) return [null, null, null];
node.sensorState.contactKnown = true;
node.sensorState.contact = contact;
contactMsg = buildContactMsg(baseMsg);
} else if (parsed.capability === "battery") {
var battery = asNumber(value);
if (battery === null) return [null, null, null];
node.sensorState.batteryKnown = true;
node.sensorState.battery = clamp(Math.round(battery), 0, 100);
updateBatteryLowFromThreshold();
batteryMsg = buildBatteryMsg(baseMsg);
contactMsg = buildContactMsg(baseMsg);
secondaryContactMsg = buildSecondaryContactMsg(baseMsg);
} else if (parsed.capability === "battery_low") {
var batteryLow = asBool(value);
if (batteryLow === null) return [null, null, null];
node.sensorState.batteryLowKnown = true;
node.sensorState.batteryLow = batteryLow;
batteryMsg = buildBatteryMsg(baseMsg);
contactMsg = buildContactMsg(baseMsg);
secondaryContactMsg = buildSecondaryContactMsg(baseMsg);
} else if (parsed.capability === "tamper") {
var tampered = asBool(value);
if (tampered === null) return [null, null, null];
node.sensorState.tamperedKnown = true;
node.sensorState.tampered = tampered;
contactMsg = buildContactMsg(baseMsg);
batteryMsg = buildBatteryMsg(baseMsg);
secondaryContactMsg = buildSecondaryContactMsg(baseMsg);
} else {
return [null, null, null];
}
return [contactMsg, secondaryContactMsg, 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, 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 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);
}
if (node.subscriptionState.lastSubscribed && bootstrapReady()) {
finalizeBootstrap("bootstrap-complete", send);
if (done) done();
return;
}
send([outputs[0], outputs[1], outputs[2], null]);
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-04p-homekit-adapter", Z2MSNZB04PNode);
};