Zway-Bot/Zway-Bot/Moduls/Mqtt.cs
2018-08-02 21:49:22 +00:00

94 lines
3.4 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;
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 zwave, InIReader settings) : base(zwave, settings) { }
#region Mqtt
protected override void Connect() {
this.mqtt = ABackend.GetInstance(this.config["settings"], ABackend.BackendType.Data);
this.mqtt.MessageIncomming += this.EventInput;
this.library.Update += this.EventOutput;
}
protected override void Disconnect() {
if (this.mqtt != null) {
this.mqtt.MessageIncomming -= this.EventInput;
}
this.library.Update -= this.EventOutput;
if (this.mqtt != null) {
this.mqtt.Dispose();
}
this.mqtt = null;
}
#endregion
#region Events
protected virtual void EventOutput(Object sender, DeviceUpdateEvent e) {
String topic = "";
String data = "";
if (e.Parent.GetType().HasInterface(typeof(IMqtt))) {
IMqtt sensor = (IMqtt)e.Parent;
topic = "zwavebot/devices/" + sensor.MqttTopic();
data = sensor.ToJson();
}
if (topic != "" && data != "") {
((ADataBackend)this.mqtt).Send(topic, data);
this.Update?.Invoke(this, new MqttEvent(topic, data));
}
}
protected virtual void EventInput(Object sender, BackendEvent e) {
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);
}
}
#endregion
}
}