[NF] Add Bot-Utils and rewrite code

This commit is contained in:
BlubbFish 2018-06-07 20:49:54 +00:00
parent fc108773d9
commit 70bcf69b1b
23 changed files with 82 additions and 513 deletions

View File

@ -1,81 +0,0 @@
using System;
namespace ZwayBot {
public class CronEvent : ModulEventArgs {
public CronEvent() {
}
public CronEvent(String addr, String prop, String value) {
this.Address = addr;
this.Property = prop;
this.Value = value;
this.Source = "Cronjob";
}
}
public class OvertakerEvent : ModulEventArgs {
public OvertakerEvent() {
}
public OvertakerEvent(String addr, String prop, String value) {
this.Address = addr;
this.Property = prop;
this.Value = value;
this.Source = "Overtaker";
}
}
public class Flex4gridEvent : ModulEventArgs {
public Flex4gridEvent() {
}
public Flex4gridEvent(String topic, String text) {
this.Address = topic;
this.Value = text;
this.Source = "Flex4Grid";
}
public override String ToString() {
return this.Source + ": on " + this.Address + " set " + this.Value;
}
}
public class MqttEvent : ModulEventArgs {
public MqttEvent() {
}
public MqttEvent(String topic, String text) {
this.Address = topic;
this.Value = text;
this.Source = "MQTT";
}
public override String ToString() {
return this.Source + ": on " + this.Address + " set " + this.Value;
}
}
public class StatusPollingEvent : ModulEventArgs {
public StatusPollingEvent() {
}
public StatusPollingEvent(String text, String node) {
this.Value = text;
this.Address = node;
this.Source = "POLLING";
}
public override String ToString() {
return this.Source + ": " + this.Value + " on " + this.Address;
}
}
public class ModulEventArgs : EventArgs {
public ModulEventArgs() {
}
public String Address { get; protected set; }
public String Property { get; protected set; }
public String Value { get; protected set; }
public String Source { get; protected set; }
public override String ToString() {
return this.Source + ": " + this.Address + " set " + this.Property + " to " + this.Value;
}
}
}

View File

@ -1,82 +0,0 @@
using System;
using System.Reflection;
namespace ZwayBot {
static class Helper {
public static void SetProperty(this Object o, String name, String value) {
PropertyInfo prop = o.GetType().GetProperty(name);
if (prop.CanWrite) {
if (prop.PropertyType == typeof(Boolean) && Boolean.TryParse(value, out Boolean vb)) {
prop.SetValue(o, vb);
} else if (prop.PropertyType == typeof(Int32) && Int32.TryParse(value, out Int32 v32)) {
prop.SetValue(o, v32);
} else if (prop.PropertyType == typeof(Single) && Single.TryParse(value, out Single vs)) {
prop.SetValue(o, vs);
} else if (prop.PropertyType == typeof(Double) && Double.TryParse(value, out Double vd)) {
prop.SetValue(o, vd);
} else if (prop.PropertyType == typeof(Int64) && Int64.TryParse(value, out Int64 v64)) {
prop.SetValue(o, v64);
}
}
}
internal static Boolean HasProperty(this Object o, String type) {
Type t = o.GetType();
foreach (PropertyInfo item in t.GetProperties()) {
if (item.Name == type) {
return true;
}
}
return false;
}
internal static Object GetProperty(this Object o, String name) {
PropertyInfo prop = o.GetType().GetProperty(name);
if(prop.CanRead) {
return prop.GetValue(o);
}
return null;
}
internal static Boolean HasAbstract(this Object o, Type type) {
if(o.GetType().BaseType == type) {
return true;
}
return false;
}
internal static Boolean HasInterface(this Type o, String type) {
foreach (Type item in o.GetInterfaces()) {
if(item.Name == type) {
return true;
}
}
return false;
}
internal static Boolean HasInterface(this Object o, Type interf) {
foreach(Type item in o.GetType().GetInterfaces()) {
if(item == interf) {
return true;
}
}
return false;
}
internal static void WriteError(String text) {
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine("ERROR: " + text);
Console.ResetColor();
}
internal static String ToUpperLower(this String s) {
if(s.Length == 0) {
return "";
}
if(s.Length == 1) {
return s.ToUpper();
}
return s[0].ToString().ToUpper() + s.Substring(1).ToLower();
}
}
}

View File

@ -1,4 +0,0 @@
namespace ZwayBot.Interfaces {
interface IForceLoad {
}
}

View File

@ -1,71 +0,0 @@
using System;
using System.Collections.Generic;
using BlubbFish.IoT.Zway;
using BlubbFish.Utils;
namespace ZwayBot {
abstract class AModul {
protected ZwayController zw;
private readonly InIReader settings;
protected Dictionary<String, Dictionary<String, String>> config = new Dictionary<String, Dictionary<String, String>>();
public Boolean HasConfig { get; private set; }
public Boolean ConfigPublic { get; private set; }
public delegate void ModulEvent(Object sender, ModulEventArgs e);
public abstract event ModulEvent Update;
public AModul(ZwayController zway, InIReader settings) {
this.HasConfig = false;
this.ConfigPublic = false;
this.zw = zway;
this.settings = settings;
this.ParseConfig();
}
private void ParseConfig() {
if (this.settings != null) {
this.HasConfig = true;
foreach (String item in this.settings.GetSections(false)) {
this.config.Add(item, this.settings.GetSection(item));
}
if(this.config.ContainsKey("modul")) {
this.ConfigPublic = this.config["modul"].ContainsKey("config") && this.config["modul"]["config"].ToLower() == "public";
}
}
}
public Dictionary<String, Dictionary<String, String>> GetConfig() {
if (this.HasConfig && this.ConfigPublic) {
Dictionary<String, Dictionary<String, String>> ret = new Dictionary<String, Dictionary<String, String>>(this.config);
if(ret.ContainsKey("modul")) {
ret.Remove("modul");
}
return ret;
}
return new Dictionary<String, Dictionary<String, String>>();
}
public virtual void Interconnect(Dictionary<String, AModul> moduls) { }
public virtual void SetInterconnection(String param, Action<Object> hook, Object data) { }
public abstract void Dispose();
internal void SetConfig(Dictionary<String, Dictionary<String, String>> newconf) {
if (this.HasConfig && this.ConfigPublic) {
if (newconf.ContainsKey("modul")) {
newconf.Remove("modul");
}
if (this.config.ContainsKey("modul")) {
newconf.Add("modul", this.config["modul"]);
}
this.config = newconf;
this.settings.SetSections(this.config);
this.UpdateConfig();
}
}
protected abstract void UpdateConfig();
}
}

View File

@ -6,13 +6,16 @@ using System.Threading;
using BlubbFish.IoT.Zway; using BlubbFish.IoT.Zway;
using BlubbFish.IoT.Zway.Interfaces; using BlubbFish.IoT.Zway.Interfaces;
using BlubbFish.Utils; using BlubbFish.Utils;
using ZwayBot.Interfaces; using BlubbFish.Utils.IoT.Bots.Moduls;
using BlubbFish.Utils.IoT.Bots.Interfaces;
using BlubbFish.Utils.IoT.Bots.Events;
using BlubbFish.Utils.IoT.Bots;
namespace ZwayBot.Moduls { namespace ZwayBot.Moduls {
internal class CronJob : AModul, IDisposable, IForceLoad { internal class CronJob : AModul<ZwayController>, IDisposable, IForceLoad {
private DateTime crontime; private DateTime crontime;
private Thread thread; private Thread thread;
private List<Tuple<String, Action<Object>, Object>> internalCron = new List<Tuple<String, Action<Object>, Object>>(); private readonly List<Tuple<String, Action<Object>, Object>> internalCron = new List<Tuple<String, Action<Object>, Object>>();
public override event ModulEvent Update; public override event ModulEvent Update;
@ -58,7 +61,7 @@ namespace ZwayBot.Moduls {
String[] items = item.Split(':'); String[] items = item.Split(':');
if(items.Length == 2) { if(items.Length == 2) {
String[] values = items[1].Split('-'); String[] values = items[1].Split('-');
ACommandClass c = this.zw.GetCommandClass(items[0]); ACommandClass c = this.library.GetCommandClass(items[0]);
if (c != null && values.Length == 2) { if (c != null && values.Length == 2) {
if (c.HasProperty(values[0])) { if (c.HasProperty(values[0])) {
c.SetProperty(values[0], values[1]); c.SetProperty(values[0], values[1]);

View File

@ -1,89 +1,69 @@
using System; using System;
using System.Collections.Generic;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading;
using BlubbFish.IoT.Zway; using BlubbFish.IoT.Zway;
using BlubbFish.IoT.Zway.Events; using BlubbFish.IoT.Zway.Events;
using BlubbFish.IoT.Zway.Interfaces; using BlubbFish.IoT.Zway.Interfaces;
using BlubbFish.Utils; 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.Connector;
using BlubbFish.Utils.IoT.Events; using BlubbFish.Utils.IoT.Events;
using BlubbFish.Utils.IoT.Interfaces;
using LitJson; using LitJson;
namespace ZwayBot.Moduls { namespace ZwayBot.Moduls {
class Mqtt : AModul, IDisposable { class Mqtt : Mqtt<ZwayController> {
private ABackend mqtt;
private readonly Thread connectionWatcher;
private Dictionary<String, AModul> modules;
public override event ModulEvent Update; public override event ModulEvent Update;
public Mqtt(ZwayController zway, InIReader settings) : base(zway, settings) { public Mqtt(ZwayController zwave, InIReader settings) : base(zwave, settings) { }
if (this.config.ContainsKey("settings")) {
this.connectionWatcher = new Thread(this.ConnectionWatcherRunner); #region Mqtt
this.connectionWatcher.Start(); protected override void Connect() {
} this.mqtt = ABackend.GetInstance(this.config["settings"], ABackend.BackendType.Data);
this.mqtt.MessageIncomming += this.EventInput;
this.library.Update += this.EventOutput;
} }
private void ConnectionWatcherRunner() { protected override void Disconnect() {
while (true) {
try {
if (this.mqtt == null || !this.mqtt.IsConnected) {
this.Reconnect();
}
Thread.Sleep(10000);
} catch (Exception) { }
}
}
private void Reconnect() {
this.Disconnect();
this.Connect();
}
private void Disconnect() {
if (this.mqtt != null) { if (this.mqtt != null) {
this.mqtt.MessageIncomming -= this.Mqtt_MessageIncomming; this.mqtt.MessageIncomming -= this.EventInput;
} }
this.zw.Update -= this.ZwayEvent; this.library.Update -= this.EventOutput;
if (this.mqtt != null) { if (this.mqtt != null) {
this.mqtt.Dispose(); this.mqtt.Dispose();
} }
this.mqtt = null; this.mqtt = null;
} }
#endregion
private void Connect() { #region Events
this.mqtt = ABackend.GetInstance(this.config["settings"], ABackend.BackendType.Data); protected virtual void EventOutput(Object sender, DeviceUpdateEvent e) {
this.mqtt.MessageIncomming += this.Mqtt_MessageIncomming;
this.zw.Update += this.ZwayEvent;
}
private void ZwayEvent(Object sender, DeviceUpdateEvent e) {
String topic = ""; String topic = "";
String data = ""; String data = "";
if(e.Parent.HasAbstract(typeof(ACommandClass))) { if (e.Parent.GetType().HasInterface(typeof(IMqtt))) {
ACommandClass sensor = (ACommandClass)e.Parent; IMqtt sensor = (IMqtt)e.Parent;
topic = "zwavebot/devices/" + sensor.MqttTopic(); topic = "zwavebot/devices/" + sensor.MqttTopic();
data = sensor.ToJson(); data = sensor.ToJson();
} }
if(topic != "" && data != "") { if (topic != "" && data != "") {
((ADataBackend)this.mqtt).Send(topic, data); ((ADataBackend)this.mqtt).Send(topic, data);
this.Update?.Invoke(this, new MqttEvent(topic, data)); this.Update?.Invoke(this, new MqttEvent(topic, data));
} }
} }
private void Mqtt_MessageIncomming(Object sender, BackendEvent e) { 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"))) { 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()); 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 = ""; String id = "";
if(m.Groups[1].Success) { if (m.Groups[1].Success) {
id = m.Groups[1].Value + "-" + m.Groups[2].Value + "-" + m.Groups[3].Value; id = m.Groups[1].Value + "-" + m.Groups[2].Value + "-" + m.Groups[3].Value;
} }
if(m.Groups[4].Success) { if (m.Groups[4].Success) {
id = m.Groups[4].Value + "-" + m.Groups[5].Value + "-" + m.Groups[6].Value + "-" + m.Groups[7].Value; id = m.Groups[4].Value + "-" + m.Groups[5].Value + "-" + m.Groups[6].Value + "-" + m.Groups[7].Value;
} }
ACommandClass c = this.zw.GetCommandClass(id); ACommandClass c = this.library.GetCommandClass(id);
if(c == null) { if (c == null) {
return; return;
} }
if (e.From.ToString().EndsWith("/set")) { if (e.From.ToString().EndsWith("/set")) {
@ -97,74 +77,17 @@ namespace ZwayBot.Moduls {
} }
} }
} catch (Exception) { } } catch (Exception) { }
} else if(e.From.ToString().EndsWith("/get")) { } else if (e.From.ToString().EndsWith("/get")) {
c.PollOnce = true; c.PollOnce = true;
((ADataBackend)this.mqtt).Send("zwavebot/devices/" + c.MqttTopic(), c.ToJson()); ((ADataBackend)this.mqtt).Send("zwavebot/devices/" + c.MqttTopic(), c.ToJson());
this.Update?.Invoke(this, new MqttEvent(e.From.ToString(), "Dataget")); this.Update?.Invoke(this, new MqttEvent(e.From.ToString(), "Dataget"));
} }
} }
if (e.From.ToString().StartsWith("zwavebot/config/") && (e.From.ToString().EndsWith("/set") || e.From.ToString().EndsWith("/get"))) { Tuple<Boolean, MqttEvent> cs = this.ChangeConfig(e, "zwavebot/config/");
Match m = new Regex("^zwavebot/config/(\\w+)/[gs]et$|").Match(e.From.ToString()); if (cs.Item1) {
if (!m.Groups[1].Success) { this.Update?.Invoke(this, cs.Item2);
return;
}
AModul modul = null;
foreach (KeyValuePair<String, AModul> item in this.modules) {
if (item.Key.ToLower() == m.Groups[1].Value) {
modul = item.Value;
}
}
if (modul == null) {
return;
}
if(e.From.ToString().EndsWith("/get") && modul.HasConfig && modul.ConfigPublic) {
String topic = "zwavebot/config/" + m.Groups[1].Value;
String data = JsonMapper.ToJson(modul.GetConfig()).ToString();
((ADataBackend)this.mqtt).Send(topic, data);
this.Update?.Invoke(this, new MqttEvent(topic, data));
}
if (e.From.ToString().EndsWith("/set") && modul.HasConfig && modul.ConfigPublic) {
try {
JsonData a = JsonMapper.ToObject(e.Message);
Dictionary<String, Dictionary<String, String>> newconf = new Dictionary<String, Dictionary<String, String>>();
foreach (String section in a.Keys) {
Dictionary<String, String> sectiondata = new Dictionary<String, String>();
foreach (String item in a[section].Keys) {
sectiondata.Add(item, a[section][item].ToString());
}
newconf.Add(section, sectiondata);
}
modul.SetConfig(newconf);
this.Update?.Invoke(this, new MqttEvent("New Config", "Write"));
} catch (Exception) { }
}
} }
} }
public override void Interconnect(Dictionary<String, AModul> moduls) {
this.modules = moduls;
}
protected override void UpdateConfig() { }
#region IDisposable Support
private Boolean disposedValue = false;
protected virtual void Dispose(Boolean disposing) {
if (!this.disposedValue) {
if (disposing) {
this.connectionWatcher.Abort();
while(this.connectionWatcher.ThreadState == ThreadState.Running) { Thread.Sleep(10); }
this.Disconnect();
}
this.disposedValue = true;
}
}
public override void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion #endregion
} }
} }

View File

@ -4,9 +4,12 @@ using BlubbFish.IoT.Zway;
using BlubbFish.IoT.Zway.Events; using BlubbFish.IoT.Zway.Events;
using BlubbFish.IoT.Zway.Interfaces; using BlubbFish.IoT.Zway.Interfaces;
using BlubbFish.Utils; using BlubbFish.Utils;
using BlubbFish.Utils.IoT.Bots;
using BlubbFish.Utils.IoT.Bots.Events;
using BlubbFish.Utils.IoT.Bots.Moduls;
namespace ZwayBot.Moduls { namespace ZwayBot.Moduls {
internal class Overtaker : AModul, IDisposable { internal class Overtaker : AModul<ZwayController>, IDisposable {
private readonly Dictionary<String, Dictionary<String, String>> events = new Dictionary<String, Dictionary<String, String>>(); private readonly Dictionary<String, Dictionary<String, String>> events = new Dictionary<String, Dictionary<String, String>>();
public override event ModulEvent Update; public override event ModulEvent Update;
@ -21,7 +24,7 @@ namespace ZwayBot.Moduls {
String from = item.Value["from"]; String from = item.Value["from"];
String[] source = from.Split(':'); String[] source = from.Split(':');
this.events.Add(source[0], item.Value); this.events.Add(source[0], item.Value);
ACommandClass c = this.zw.GetCommandClass(source[0]); ACommandClass c = this.library.GetCommandClass(source[0]);
if (c != null) { if (c != null) {
c.Polling = true; c.Polling = true;
c.Update += this.ChangedEvent; c.Update += this.ChangedEvent;
@ -31,7 +34,7 @@ namespace ZwayBot.Moduls {
} }
private void ChangedEvent(Object sender, DeviceUpdateEvent e) { private void ChangedEvent(Object sender, DeviceUpdateEvent e) {
if(sender.HasAbstract(typeof(ACommandClass))) { if(sender.GetType().HasAbstract(typeof(ACommandClass))) {
if (this.events.ContainsKey(((ACommandClass)sender).Id)) { if (this.events.ContainsKey(((ACommandClass)sender).Id)) {
this.SetValues(sender, ((ACommandClass)sender).Id, this.events[((ACommandClass)sender).Id]); this.SetValues(sender, ((ACommandClass)sender).Id, this.events[((ACommandClass)sender).Id]);
} }
@ -62,7 +65,7 @@ namespace ZwayBot.Moduls {
foreach (String to in dictionary["to"].Split(';')) { foreach (String to in dictionary["to"].Split(';')) {
String[] target = to.Split(':'); String[] target = to.Split(':');
if (target.Length == 2) { if (target.Length == 2) {
ACommandClass c = this.zw.GetCommandClass(target[0]); ACommandClass c = this.library.GetCommandClass(target[0]);
if (c != null) { if (c != null) {
if (c.HasProperty(target[1])) { if (c.HasProperty(target[1])) {
if (c.GetProperty(target[1]).ToString() != source_value) { if (c.GetProperty(target[1]).ToString() != source_value) {

View File

@ -2,63 +2,39 @@
using BlubbFish.IoT.Zway; using BlubbFish.IoT.Zway;
using BlubbFish.IoT.Zway.Events; using BlubbFish.IoT.Zway.Events;
using BlubbFish.Utils; using BlubbFish.Utils;
using BlubbFish.Utils.IoT.Bots;
using BlubbFish.Utils.IoT.Bots.Events;
using BlubbFish.Utils.IoT.Connector; using BlubbFish.Utils.IoT.Connector;
using BlubbFish.Utils.IoT.Events; using BlubbFish.Utils.IoT.Events;
using BlubbFish.Utils.IoT.Interfaces; using BlubbFish.Utils.IoT.Interfaces;
namespace ZwayBot.Moduls { namespace ZwayBot.Moduls {
class Senml : AModul { class Senml : Mqtt {
public override event ModulEvent Update; public override event ModulEvent Update;
private readonly ABackend mqtt;
private readonly String SenmlGuid; private readonly String SenmlGuid;
public Senml(ZwayController zway, InIReader settings) : base(zway, settings) { public Senml(ZwayController zway, InIReader settings) : base(zway, settings) {
if (this.config.ContainsKey("settings")) { if (this.config.ContainsKey("settings")) {
this.mqtt = ABackend.GetInstance(this.config["settings"], ABackend.BackendType.Data);
this.mqtt.MessageIncomming += this.EventInput;
this.zw.Update += this.EventOutput;
this.SenmlGuid = this.config["settings"]["guid"]; this.SenmlGuid = this.config["settings"]["guid"];
} }
} }
#region Events #region Events
private void EventOutput(Object sender, DeviceUpdateEvent e) { protected override void EventOutput(Object sender, DeviceUpdateEvent e) {
String topic = ""; String topic = "";
String data = ""; String data = "";
if (e.Parent.HasInterface(typeof(ISenml))) { if (e.Parent.GetType().HasInterface(typeof(ISenml))) {
ISenml sensor = (ISenml)e.Parent; ISenml sensor = (ISenml)e.Parent;
topic = sensor.SenmlTopic() + this.SenmlGuid+ "/senml"; topic = sensor.SenmlTopic() + this.SenmlGuid+ "/senml";
data = sensor.ToSenml(); data = sensor.ToSenml();
} }
if (topic != "" && data != null && data != "") { if (topic != "" && data != null && data != "") {
((ADataBackend)this.mqtt).Send(topic, data); ((ADataBackend)this.mqtt).Send(topic, data);
this.Update?.Invoke(this, new MqttEvent(topic, data)); this.Update?.Invoke(this, new SenmlEvent(topic, data));
} }
} }
private void EventInput(Object sender, BackendEvent e) { } protected override void EventInput(Object sender, BackendEvent e) { }
#endregion
#region Config
protected override void UpdateConfig() { }
#endregion
#region IDisposable Support
private Boolean disposedValue = false;
protected virtual void Dispose(Boolean disposing) {
if (!this.disposedValue) {
if (disposing) {
this.mqtt.Dispose();
}
this.disposedValue = true;
}
}
public override void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion #endregion
} }
} }

View File

@ -4,23 +4,25 @@ using BlubbFish.IoT.Zway;
using BlubbFish.IoT.Zway.Devices; using BlubbFish.IoT.Zway.Devices;
using BlubbFish.IoT.Zway.Interfaces; using BlubbFish.IoT.Zway.Interfaces;
using BlubbFish.Utils; using BlubbFish.Utils;
using ZwayBot.Interfaces; using BlubbFish.Utils.IoT.Bots.Events;
using BlubbFish.Utils.IoT.Bots.Interfaces;
using BlubbFish.Utils.IoT.Bots.Moduls;
namespace ZwayBot.Moduls { namespace ZwayBot.Moduls {
class Statuspolling : AModul, IDisposable, IForceLoad { class Statuspolling : AModul<ZwayController>, IDisposable, IForceLoad {
public override event ModulEvent Update; public override event ModulEvent Update;
public Statuspolling(ZwayController zway, InIReader settings) : base(zway, settings) { } public Statuspolling(ZwayController zway, InIReader settings) : base(zway, settings) { }
public override void Interconnect(Dictionary<String, AModul> moduls) { public override void Interconnect(Dictionary<String, Object> moduls) {
foreach (KeyValuePair<String, AModul> item in moduls) { foreach (KeyValuePair<String, Object> item in moduls) {
if (item.Value is CronJob) { if (item.Value is CronJob) {
item.Value.SetInterconnection("0 0 * * *", new Action<Object>(this.PollAll), null); ((AModul<ZwayController>)item.Value).SetInterconnection("0 0 * * *", new Action<Object>(this.PollAll), null);
if (this.config.Count != 0) { if (this.config.Count != 0) {
foreach (KeyValuePair<String, Dictionary<String, String>> section in this.config) { foreach (KeyValuePair<String, Dictionary<String, String>> section in this.config) {
if (section.Value.ContainsKey("cron") && section.Value.ContainsKey("devices")) { if (section.Value.ContainsKey("cron") && section.Value.ContainsKey("devices")) {
item.Value.SetInterconnection(section.Value["cron"], new Action<Object>(this.PollSpecific), section.Value["devices"]); ((AModul<ZwayController>)item.Value).SetInterconnection(section.Value["cron"], new Action<Object>(this.PollSpecific), section.Value["devices"]);
} }
} }
} }
@ -31,14 +33,14 @@ namespace ZwayBot.Moduls {
private void PollSpecific(Object obj) { private void PollSpecific(Object obj) {
String devices = (String)obj; String devices = (String)obj;
foreach (String item in devices.Split(',')) { foreach (String item in devices.Split(',')) {
ACommandClass c = this.zw.GetCommandClass(item); ACommandClass c = this.library.GetCommandClass(item);
c.PollOnce = true; c.PollOnce = true;
this.Update?.Invoke(this, new StatusPollingEvent("Polling", item)); this.Update?.Invoke(this, new StatusPollingEvent("Polling", item));
} }
} }
private void PollAll(Object o) { private void PollAll(Object o) {
foreach (KeyValuePair<Int32, Device> device in this.zw.Devices) { foreach (KeyValuePair<Int32, Device> device in this.library.Devices) {
foreach (KeyValuePair<Int32, Instance> instance in device.Value.Instances) { foreach (KeyValuePair<Int32, Instance> instance in device.Value.Instances) {
foreach (KeyValuePair<ACommandClass.Classes, ACommandClass> commandclass in instance.Value.CommandClasses) { foreach (KeyValuePair<ACommandClass.Classes, ACommandClass> commandclass in instance.Value.CommandClasses) {
commandclass.Value.PollOnce = true; commandclass.Value.PollOnce = true;

View File

@ -1,20 +1,13 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using BlubbFish.IoT.Zway; using BlubbFish.IoT.Zway;
using BlubbFish.Utils; using BlubbFish.Utils;
using BlubbFish.Utils.IoT.Bots;
namespace ZwayBot { namespace ZwayBot {
class Program { class Program : Bot {
static void Main(String[] args) => new Program(args); static void Main(String[] args) => new Program(args);
private readonly ZwayController zw;
private readonly Dictionary<String, AModul> moduls = new Dictionary<String, AModul>();
private Boolean RunningProcess = true;
private Thread sig_thread;
private readonly ProgramLogger logger = new ProgramLogger();
public Program(String[] args) { public Program(String[] args) {
InIReader.SetSearchPath(new List<String>() { "/etc/zwaybot", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\zwaybot" }); InIReader.SetSearchPath(new List<String>() { "/etc/zwaybot", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\zwaybot" });
Dictionary<String, String> names; Dictionary<String, String> names;
@ -28,89 +21,15 @@ namespace ZwayBot {
return; return;
} }
this.logger.SetPath(InIReader.GetInstance("settings").GetValue("logging", "path")); this.logger.SetPath(InIReader.GetInstance("settings").GetValue("logging", "path"));
this.zw = new ZwayController(InIReader.GetInstance("settings").GetSection("zway"), names, false); ZwayController zw = new ZwayController(InIReader.GetInstance("settings").GetSection("zway"), names, false);
this.zw.Update += this.ZwayDataUpate; zw.Update += this.ZwayDataUpate;
this.ModulLoader(); this.ModulLoader<ZwayController>("ZwayBot.Moduls", zw);
this.ModulInterconnect(); this.ModulInterconnect<ZwayController>();
this.ModulEvents(); this.ModulEvents<ZwayController>();
this.WaitForShutdown(); this.WaitForShutdown();
this.ModulDispose(); this.ModulDispose<ZwayController>();
} zw.Dispose();
}
private void ModulInterconnect() {
foreach (KeyValuePair<String, AModul> item in this.moduls) {
item.Value.Interconnect(this.moduls);
}
}
private void WaitForShutdown() {
if (Type.GetType("Mono.Runtime") != null) {
this.sig_thread = new Thread(delegate () {
Mono.Unix.UnixSignal[] signals = new Mono.Unix.UnixSignal[] {
new Mono.Unix.UnixSignal(Mono.Unix.Native.Signum.SIGTERM),
new Mono.Unix.UnixSignal(Mono.Unix.Native.Signum.SIGINT)
};
Console.WriteLine("Signalhandler Mono attached.");
while (true) {
Int32 i = Mono.Unix.UnixSignal.WaitAny(signals, -1);
Console.WriteLine("Signalhandler Mono INT recieved " + i + ".");
this.RunningProcess = false; // TODO BUG
break;
}
});
this.sig_thread.Start();
} else {
Console.CancelKeyPress += new ConsoleCancelEventHandler(this.SetupShutdown);
Console.WriteLine("Signalhandler Windows attached.");
}
while (this.RunningProcess) {
Thread.Sleep(100);
}
}
private void SetupShutdown(Object sender, ConsoleCancelEventArgs e) {
e.Cancel = true;
Console.WriteLine("Signalhandler Windows INT recieved.");
this.RunningProcess = false;
}
private void ModulDispose() {
foreach (KeyValuePair<String, AModul> item in this.moduls) {
item.Value.Dispose();
Console.WriteLine("Modul entladen: " + item.Key);
}
this.zw.Dispose();
if (this.sig_thread != null && this.sig_thread.IsAlive) {
this.sig_thread.Abort();
}
}
private void ModulEvents() {
foreach (KeyValuePair<String, AModul> item in this.moduls) {
item.Value.Update += this.ModulUpdate;
}
}
private void ModulUpdate(Object sender, ModulEventArgs e) {
Console.WriteLine(e.ToString());
}
private void ModulLoader() {
Assembly asm = Assembly.GetExecutingAssembly();
foreach (Type item in asm.GetTypes()) {
if(item.Namespace == "ZwayBot.Moduls") {
Type t = item;
String name = t.Name;
if (InIReader.ConfigExist(name.ToLower())) {
this.moduls.Add(name, (AModul)t.GetConstructor(new Type[] { typeof(ZwayController), typeof(InIReader) }).Invoke(new Object[] { this.zw, InIReader.GetInstance(name.ToLower()) }));
Console.WriteLine("Load Modul " + name);
} else if(t.HasInterface("IForceLoad")) {
this.moduls.Add(name, (AModul)t.GetConstructor(new Type[] { typeof(ZwayController), typeof(InIReader) }).Invoke(new Object[] { this.zw, null }));
Console.WriteLine("Load Modul Forced " + name);
}
}
}
}
private void ZwayDataUpate(Object sender, BlubbFish.IoT.Zway.Events.DeviceUpdateEvent e) { private void ZwayDataUpate(Object sender, BlubbFish.IoT.Zway.Events.DeviceUpdateEvent e) {
Console.WriteLine("-> ZW [" + e.UpdateTime + "]: " + e.Parent.ToString()); Console.WriteLine("-> ZW [" + e.UpdateTime + "]: " + e.Parent.ToString());

View File

@ -31,8 +31,8 @@ using System.Runtime.InteropServices;
// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, // Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden,
// übernehmen, indem Sie "*" eingeben: // übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.6.0")] [assembly: AssemblyVersion("1.6.1")]
[assembly: AssemblyFileVersion("1.6.0")] [assembly: AssemblyFileVersion("1.6.1")]
[assembly: NeutralResourcesLanguage("de-DE")] [assembly: NeutralResourcesLanguage("de-DE")]
// “Internet Of Things” icon by By Michael Wohlwend, US, from thenounproject.com. // “Internet Of Things” icon by By Michael Wohlwend, US, from thenounproject.com.

View File

@ -40,25 +40,10 @@
<PropertyGroup> <PropertyGroup>
<ApplicationIcon>Resources\Icon.ico</ApplicationIcon> <ApplicationIcon>Resources\Icon.ico</ApplicationIcon>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="dpkg\preinst" /> <None Include="dpkg\preinst" />
<None Include="dpkg\postinst" /> <None Include="dpkg\postinst" />
<Compile Include="Events.cs" />
<Compile Include="Interfaces\IForceLoad.cs" />
<Compile Include="Moduls\AModul.cs" />
<Compile Include="Moduls\CronJob.cs" /> <Compile Include="Moduls\CronJob.cs" />
<Compile Include="Helper.cs" />
<Compile Include="Moduls\Mqtt.cs" /> <Compile Include="Moduls\Mqtt.cs" />
<Compile Include="Moduls\Overtaker.cs" /> <Compile Include="Moduls\Overtaker.cs" />
<Compile Include="Moduls\Senml.cs" /> <Compile Include="Moduls\Senml.cs" />
@ -76,6 +61,10 @@
<Project>{91a14cd2-2940-4500-8193-56d37edddbaa}</Project> <Project>{91a14cd2-2940-4500-8193-56d37edddbaa}</Project>
<Name>litjson_4.7.1</Name> <Name>litjson_4.7.1</Name>
</ProjectReference> </ProjectReference>
<ProjectReference Include="..\..\Utils\Bot-Utils\Bot-Utils.csproj">
<Project>{bb7bfcb5-3db0-49e1-802a-3ce3eecc59f9}</Project>
<Name>Bot-Utils</Name>
</ProjectReference>
<ProjectReference Include="..\..\Utils\IoT\Connector\Data\Mqtt\ConnectorDataMqtt.csproj"> <ProjectReference Include="..\..\Utils\IoT\Connector\Data\Mqtt\ConnectorDataMqtt.csproj">
<Project>{ee6c8f68-ed46-4c1c-abdd-cfcdf75104f2}</Project> <Project>{ee6c8f68-ed46-4c1c-abdd-cfcdf75104f2}</Project>
<Name>ConnectorDataMqtt</Name> <Name>ConnectorDataMqtt</Name>
@ -127,7 +116,6 @@
<None Include="dpkg\prerm" /> <None Include="dpkg\prerm" />
<None Include="dpkg\zwaybot-logrotate" /> <None Include="dpkg\zwaybot-logrotate" />
<None Include="dpkg\zwaybot.service" /> <None Include="dpkg\zwaybot.service" />
<None Include="packages.config" />
<None Include="Resources\Icon.ico" /> <None Include="Resources\Icon.ico" />
<Content Include="Resources\icon.svg" /> <Content Include="Resources\icon.svg" />
</ItemGroup> </ItemGroup>
@ -137,12 +125,9 @@
<LastGenOutput>Resources.Designer.cs</LastGenOutput> <LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Drawing" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\Mono.Posix.5.4.0.201\build\net45\Mono.Posix.targets" Condition="Exists('..\packages\Mono.Posix.5.4.0.201\build\net45\Mono.Posix.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>Dieses Projekt verweist auf mindestens ein NuGet-Paket, das auf diesem Computer fehlt. Verwenden Sie die Wiederherstellung von NuGet-Paketen, um die fehlenden Dateien herunterzuladen. Weitere Informationen finden Sie unter "http://go.microsoft.com/fwlink/?LinkID=322105". Die fehlende Datei ist "{0}".</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Mono.Posix.5.4.0.201\build\net45\Mono.Posix.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Mono.Posix.5.4.0.201\build\net45\Mono.Posix.targets'))" />
</Target>
</Project> </Project>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -13,7 +13,7 @@ ExecStart=/usr/bin/mono /usr/local/bin/zwaybot/Zway-Bot.exe
KillMode=control-group KillMode=control-group
Restart=on-failure Restart=on-failure
StandardOutput=null StandardOutput=null
StandardError=syslog+journal StandardError=syslog
[Install] [Install]
WantedBy=multi-user.target WantedBy=multi-user.target

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Mono.Posix" version="5.4.0.201" targetFramework="net471" />
</packages>