Files
Zway-Bot/Zway-Bot/Moduls/Mqtt.cs
T
2022-01-16 22:36:43 +01:00

85 lines
3.3 KiB
C#

using System;
using System.Text.RegularExpressions;
using BlubbFish.IoT.Zway;
using BlubbFish.IoT.Zway.Events;
using BlubbFish.IoT.Zway.Interfaces;
using BlubbFish.Utils;
using BlubbFish.Utils.IoT.Bots.Events;
using BlubbFish.Utils.IoT.Bots.Moduls;
using BlubbFish.Utils.IoT.Connector;
using BlubbFish.Utils.IoT.Events;
using BlubbFish.Utils.IoT.Interfaces;
using LitJson;
namespace BlubbFish.IoT.Bots.ZwayBot.Moduls {
class Mqtt : Mqtt<ZwayController> {
public override event ModulEvent Update;
public Mqtt(ZwayController lib, InIReader settings) : base(lib, settings) { }
public override void EventLibSetter() => this.library.Recieved += this.HandleLibUpdate;
protected override void LibUpadteThread(Object state) {
try {
if(this.mqtt.IsConnected) {
DeviceUpdateEvent e = state as DeviceUpdateEvent;
if(e.Parent.GetType().HasInterface(typeof(IMqtt))) {
IMqtt sensor = e.Parent as IMqtt;
((ADataBackend)this.mqtt).Send("zwavebot/devices/" + sensor.MqttTopic(), sensor.ToJson());
this.Update?.Invoke(this, new MqttEvent("zwavebot/devices/" + sensor.MqttTopic(), sensor.ToJson()));
}
}
} catch (Exception e) {
Helper.WriteError("BlubbFish.IoT.Bots.ZwayBot.Moduls.Mqtt.LibUpadteThread: " + e.Message);
}
}
#region Events
protected virtual void MqttUpdate(Object sender, BackendEvent e) {
try {
if (this.mqtt.IsConnected) {
if (e.From.ToString().StartsWith("zwavebot/devices/") && (e.From.ToString().EndsWith("/set") || e.From.ToString().EndsWith("/get"))) {
Match m = new Regex("^zwavebot/devices/(\\d+)/(\\d+)/(\\d+)/[gs]et$|^zwavebot/devices/(\\d+)/(\\d+)/(\\d+)/(\\d+)/[gs]et$").Match(e.From.ToString());
String id = "";
if (m.Groups[1].Success) {
id = m.Groups[1].Value + "-" + m.Groups[2].Value + "-" + m.Groups[3].Value;
}
if (m.Groups[4].Success) {
id = m.Groups[4].Value + "-" + m.Groups[5].Value + "-" + m.Groups[6].Value + "-" + m.Groups[7].Value;
}
ACommandClass c = this.library.GetCommandClass(id);
if (c == null) {
return;
}
if (e.From.ToString().EndsWith("/set")) {
try {
JsonData a = JsonMapper.ToObject(e.Message);
foreach (String item in a.Keys) {
String key = item.ToUpperLower();
if (c.HasProperty(key)) {
c.SetProperty(key, a[item].ToString());
this.Update?.Invoke(this, new MqttEvent(c.Id, a[item].ToString()));
}
}
} catch (Exception) { }
} else if (e.From.ToString().EndsWith("/get")) {
c.PollOnce = true;
((ADataBackend)this.mqtt).Send("zwavebot/devices/" + c.MqttTopic(), c.ToJson());
this.Update?.Invoke(this, new MqttEvent(e.From.ToString(), "Dataget"));
}
}
Tuple<Boolean, MqttEvent> cs = this.ChangeConfig(e, "zwavebot/config/");
if (cs.Item1) {
this.Update?.Invoke(this, cs.Item2);
}
}
} catch { }
}
#endregion
}
}