"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const zigbee_herdsman_1 = require("@willieee802/zigbee-herdsman");
const exposes = __importStar(require("../lib/exposes"));
const fromZigbee_1 = __importDefault(require("../converters/fromZigbee"));
const toZigbee_1 = __importDefault(require("../converters/toZigbee"));
const constants = __importStar(require("../lib/constants"));
const reporting = __importStar(require("../lib/reporting"));
const globalStore = __importStar(require("../lib/store"));
const utils = __importStar(require("../lib/utils"));
const e = exposes.presets;
const ea = exposes.access;
const kmpcilOptions = {
    presence_timeout_dc: () => {
        return e
            .numeric("presence_timeout_dc", ea.STATE)
            .withValueMin(60)
            .withDescription("Time in seconds after which presence is cleared after detecting it (default 60 seconds) while in DC.");
    },
    presence_timeout_battery: () => {
        return e
            .numeric("presence_timeout_battery", ea.STATE)
            .withValueMin(120)
            .withDescription("Time in seconds after which presence is cleared after detecting it (default 420 seconds) while in Battery.");
    },
};
function handleKmpcilPresence(model, msg, publish, options, meta) {
    const useOptionsTimeoutBattery = options && options.hasOwnProperty("presence_timeout_battery");
    const timeoutBattery = useOptionsTimeoutBattery
        ? options.presence_timeout_battery
        : 420; // 100 seconds by default
    const useOptionsTimeoutDc = options && options.hasOwnProperty("presence_timeout_dc");
    const timeoutDc = useOptionsTimeoutDc ? options.presence_timeout_dc : 60;
    const mode = meta.state ? meta.state["power_state"] : false;
    const timeout = Number(mode ? timeoutDc : timeoutBattery);
    // Stop existing timer because motion is detected and set a new one.
    clearTimeout(globalStore.getValue(msg.endpoint, "timer"));
    const timer = setTimeout(() => publish({ presence: false }), timeout * 1000);
    globalStore.putValue(msg.endpoint, "timer", timer);
    return { presence: true };
}
const kmpcilConverters = {
    presence_binary_input: {
        cluster: "genBinaryInput",
        type: ["attributeReport", "readResponse"],
        convert: (model, msg, publish, options, meta) => {
            const payload = handleKmpcilPresence(model, msg, publish, options, meta);
            if (msg.data.hasOwnProperty("presentValue")) {
                const presentValue = msg.data["presentValue"];
                payload.power_state = (presentValue & 0x01) > 0;
                payload.occupancy = (presentValue & 0x04) > 0;
                payload.vibration = (presentValue & 0x02) > 0;
            }
            return payload;
        },
    },
    presence_power: {
        cluster: "genPowerCfg",
        type: ["attributeReport", "readResponse"],
        options: [
            kmpcilOptions.presence_timeout_dc(),
            kmpcilOptions.presence_timeout_battery(),
        ],
        convert: (model, msg, publish, options, meta) => {
            const payload = handleKmpcilPresence(model, msg, publish, options, meta);
            if (msg.data.hasOwnProperty("batteryVoltage")) {
                payload.voltage = msg.data["batteryVoltage"] * 100;
                if (model.meta &&
                    model.meta.battery &&
                    model.meta.battery.voltageToPercentage) {
                    // @ts-expect-error
                    payload.battery = utils.batteryVoltageToPercentage(payload.voltage, model.meta.battery.voltageToPercentage);
                }
            }
            return payload;
        },
    },
};
const definitions = [
    {
        zigbeeModel: ["RES005"],
        model: "KMPCIL_RES005",
        vendor: "KMPCIL",
        description: "Environment sensor",
        exposes: [
            e.battery(),
            e.temperature(),
            e.humidity(),
            e.pressure(),
            e.illuminance().withAccess(ea.STATE_GET),
            e.illuminance_lux().withAccess(ea.STATE_GET),
            e.occupancy(),
            e.switch(),
        ],
        fromZigbee: [
            fromZigbee_1.default.battery,
            fromZigbee_1.default.temperature,
            fromZigbee_1.default.humidity,
            fromZigbee_1.default.pressure,
            fromZigbee_1.default.illuminance,
            fromZigbee_1.default.kmpcil_res005_occupancy,
            fromZigbee_1.default.kmpcil_res005_on_off,
        ],
        toZigbee: [toZigbee_1.default.kmpcil_res005_on_off, toZigbee_1.default.illuminance],
        configure: async (device, coordinatorEndpoint) => {
            const endpoint = device.getEndpoint(8);
            const binds = [
                "genPowerCfg",
                "msTemperatureMeasurement",
                "msRelativeHumidity",
                "msPressureMeasurement",
                "msIlluminanceMeasurement",
                "genBinaryInput",
                "genBinaryOutput",
            ];
            await reporting.bind(endpoint, coordinatorEndpoint, binds);
            await reporting.temperature(endpoint);
            await reporting.humidity(endpoint);
            const payloadBattery = [
                {
                    attribute: "batteryPercentageRemaining",
                    minimumReportInterval: 1,
                    maximumReportInterval: 120,
                    reportableChange: 1,
                },
            ];
            await endpoint.configureReporting("genPowerCfg", payloadBattery);
            const payload = [
                {
                    attribute: "measuredValue",
                    minimumReportInterval: 5,
                    maximumReportInterval: constants.repInterval.HOUR,
                    reportableChange: 200,
                },
            ];
            await endpoint.configureReporting("msIlluminanceMeasurement", payload);
            const payloadPressure = [
                {
                    // 0 = measuredValue, override dataType from int16 to uint16
                    // https://github.com/Koenkk/zigbee-herdsman/pull/191/files?file-filters%5B%5D=.ts#r456569398
                    attribute: { ID: 0, type: zigbee_herdsman_1.Zcl.DataType.UINT16 },
                    minimumReportInterval: 2,
                    maximumReportInterval: constants.repInterval.HOUR,
                    reportableChange: 3,
                },
            ];
            await endpoint.configureReporting("msPressureMeasurement", payloadPressure);
            const options = { disableDefaultResponse: true };
            await endpoint.write("genBinaryInput", { 0x0051: { value: 0x01, type: 0x10 } }, options);
            await endpoint.write("genBinaryInput", { 0x0101: { value: 25, type: 0x23 } }, options);
            const payloadBinaryInput = [
                {
                    attribute: "presentValue",
                    minimumReportInterval: 0,
                    maximumReportInterval: 30,
                    reportableChange: 1,
                },
            ];
            await endpoint.configureReporting("genBinaryInput", payloadBinaryInput);
            await endpoint.write("genBinaryOutput", { 0x0051: { value: 0x01, type: 0x10 } }, options);
            const payloadBinaryOutput = [
                {
                    attribute: "presentValue",
                    minimumReportInterval: 0,
                    maximumReportInterval: 30,
                    reportableChange: 1,
                },
            ];
            await endpoint.configureReporting("genBinaryOutput", payloadBinaryOutput);
        },
    },
    {
        zigbeeModel: ["tagv1"],
        model: "KMPCIL-tag-001",
        vendor: "KMPCIL",
        description: "Arrival sensor",
        fromZigbee: [
            kmpcilConverters.presence_binary_input,
            kmpcilConverters.presence_power,
            fromZigbee_1.default.temperature,
        ],
        exposes: [
            e.battery(),
            e.presence(),
            e.binary("power_state", exposes.access.STATE, true, false),
            e.occupancy(),
            e.vibration(),
            e.temperature(),
        ],
        toZigbee: [],
        meta: { battery: { voltageToPercentage: "3V_1500_2800" } },
        configure: async (device, coordinatorEndpoint) => {
            const endpoint = device.getEndpoint(1);
            for (const cluster of [
                "msTemperatureMeasurement",
                "genPowerCfg",
                "genBinaryInput",
            ]) {
                // This sleep here(and the sleep) after is to allow the command to be
                // fully sent to coordinator.  In case repeater involved and the repeater
                // is litted in resources,  we may want to give some time so that the sequence of
                // commands does not overwhelm the repeater.
                await utils.sleep(2000);
                await endpoint.bind(cluster, coordinatorEndpoint);
            }
            await utils.sleep(1000);
            const p = reporting.payload("batteryVoltage", 0, 10, 1);
            await endpoint.configureReporting("genPowerCfg", p);
            await utils.sleep(1000);
            const p2 = reporting.payload("presentValue", 0, 300, 1);
            await endpoint.configureReporting("genBinaryInput", p2);
            await utils.sleep(1000);
            await reporting.temperature(endpoint);
            await endpoint.read("genBinaryInput", ["presentValue"]);
        },
    },
];
exports.default = definitions;
module.exports = definitions;
//# sourceMappingURL=kmpcil.js.map