import asyncdispatch, strutils, json, tables, options, times import ../types, ../vars, ../utils import nmqtt proc setZigbee2MqttLampState* (deviceName: string, value: bool) {.async.} = let config = server.config.devices[deviceName] var sendState = "OFF" if config.type != Zigbee2MqttLamp: return if value == true: sendState = "ON" await mqttContext.publish("zigbee2mqtt/" & config.deviceName.get & "/set", "{\"state\": \"" & sendState & "\"}") proc toggleZigbee2MqttLampState* (deviceName: string) {.async.} = let config = server.config.devices[deviceName] if config.type != Zigbee2MqttLamp: return await mqttContext.publish("zigbee2mqtt/" & config.deviceName.get & "/set", "{\"state\": \"TOGGLE\"}") proc setZigbee2MqttLampBrightness* (deviceName: string, brightness: uint8) {.async.} = let config = server.config.devices[deviceName] if config.type != Zigbee2MqttLamp: return await mqttContext.publish("zigbee2mqtt/" & config.deviceName.get & "/set", "{\"brightness\": \"" & $brightness & "\"}") proc setZigbee2MqttLampColor* (deviceName: string, colorX: float, colorY: float) {.async.} = let config = server.config.devices[deviceName] if config.type != Zigbee2MqttLamp: return await mqttContext.publish("zigbee2mqtt/" & config.deviceName.get & "/set", "{\"color\": {\"X\": \"" & $colorX & "\", \"Y\": \"" & $colorY & "\"}}") proc setZigbee2MqttLampColorTemperature* (deviceName: string, colorTemperature: int) {.async.} = let config = server.config.devices[deviceName] if config.type != Zigbee2MqttLamp: return await mqttContext.publish("zigbee2mqtt/" & config.deviceName.get & "/set", "{\"color_temp\": \"" & $colorTemperature & "\"}") proc updateLamp (topic: string, message: string) = try: let deviceName = zigbee2mqttDevices[topic] let recivedData = parseJson(message) server.state[deviceName].lastUpdated = some(toUnix(getTime())) if recivedData.hasKey("linkquality"): server.state[deviceName].lampLinkquality = recivedData["linkquality"].getInt if recivedData.hasKey("state"): if recivedData["state"].getStr != "ON": server.state[deviceName].lampState = false else: server.state[deviceName].lampState = true if recivedData.hasKey("brightness"): server.state[deviceName].lampBrightness = recivedData["brightness"].getInt if recivedData.hasKey("color"): server.state[deviceName].lampColorX = recivedData["color"]["x"].getFloat server.state[deviceName].lampColorY = recivedData["color"]["y"].getFloat if recivedData.hasKey("color_temp"): server.state[deviceName].lampColorTemperature = recivedData["color_temp"].getInt broadcastServerState() except: echo "Error[updateLamp]:\n", getCurrentExceptionMsg() proc initZigbee2MqttLamps* () {.async.} = for key, device in server.config.devices.pairs(): if device.type != Zigbee2MqttLamp: continue zigbee2mqttDevices["zigbee2mqtt/" & device.deviceName.get] = key server.state[key] = DeviceState(type: Zigbee2MqttLamp, lampType: device.lampType) await mqttContext.subscribe("zigbee2mqtt/" & device.deviceName.get, 2, updateLamp)