[NF] Nun in der Lage Flex4Grid anzuzapfen

This commit is contained in:
BlubbFish 2017-09-19 20:57:08 +00:00
parent cfa9815d77
commit a0312c7757
19 changed files with 250 additions and 155 deletions

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
namespace Dashboard.Connector {
abstract class AMqtt {
public abstract event MqttMessage MessageIncomming;
public abstract event MqttMessage MessageSending;
public delegate void MqttMessage(Object sender, MqttEventArgs e);
internal static void SetInstance(Dictionary<String, String> dictionary) {
String object_sensor = "Dashboard.Connector." + Char.ToUpper(dictionary["type"][0]) + dictionary["type"].Substring(1);
Type t = null;
try {
t = Type.GetType(object_sensor, true);
} catch (TypeLoadException) {
throw new ArgumentException("settings.ini: " + dictionary["type"] + " is not a Connector");
}
Instance = (AMqtt)t.GetConstructor(new Type[] { typeof(Dictionary<String, String>) }).Invoke(new Object[] { dictionary });
}
public abstract void Send(String topic, String data);
public abstract void Dispose();
public static AMqtt Instance { get; private set; }
}
public class MqttEventArgs : EventArgs {
public MqttEventArgs() : base() { }
public MqttEventArgs(String message, String topic) {
this.Topic = topic;
this.Message = message;
this.Date = DateTime.Now;
}
public String Topic { get; private set; }
public String Message { get; private set; }
public DateTime Date { get; private set; }
}
}

View File

@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace Dashboard.Connector {
class Mosquitto : AMqtt, IDisposable {
private Process p;
private String message;
public override event MqttMessage MessageIncomming;
public override event MqttMessage MessageSending;
public Mosquitto(Dictionary<String, String> settings) {
//mosquitto_sub --cafile ca.pem --cert cert.pem --key cert.key -h swb.broker.flex4grid.eu -p 8883 -t /# -v
this.message = "";
this.p = new Process();
this.p.StartInfo.FileName = "mosquitto_sub.exe";
String args = "-h " + settings["server"]+" ";
if(settings.ContainsKey("port")) {
args += "-p "+ settings["port"]+" ";
}
if (settings.ContainsKey("cafile")) {
args += "--cafile " + settings["cafile"] + " ";
}
if (settings.ContainsKey("cert")) {
args += "--cert " + settings["cert"] + " ";
}
if (settings.ContainsKey("key")) {
args += "--key " + settings["key"] + " ";
}
this.p.StartInfo.Arguments = args+"-t /# -v -d";
this.p.StartInfo.CreateNoWindow = true;
this.p.StartInfo.UseShellExecute = false;
this.p.StartInfo.RedirectStandardOutput = true;
this.p.StartInfo.RedirectStandardError = true;
this.p.OutputDataReceived += this.P_OutputDataReceived;
this.p.ErrorDataReceived += this.P_ErrorDataReceived;
this.p.Start();
this.p.BeginOutputReadLine();
}
public override void Send(String topic, String data) {
MessageSending?.Invoke(this, new MqttEventArgs(data, topic));
}
private void P_ErrorDataReceived(Object sender, DataReceivedEventArgs e) {
if (e.Data != null) {
throw new NotImplementedException(e.Data);
}
}
private void P_OutputDataReceived(Object sender, DataReceivedEventArgs e) {
if (e.Data != null) {
if (e.Data.StartsWith("Client mosqsub")) {
if (this.message != "" && this.message.IndexOf(" received PUBLISH ") > 0) {
MatchCollection matches = (new Regex("^Client mosqsub\\|.*received PUBLISH \\(.*,.*,.*,.*, '(.*)'.*\\)\\)\n[^ ]* (.*)$", RegexOptions.IgnoreCase | RegexOptions.Singleline)).Matches(this.message);
String topic = matches[0].Groups[1].Value;
String message = matches[0].Groups[2].Value.Trim();
this.MessageIncomming?.Invoke(this, new MqttEventArgs(message, topic));
}
this.message = e.Data + "\n";
} else {
this.message += e.Data + "\n";
}
}
}
#region IDisposable Support
private Boolean disposedValue = false; // Dient zur Erkennung redundanter Aufrufe.
protected virtual void Dispose(Boolean disposing) {
if (!this.disposedValue) {
if (disposing) {
this.p.CancelOutputRead();
if (!this.p.HasExited) {
this.p.Kill();
}
this.p.Close();
}
this.p = null;
this.disposedValue = true;
}
}
~Mosquitto() {
Dispose(false);
}
public override void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}

View File

@ -1,31 +1,26 @@
using System;
using System.Collections.Generic;
using System.Text;
using BlubbFish.Utils;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace Dashboard.Connector {
class Mqtt : IDisposable {
private static Mqtt instance;
class Mqtt : AMqtt, IDisposable {
private MqttClient client;
public delegate void MqttMessage(Object sender, MqttMsgPublishEventArgs e);
public override event MqttMessage MessageIncomming;
public override event MqttMessage MessageSending;
public event MqttMessage MessageIncomming;
public event MqttMessage MessageSending;
private Mqtt() {
this.client = new MqttClient(InIReader.GetInstance("settings.ini").GetValue("general", "mqtt-server"));
public Mqtt(Dictionary<String, String> settings) {
if(settings.ContainsKey("port")) {
this.client = new MqttClient(settings["server"], Int32.Parse(settings["port"]), false, null, null, MqttSslProtocols.None);
} else {
this.client = new MqttClient(settings["server"]);
}
Connect();
}
public static Mqtt Instance {
get {
if(instance == null) {
instance = new Mqtt();
}
return instance;
}
}
private void Connect() {
this.client.MqttMsgPublishReceived += this.Client_MqttMsgPublishReceived;
this.client.Connect(Guid.NewGuid().ToString());
@ -33,18 +28,21 @@ namespace Dashboard.Connector {
}
private void Client_MqttMsgPublishReceived(Object sender, MqttMsgPublishEventArgs e) {
this.MessageIncomming?.Invoke(this, e);
this.MessageIncomming?.Invoke(this, new MqttEventArgs(Encoding.UTF8.GetString(e.Message), e.Topic));
}
public void Send(String topic, String data) {
public override void Send(String topic, String data) {
this.client.Publish(topic, Encoding.UTF8.GetBytes(data));
this.MessageSending?.Invoke(this, new MqttMsgPublishEventArgs(topic, Encoding.UTF8.GetBytes(data), false, 0, false));
this.MessageSending?.Invoke(this, new MqttEventArgs(data, topic));
}
#region IDisposable Support
private bool disposedValue = false;
protected virtual void Dispose(bool disposing) {
if(!disposedValue) {
private Boolean disposedValue = false;
protected virtual void Dispose(Boolean disposing) {
if(!this.disposedValue) {
if(disposing) {
this.client.MqttMsgPublishReceived -= this.Client_MqttMsgPublishReceived;
this.client.Unsubscribe(new String[] { "#" });
@ -53,13 +51,13 @@ namespace Dashboard.Connector {
this.client = null;
disposedValue = true;
this.disposedValue = true;
}
}
~Mqtt() {
Dispose(false);
}
public void Dispose() {
public override void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}

View File

@ -25,13 +25,16 @@
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<Optimize>false</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="LitJson, Version=0.9.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\LitJson.0.9.0\lib\LitJson.dll</HintPath>
</Reference>
<Reference Include="M2Mqtt.Net, Version=4.3.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\M2Mqtt.4.3.0.0\lib\net45\M2Mqtt.Net.dll</HintPath>
</Reference>
@ -49,6 +52,8 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Connector\AMqtt.cs" />
<Compile Include="Connector\Mosquitto.cs" />
<Compile Include="Connector\Mqtt.cs" />
<Compile Include="Form1.cs">
<SubType>Form</SubType>
@ -59,11 +64,9 @@
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Sensor\ASensor.cs" />
<Compile Include="Sensor\Luminanz.cs" />
<Compile Include="Sensor\Flex4GridPower.cs" />
<Compile Include="Sensor\Power.cs" />
<Compile Include="Sensor\Pir.cs" />
<Compile Include="Sensor\Switch.cs" />
<Compile Include="Sensor\Temperatur.cs" />
<Compile Include="Tracings\ATracings.cs" />
<Compile Include="Tracings\Graph.cs" />
<Compile Include="Tracings\Meter.cs" />

View File

@ -1,32 +1,26 @@
using System;
using System.Text;
using System.Collections.Generic;
using System.Windows.Forms;
using BlubbFish.Utils;
using Dashboard.Connector;
using Dashboard.Sensor;
using Dashboard.Tracings;
using BlubbFish.Utils;
using System.Collections.Generic;
using System.Threading;
namespace Dashboard {
public partial class Dashboard : Form {
private Dictionary<String, ASensor> sensors = new Dictionary<String, ASensor>();
private Thread updateThread;
public Dashboard() {
InitializeComponent();
Mqtt.Instance.Connect();
AMqtt.SetInstance(InIReader.GetInstance("settings.ini").GetSection("mqtt"));
this.GenerateSensors();
this.GenerateForms();
this.updateThread = new Thread(this.SensorPolling);
this.updateThread.Start();
this.FormClosed += this.Dashboard_FormClosed;
this.SizeChanged += this.Dashboard_SizeChanged;
Mqtt.Instance.MessageIncomming += this.Instance_MessageIncomming;
AMqtt.Instance.MessageIncomming += this.Instance_MessageIncomming;
}
private void Dashboard_SizeChanged(Object sender, EventArgs e) {
@ -40,6 +34,7 @@ namespace Dashboard {
this.sensors.Add(sensor.ToLower().Substring(1, sensor.Length - 2), ASensor.GetInstance(ini.GetValue(sensor, "type").ToLower(), ini.GetSection(sensor)));
}
}
private void GenerateForms() {
InIReader ini = InIReader.GetInstance("tracings.ini");
List<String> tracingini = ini.GetSections();
@ -47,27 +42,21 @@ namespace Dashboard {
this.flowLayoutPanel2.Controls.Add(ATracings.GetInstance(ini.GetValue(tracing, "type").ToLower(), this.sensors[ini.GetValue(tracing, "sensor").ToLower()], ini.GetSection(tracing)).GetPanel());
}
}
private void SensorPolling() {
while(true) {
Thread.Sleep(1000);
foreach(KeyValuePair<String, ASensor> sensor in this.sensors) {
sensor.Value.Poll();
}
}
}
private void Dashboard_FormClosed(Object sender, FormClosedEventArgs e) {
this.Dispose();
}
private new void Dispose() {
this.updateThread.Abort();
while (this.updateThread.ThreadState != ThreadState.Aborted) { }
foreach (KeyValuePair<String, ASensor> item in this.sensors) {
item.Value.Dispose();
}
this.sensors.Clear();
Mqtt.Instance.MessageIncomming -= this.Instance_MessageIncomming;
Mqtt.Instance.Dispose();
AMqtt.Instance.MessageIncomming -= this.Instance_MessageIncomming;
AMqtt.Instance.Dispose();
this.Dispose(true);
}
private void Instance_MessageIncomming(Object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e) {
System.Diagnostics.Debug.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic+" at "+DateTime.Now.ToUniversalTime());
private void Instance_MessageIncomming(Object sender, MqttEventArgs e) {
System.Diagnostics.Debug.WriteLine("Received = " + e.Message + " on topic " + e.Topic+" at "+DateTime.Now.ToUniversalTime());
}
}
}

View File

@ -1,6 +1,5 @@
using Dashboard.Connector;
using System;
using uPLibrary.Networking.M2Mqtt.Messages;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@ -20,7 +19,7 @@ namespace Dashboard.Sensor {
this.Polling = (settings.Keys.Contains("polling")) ? Int32.Parse(settings["polling"]) : 60;
this.pollcount = this.Polling;
this.settings = settings;
Mqtt.Instance.MessageIncomming += this.IncommingMqttMessage;
AMqtt.Instance.MessageIncomming += this.IncommingMqttMessage;
this.updateThread = new Thread(this.SensorPolling);
this.updateThread.Start();
}
@ -32,37 +31,38 @@ namespace Dashboard.Sensor {
}
}
private void IncommingMqttMessage(Object sender, MqttMsgPublishEventArgs e) {
private void IncommingMqttMessage(Object sender, MqttEventArgs e) {
if(e.Topic == this.topic) {
this.UpdateValue(e);
this.Timestamp = DateTime.Now;
this.Update?.Invoke(this, e);
if (this.UpdateValue(e)) {
this.Timestamp = DateTime.Now;
this.Update?.Invoke(this, e);
}
}
}
internal static ASensor GetInstance(String v, Dictionary<String, String> dictionary) {
string object_sensor = "Dashboard.Sensor." + char.ToUpper(v[0]) + v.Substring(1);
String object_sensor = "Dashboard.Sensor." + Char.ToUpper(v[0]) + v.Substring(1);
Type t = null;
try {
t = Type.GetType(object_sensor, true);
} catch(TypeLoadException) {
throw new ArgumentException("sensor.ini: " + v + " is not a Sensor");
}
return (ASensor)t.GetConstructor(new Type[] { typeof(Dictionary<String, String>) }).Invoke(new object[] { dictionary });
return (ASensor)t.GetConstructor(new Type[] { typeof(Dictionary<String, String>) }).Invoke(new Object[] { dictionary });
}
private void Poll() {
if(this.pollcount++ >= this.Polling) {
this.pollcount = 1;
Mqtt.Instance.Send(this.topic + "/status","");
AMqtt.Instance.Send(this.topic + "/status","");
}
}
internal virtual void SetBool(Boolean v) {
Mqtt.Instance.Send(this.topic + "/set", v ? "on" : "off");
AMqtt.Instance.Send(this.topic + "/set", v ? "on" : "off");
}
protected abstract void UpdateValue(MqttMsgPublishEventArgs e);
protected abstract Boolean UpdateValue(MqttEventArgs e);
public Single GetFloat { get; protected set; }
public Boolean GetBool { get; protected set; }
@ -79,17 +79,17 @@ namespace Dashboard.Sensor {
public event UpdatedValue Update;
#region IDisposable Support
private bool disposedValue = false;
protected virtual void Dispose(bool disposing) {
if(!disposedValue) {
private Boolean disposedValue = false;
protected virtual void Dispose(Boolean disposing) {
if(!this.disposedValue) {
if(disposing) {
this.updateThread.Abort();
while(this.updateThread.ThreadState != ThreadState.Aborted) { }
Mqtt.Instance.MessageIncomming -= this.IncommingMqttMessage;
AMqtt.Instance.MessageIncomming -= this.IncommingMqttMessage;
}
this.settings = null;
this.updateThread = null;
disposedValue = true;
this.disposedValue = true;
}
}
~ASensor() {

View File

@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Dashboard.Connector;
using LitJson;
namespace Dashboard.Sensor {
class Flex4gridpower : ASensor {
private String id;
public Flex4gridpower(Dictionary<String, String> settings) : base(settings) {
this.GetBool = true;
this.GetFloat = 0.0f;
this.GetInt = 0;
this.Datatypes = Types.Float;
this.id = settings["id"];
}
protected override Boolean UpdateValue(MqttEventArgs e) {
CultureInfo info = new CultureInfo("de-DE");
info.NumberFormat.NumberDecimalSeparator = ".";
CultureInfo.DefaultThreadCurrentCulture = info;
CultureInfo.DefaultThreadCurrentUICulture = info;
System.Threading.Thread.CurrentThread.CurrentCulture = info;
System.Threading.Thread.CurrentThread.CurrentUICulture = info;
try {
JsonData data = JsonMapper.ToObject(e.Message);
if(data["id"].ToString() == this.id) {
this.GetFloat = Single.Parse(data["power"].ToString());
return true;
}
} catch (Exception) {
}
return false;
}
}
}

View File

@ -1,8 +1,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using uPLibrary.Networking.M2Mqtt.Messages;
using Dashboard.Connector;
namespace Dashboard.Sensor {
class Power : ASensor {
@ -13,8 +12,9 @@ namespace Dashboard.Sensor {
this.Datatypes = Types.Float;
}
protected override void UpdateValue(MqttMsgPublishEventArgs e) {
this.GetFloat = Single.Parse(Encoding.UTF8.GetString(e.Message), new CultureInfo("en-US"));
protected override Boolean UpdateValue(MqttEventArgs e) {
this.GetFloat = Single.Parse(e.Message, new CultureInfo("en-US"));
return true;
}
}
}

View File

@ -1,6 +1,6 @@
using System.Collections.Generic;
using System.Text;
using uPLibrary.Networking.M2Mqtt.Messages;
using System;
using System.Collections.Generic;
using Dashboard.Connector;
namespace Dashboard.Sensor {
class Switch : ASensor {
@ -8,8 +8,9 @@ namespace Dashboard.Sensor {
this.Datatypes = Types.Bool;
}
protected override void UpdateValue(MqttMsgPublishEventArgs e) {
this.GetBool = (Encoding.UTF8.GetString(e.Message).ToLower() == "on") ? true : false;
protected override Boolean UpdateValue(MqttEventArgs e) {
this.GetBool = (e.Message.ToLower() == "on") ? true : false;
return true;
}
}
}

View File

@ -16,14 +16,14 @@ namespace Dashboard.Tracings {
protected abstract void SensorUpdate(Object sender, EventArgs e);
public abstract Panel GetPanel();
internal static ATracings GetInstance(String v, ASensor aSensor, Dictionary<String, String> dictionary) {
string object_sensor = "Dashboard.Tracings." + char.ToUpper(v[0]) + v.Substring(1);
String object_sensor = "Dashboard.Tracings." + Char.ToUpper(v[0]) + v.Substring(1);
Type t = null;
try {
t = Type.GetType(object_sensor, true);
} catch(TypeLoadException) {
throw new ArgumentException("tracings.ini: " + v + " is not a Tracing");
}
return (ATracings)t.GetConstructor(new Type[] { typeof(ASensor), typeof(Dictionary<String, String>) }).Invoke(new object[] { aSensor, dictionary });
return (ATracings)t.GetConstructor(new Type[] { typeof(ASensor), typeof(Dictionary<String, String>) }).Invoke(new Object[] { aSensor, dictionary });
}
}
}

View File

@ -14,12 +14,12 @@ namespace Dashboard.Tracings {
public Graph(ASensor sensor, Dictionary<String, String> settings) : base(sensor, settings) {
this.Chart_Items = (settings.Keys.Contains("items")) ? Int32.Parse(settings["items"]) : 1000;
this.chart = new Chart();
}
public override Panel GetPanel() {
Panel panel = new Panel();
this.chart = new Chart();
ChartArea chartArea = new ChartArea();
chartArea.AxisX.LabelStyle.Enabled = false;
chartArea.AxisX.LineColor = System.Drawing.Color.Gainsboro;

Binary file not shown.

Binary file not shown.

View File

@ -1,24 +0,0 @@
[Thinkpad]
topic=zway/wohnzimmer/thinkpad/power
type=Power
polling=10
[Tv]
topic=zway/wohnzimmer/tV/power
type=Power
polling=10
[Kühlschrank]
topic=zway/küche/kuehlschrank/power
type=Power
polling=10
[TvSW]
topic=zway/wohnzimmer/tV/switch
type=switch
polling=10
;[Ventilator]
;topic=zway/power/test/wVentilator
;type=Power
;polling=10

View File

@ -1,2 +0,0 @@
[general]
mqtt-server=localhost

View File

@ -1,45 +0,0 @@
[ThinkpadMeter]
sensor=Thinkpad
type=PowerMeter
items=100
[TvMeter]
sensor=Tv
type=PowerMeter
items=100
[KühlschrankrMeter]
sensor=Kühlschrank
type=PowerMeter
items=100
[ThinkpadGraph]
sensor=Thinkpad
type=Graph
items=100
[TvGraph]
sensor=Tv
type=Graph
items=100
[KühlschrankGraph]
sensor=Kühlschrank
type=Graph
items=100
[TvSWMeter]
sensor=TvSW
type=Switcher
items=100
;[VentilatorGraph]
;sensor=Ventilator
;type=Graph
;items=100
;[VentilatorMeter]
;sensor=Ventilator
;type=Meter
;unit=W
;items=100

View File

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="LitJson" version="0.9.0" targetFramework="net452" />
<package id="M2Mqtt" version="4.3.0.0" targetFramework="net452" />
</packages>

View File

@ -1,2 +1,3 @@
[general]
mqtt-server=localhost
[mqtt]
type=mqtt
server=localhost