This commit is contained in:
2017-09-26 20:21:42 +02:00
parent e144bde202
commit 319ca0cbbb
194 changed files with 10149 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
namespace Dashboard.Connector {
public abstract class ADataBackend {
public abstract event MqttMessage MessageIncomming;
public abstract event MqttMessage MessageSending;
public delegate void MqttMessage(Object sender, MqttEventArgs e);
public static ADataBackend GetInstance(Dictionary<String, String> dictionary) {
String object_sensor = "Dashboard.Connector." + Char.ToUpper(dictionary["type"][0]) + dictionary["type"].Substring(1).ToLower();
Type t = null;
try {
t = Type.GetType(object_sensor, true);
} catch (TypeLoadException) {
throw new ArgumentException("settings.ini: " + dictionary["type"] + " is not a Connector");
}
return (ADataBackend)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 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; }
}
}
@@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace Dashboard.Connector {
class Mosquitto : ADataBackend, IDisposable {
private Process p;
private String message;
public override event MqttMessage MessageIncomming;
public override event MqttMessage MessageSending;
public Mosquitto(Dictionary<String, String> mqtt_settings) {
this.settings = mqtt_settings;
//mosquitto_sub --cafile ca.pem --cert cert.pem --key cert.key -h swb.broker.flex4grid.eu -p 8883 -t "#" -v -d
this.message = "";
this.p = new Process();
this.p.StartInfo.FileName = "mosquitto_sub";
String args = "-h " + this.settings["server"]+" ";
if(this.settings.ContainsKey("port")) {
args += "-p "+ this.settings["port"]+" ";
}
if (this.settings.ContainsKey("cafile")) {
args += "--cafile " + this.settings["cafile"] + " ";
}
if (this.settings.ContainsKey("cert")) {
args += "--cert " + this.settings["cert"] + " ";
}
if (this.settings.ContainsKey("key")) {
args += "--key " + this.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) {
Process send = new Process();
send.StartInfo.FileName = "mosquitto_pub";
String args = "-h " + this.settings["server"] + " ";
if (this.settings.ContainsKey("port")) {
args += "-p " + this.settings["port"] + " ";
}
if (this.settings.ContainsKey("cafile")) {
args += "--cafile " + this.settings["cafile"] + " ";
}
if (this.settings.ContainsKey("cert")) {
args += "--cert " + this.settings["cert"] + " ";
}
if (this.settings.ContainsKey("key")) {
args += "--key " + this.settings["key"] + " ";
}
send.StartInfo.Arguments = args + "-m \""+data.Replace("\"","\\\"")+"\" -t \""+topic+"\" -d";
send.StartInfo.CreateNoWindow = true;
send.StartInfo.UseShellExecute = false;
send.StartInfo.RedirectStandardOutput = true;
send.StartInfo.RedirectStandardError = true;
send.Start();
send.WaitForExit();
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.
private readonly Dictionary<String, String> settings;
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
}
}
@@ -0,0 +1,66 @@
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 : ADataBackend, IDisposable {
private MqttClient client;
public override event MqttMessage MessageIncomming;
public override event MqttMessage MessageSending;
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();
}
private void Connect() {
this.client.MqttMsgPublishReceived += this.Client_MqttMsgPublishReceived;
this.client.Connect(Guid.NewGuid().ToString());
this.client.Subscribe(new String[] { "#" }, new Byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
}
private void Client_MqttMsgPublishReceived(Object sender, MqttMsgPublishEventArgs e) {
this.MessageIncomming?.Invoke(this, new MqttEventArgs(Encoding.UTF8.GetString(e.Message), e.Topic));
}
public override void Send(String topic, String data) {
this.client.Publish(topic, Encoding.UTF8.GetBytes(data));
this.MessageSending?.Invoke(this, new MqttEventArgs(data, topic));
}
#region IDisposable Support
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[] { "#" });
this.client.Disconnect();
}
this.client = null;
this.disposedValue = true;
}
}
~Mqtt() {
Dispose(false);
}
public override void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
@@ -0,0 +1,54 @@
using BlubbFish.Utils;
using System;
using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Types;
namespace MqttToTelegram {
class Telegram {
private static Telegram instance;
private TelegramBotClient bot;
private ChatId chat;
public delegate void TelegramMessage(Object sender, Message e);
public event TelegramMessage MessageIncomming;
public event TelegramMessage MessageSending;
private Telegram() {
bot = new TelegramBotClient(InIReader.GetInstance("settings.ini").GetValue("general", "telegram-key"));
bot.OnMessage += Bot_OnMessage;
this.Connect();
}
private void Bot_OnMessage(Object sender, MessageEventArgs e) {
this.MessageIncomming?.Invoke(this, e.Message);
}
public static Telegram Instance {
get {
if(instance == null) {
instance = new Telegram();
}
return instance;
}
}
private void Connect() {
bot.StartReceiving();
this.chat = new ChatId(InIReader.GetInstance("settings.ini").GetValue("general", "chatid"));
}
public async void Send(String text) {
try {
Message x = await this.bot.SendTextMessageAsync(this.chat, text);
this.MessageSending?.Invoke(this, x);
} catch(ApiRequestException e) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message+" "+e.ErrorCode+" "+e.Parameters);
Console.ForegroundColor = ConsoleColor.White;
}
}
}
}
@@ -0,0 +1,149 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{16AC0F61-0B60-4A1D-A827-B3BFDBA9AAC7}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>Dashboard</RootNamespace>
<AssemblyName>Dashboard</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</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>
<Reference Include="OxyPlot, Version=1.0.0.0, Culture=neutral, PublicKeyToken=638079a8f0bd61e9, processorArchitecture=MSIL">
<HintPath>..\packages\OxyPlot.Core.1.0.0\lib\net45\OxyPlot.dll</HintPath>
</Reference>
<Reference Include="OxyPlot.WindowsForms, Version=1.0.0.0, Culture=neutral, PublicKeyToken=245eacd6b5d2d338, processorArchitecture=MSIL">
<HintPath>..\packages\OxyPlot.WindowsForms.1.0.0\lib\net45\OxyPlot.WindowsForms.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Windows.Forms.DataVisualization" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Connector\ADataBackend.cs" />
<Compile Include="Connector\Mosquitto.cs" />
<Compile Include="Connector\Mqtt.cs" />
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Sensor\ASensor.cs" />
<Compile Include="Sensor\Flex4GridPower.cs" />
<Compile Include="Sensor\Power.cs" />
<Compile Include="Sensor\Flex4GridSwitch.cs" />
<Compile Include="Sensor\Switch.cs" />
<Compile Include="Tracings\ATracings.cs" />
<Compile Include="Tracings\Graph.cs" />
<Compile Include="Tracings\Meter.cs" />
<Compile Include="Tracings\PowerMeter.cs" />
<Compile Include="Tracings\Switcher.cs" />
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<None Include="sensor.ini.example" />
<None Include="settings.ini.example" />
<None Include="tracings.ini.example" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Utils\Utils\Utils.csproj">
<Project>{fac8ce64-bf13-4ece-8097-aeb5dd060098}</Project>
<Name>Utils</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.5.2">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.5.2 %28x86 und x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<StartArguments>-debug</StartArguments>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<StartArguments>-debug</StartArguments>
</PropertyGroup>
<PropertyGroup>
<PublishUrlHistory />
<InstallUrlHistory />
<SupportUrlHistory />
<UpdateUrlHistory />
<BootstrapperUrlHistory />
<ErrorReportUrlHistory />
<FallbackCulture>de-DE</FallbackCulture>
<VerifyUploadedFiles>false</VerifyUploadedFiles>
</PropertyGroup>
</Project>
+65
View File
@@ -0,0 +1,65 @@
namespace Dashboard {
partial class Dashboard {
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Verwendete Ressourcen bereinigen.
/// </summary>
/// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Vom Windows Form-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent() {
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel();
this.SuspendLayout();
//
// statusStrip1
//
this.statusStrip1.Location = new System.Drawing.Point(0, 490);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(1247, 22);
this.statusStrip1.TabIndex = 0;
this.statusStrip1.Text = "statusStrip1";
//
// flowLayoutPanel2
//
this.flowLayoutPanel2.Location = new System.Drawing.Point(12, 12);
this.flowLayoutPanel2.Name = "flowLayoutPanel2";
this.flowLayoutPanel2.Size = new System.Drawing.Size(1223, 475);
this.flowLayoutPanel2.TabIndex = 3;
//
// Dashboard
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1247, 512);
this.Controls.Add(this.flowLayoutPanel2);
this.Controls.Add(this.statusStrip1);
this.Name = "Dashboard";
this.Text = "Dashboard";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.StatusStrip statusStrip1;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2;
}
}
+72
View File
@@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using BlubbFish.Utils;
using Dashboard.Connector;
using Dashboard.Sensor;
using Dashboard.Tracings;
namespace Dashboard {
public partial class Dashboard : Form {
private Dictionary<String, ASensor> sensors = new Dictionary<String, ASensor>();
private ADataBackend mqtt;
public Dashboard(Boolean debug) {
InitializeComponent();
this.mqtt = ADataBackend.GetInstance(InIReader.GetInstance("settings.ini").GetSection("mqtt"));
this.GenerateSensors();
this.GenerateForms();
this.FormClosed += this.Dashboard_FormClosed;
this.SizeChanged += this.Dashboard_SizeChanged;
if (debug) {
this.mqtt.MessageIncomming += this.Instance_MessageIncomming;
this.mqtt.MessageSending += this.Instance_MessageSending;
}
}
private void Dashboard_SizeChanged(Object sender, EventArgs e) {
this.flowLayoutPanel2.Size = new System.Drawing.Size(this.Size.Width - 40, this.Size.Width - 76);
}
private void GenerateSensors() {
InIReader ini = InIReader.GetInstance("sensor.ini");
List<String> sensorini = ini.GetSections(false);
foreach(String sensor in sensorini) {
this.sensors.Add(sensor.ToLower(), ASensor.GetInstance(this.mqtt, ini.GetSection(sensor), sensor));
}
}
private void GenerateForms() {
InIReader ini = InIReader.GetInstance("tracings.ini");
List<String> tracingini = ini.GetSections();
foreach(String tracing in tracingini) {
this.flowLayoutPanel2.Controls.Add(ATracings.GetInstance(ini.GetValue(tracing, "type").ToLower(), this.sensors, ini.GetSection(tracing)).GetPanel());
}
}
private void Dashboard_FormClosed(Object sender, FormClosedEventArgs e) {
this.Dispose();
}
private new void Dispose() {
foreach (KeyValuePair<String, ASensor> item in this.sensors) {
item.Value.Dispose();
}
this.sensors.Clear();
this.mqtt.MessageIncomming -= this.Instance_MessageIncomming;
this.mqtt.MessageSending -= this.Instance_MessageSending;
this.mqtt.Dispose();
this.Dispose(true);
}
private void Instance_MessageIncomming(Object sender, MqttEventArgs e) {
Console.WriteLine("Received = " + e.Message + " on topic " + e.Topic+" at "+DateTime.Now.ToUniversalTime());
}
private void Instance_MessageSending(Object sender, MqttEventArgs e) {
Console.WriteLine("Sended = " + e.Message + " on topic " + e.Topic + " at " + DateTime.Now.ToUniversalTime());
}
}
}
+123
View File
@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="statusStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>
+25
View File
@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using BlubbFish.Utils;
namespace Dashboard {
static class Program {
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main(String[] args) {
CmdArgs.Instance.SetArguments(new Dictionary<String, CmdArgs.VaildArguments> {
{ "-debug", new CmdArgs.VaildArguments(CmdArgs.ArgLength.Single) }
}, args);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Boolean debug = false;
if(CmdArgs.Instance.HasArgumentType("-debug")) {
debug = true;
}
Application.Run(new Dashboard(debug));
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("Mqtt-Dashboard")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Mqtt-Dashboard")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly
// für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("16ac0f61-0b60-4a1d-a827-b3bfdba9aac7")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden,
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
@@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Dashboard.Properties {
using System;
/// <summary>
/// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw.
/// </summary>
// Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert
// -Klasse über ein Tool wie ResGen oder Visual Studio automatisch generiert.
// Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen
// mit der /str-Option erneut aus, oder Sie erstellen Ihr VS-Projekt neu.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Dashboard.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle
/// Ressourcenzuordnungen, die diese stark typisierte Ressourcenklasse verwenden.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
@@ -0,0 +1,26 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Dashboard.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.1.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
@@ -0,0 +1,121 @@
using Dashboard.Connector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Text.RegularExpressions;
namespace Dashboard.Sensor {
public abstract class ASensor : IDisposable {
protected String topic;
protected Int32 pollcount;
private Dictionary<String, String> settings;
protected ADataBackend backend;
private Thread updateThread;
private Boolean pollEnabled = false;
public ASensor(Dictionary<String, String> settings, String name, ADataBackend backend) {
this.GetBool = true;
this.GetFloat = 0.0f;
this.GetInt = 0;
this.topic = (settings.Keys.Contains("topic")) ? settings["topic"] : "";
this.settings = settings;
this.Title = (settings.Keys.Contains("title")) ? settings["title"] : "";
this.Name = name;
this.backend = backend;
this.backend.MessageIncomming += this.IncommingMqttMessage;
if (settings.Keys.Contains("polling")) {
this.pollEnabled = true;
this.Polling = Int32.Parse(settings["polling"]);
this.pollcount = this.Polling;
this.updateThread = new Thread(this.SensorPolling);
this.updateThread.Start();
}
}
private void SensorPolling() {
while(this.pollEnabled) {
Thread.Sleep(1000);
this.Poll();
}
}
private void IncommingMqttMessage(Object sender, MqttEventArgs e) {
if(Regex.Match(e.Topic, this.topic).Success) {
if (this.UpdateValue(e)) {
this.Timestamp = DateTime.Now;
this.Update?.Invoke(this, e);
}
}
}
internal static ASensor GetInstance(ADataBackend backend, Dictionary<String, String> dictionary, String name) {
String object_sensor = "Dashboard.Sensor." + Char.ToUpper(dictionary["type"][0]) + dictionary["type"].Substring(1).ToLower();
Type t = null;
try {
t = Type.GetType(object_sensor, true);
} catch(TypeLoadException) {
throw new ArgumentException("sensor.ini: " + dictionary["type"] + " is not a Sensor");
}
return (ASensor)t.GetConstructor(new Type[] { typeof(Dictionary<String, String>), typeof(String), typeof(ADataBackend) }).Invoke(new Object[] { dictionary, name, backend });
}
protected virtual void Poll() {
if(this.pollcount++ >= this.Polling) {
this.pollcount = 1;
this.backend.Send(this.topic + "/status","");
}
}
internal virtual void SetBool(Boolean v) {
this.backend.Send(this.topic + "/set", v ? "on" : "off");
}
protected abstract Boolean UpdateValue(MqttEventArgs e);
public Single GetFloat { get; protected set; }
public Boolean GetBool { get; protected set; }
public Int32 GetInt { get; protected set; }
public Types Datatypes { get; protected set; }
public DateTime Timestamp { get; protected set; }
public Int32 Polling { get; private set; }
public String Title { get; protected set; }
public String Name { get; internal set; }
public enum Types {
Bool,
Int,
Float
}
public delegate void UpdatedValue(ASensor sender, EventArgs e);
public event UpdatedValue Update;
#region IDisposable Support
private Boolean disposedValue = false;
protected virtual void Dispose(Boolean disposing) {
if(!this.disposedValue) {
if(disposing) {
this.pollEnabled = false;
if (this.updateThread != null && this.updateThread.ThreadState == ThreadState.Running) {
this.updateThread.Abort();
while (this.updateThread.ThreadState != ThreadState.Aborted) { }
}
this.backend.MessageIncomming -= this.IncommingMqttMessage;
}
this.settings = null;
this.updateThread = null;
this.disposedValue = true;
}
}
~ASensor() {
Dispose(false);
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using Dashboard.Connector;
using LitJson;
namespace Dashboard.Sensor {
class Flex4gridswitch : ASensor {
private String id;
public Flex4gridswitch(Dictionary<String, String> settings, String name, ADataBackend backend) : base(settings, name, backend) {
this.Datatypes = Types.Bool;
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.Keys.Contains("id") && data["id"].ToString() == this.id) {
this.GetBool = data["status"].ToString() == "active" ? true : false;
return true;
}
if(data.Keys.Contains(this.id)) {
this.GetBool = data[this.id].ToString() == "active" ? true : false;
return true;
}
} catch (Exception) {
}
return false;
}
protected override void Poll() {
if (this.pollcount++ >= this.Polling) {
this.pollcount = 1;
String hid = Regex.Match(this.topic, "/flex4grid/v1/households/([^/]*)/device/state").Groups[1].Value;
this.backend.Send("/flex4grid/v1/households/" + hid + "/devices/state/request", "{\"timestamp\": \"" + DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffff'Z'") + "\"}");
}
}
internal override void SetBool(Boolean v) {
String hid = Regex.Match(this.topic, "/flex4grid/v1/households/([^/]*)/device/state").Groups[1].Value;
this.backend.Send("/flex4grid/v1/households/" + hid + "/device/actuate", "{\"command\":\""+(v ? "ON" : "OFF") + "\",\"deviceId\":\""+ this.id + "\",\"timestamp\":\"" + DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffff'Z'") + "\"}");
}
}
}
@@ -0,0 +1,34 @@
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, String name, ADataBackend backend) : base(settings, name, backend) {
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;
}
}
}
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace Dashboard.Sensor {
class Luminanz : ASensor {
public Luminanz(Dictionary<String, String> settings) : base(settings) {
this.GetBool = true;
this.GetFloat = 0.0f;
this.GetInt = 0;
this.Datatypes = Types.Int;
}
protected override void UpdateValue(MqttMsgPublishEventArgs e) {
this.GetInt = Int32.Parse(Encoding.UTF8.GetString(e.Message), new CultureInfo("en-US"));
}
}
}
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Text;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace Dashboard.Sensor {
class Pir : ASensor {
public Pir(Dictionary<String, String> settings) : base(settings) {
this.Datatypes = Types.Bool;
}
protected override void UpdateValue(MqttMsgPublishEventArgs e) {
this.GetBool = (Encoding.UTF8.GetString(e.Message).ToLower() == "on") ? true : false;
}
}
}
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Dashboard.Connector;
namespace Dashboard.Sensor {
class Power : ASensor {
public Power(Dictionary<String, String> settings, String name, ADataBackend backend) : base(settings, name, backend) {
this.GetBool = true;
this.GetFloat = 0.0f;
this.GetInt = 0;
this.Datatypes = Types.Float;
}
protected override Boolean UpdateValue(MqttEventArgs e) {
this.GetFloat = Single.Parse(e.Message, new CultureInfo("en-US"));
return true;
}
}
}
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using Dashboard.Connector;
namespace Dashboard.Sensor {
class Switch : ASensor {
public Switch(Dictionary<System.String, System.String> settings, String name, ADataBackend backend) : base(settings, name, backend) {
this.Datatypes = Types.Bool;
}
protected override Boolean UpdateValue(MqttEventArgs e) {
this.GetBool = (e.Message.ToLower() == "on") ? true : false;
return true;
}
}
}
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace Dashboard.Sensor {
class Temperatur : ASensor {
public Temperatur(Dictionary<String, String> settings) : base(settings) {
this.GetBool = true;
this.GetFloat = 0.0f;
this.GetInt = 0;
this.Datatypes = Types.Float;
}
protected override void UpdateValue(MqttMsgPublishEventArgs e) {
this.GetFloat = Single.Parse(Encoding.UTF8.GetString(e.Message), new CultureInfo("en-US"));
}
}
}
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Dashboard.Sensor;
namespace Dashboard.Tracings {
public abstract class ATracings {
protected ASensor sensor;
protected Dictionary<String, String> settings;
protected Dictionary<String, ASensor> sensors;
public ATracings(ASensor sensor, Dictionary<String, String> settings) {
this.sensor = sensor;
this.sensor.Update += this.SensorUpdate;
this.settings = settings;
}
public ATracings(Dictionary<String, ASensor> sensors, Dictionary<String, String> settings) {
this.sensors = sensors;
foreach(KeyValuePair<String, ASensor> sensor in this.sensors) {
sensor.Value.Update += this.SensorsUpdate;
}
this.settings = settings;
}
protected abstract void SensorsUpdate(ASensor sender, EventArgs e);
protected abstract void SensorUpdate(ASensor sender, EventArgs e);
public abstract Panel GetPanel();
internal static ATracings GetInstance(String v, Dictionary<String, ASensor> sensorList, Dictionary<String, String> dictionary) {
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");
}
if (dictionary["sensor"].Contains(",")) {
Dictionary<String, ASensor> sensors = new Dictionary<String, ASensor>();
String[] sensors_name = dictionary["sensor"].Split(',');
foreach (String item in sensors_name) {
sensors.Add(item, sensorList[item.ToLower()]);
}
return (ATracings)t.GetConstructor(new Type[] { typeof(Dictionary<String, ASensor>), typeof(Dictionary<String, String>) }).Invoke(new Object[] { sensors, dictionary });
} else {
return (ATracings)t.GetConstructor(new Type[] { typeof(ASensor), typeof(Dictionary<String, String>) }).Invoke(new Object[] { sensorList[dictionary["sensor"].ToLower()], dictionary });
}
}
}
}
@@ -0,0 +1,156 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Dashboard.Sensor;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Series;
using OxyPlot.WindowsForms;
namespace Dashboard.Tracings {
class Graph : ATracings, IDisposable {
private Queue<Tuple<DateTime, Single>> hist = new Queue<Tuple<DateTime, Single>>();
private Dictionary<String, Queue<Tuple<DateTime, Single>>> hists = new Dictionary<String, Queue<Tuple<DateTime, Single>>>();
private Dictionary<String, Single> hists_last = new Dictionary<String, Single>();
private Int32 Chart_Items;
private PlotView plot = new PlotView { BackColor = System.Drawing.Color.White };
private PlotModel Model = new PlotModel();
private Boolean multi;
private Single MaximumDrawn = 1;
private String[] colors = { "255,255,0,0","255,230,230,0", "255,0,128,0", "255,0,0,255", "255,255,0,255", "255,255,128,0", "255,0,255,255", "255,158,255,128", "255,0,128,255", "255,0,0,0" };
public Graph(ASensor sensor, Dictionary<String, String> settings) : base(sensor, settings) {
this.Chart_Items = (settings.Keys.Contains("items")) ? Int32.Parse(settings["items"]) : 1000;
this.multi = false;
}
public Graph(Dictionary<String, ASensor> sensors, Dictionary<String, String> settings) : base(sensors, settings) {
this.Chart_Items = (settings.Keys.Contains("items")) ? Int32.Parse(settings["items"]) : 1000;
this.multi = true;
}
public override Panel GetPanel() {
Panel panel = new Panel { BorderStyle = BorderStyle.FixedSingle };
this.Model.Axes.Add(new DateTimeAxis { Position = AxisPosition.Bottom, AbsoluteMinimum = DateTimeAxis.ToDouble(DateTime.Now), AbsoluteMaximum = DateTimeAxis.ToDouble(DateTime.Now.AddMinutes(1)), IsZoomEnabled = false });
this.Model.Axes.Add(new LinearAxis { Position = AxisPosition.Left, AbsoluteMinimum = 0, Minimum = 0, AbsoluteMaximum = 1, IsZoomEnabled = false });
if (this.multi) {
Int32 i = 0;
foreach (KeyValuePair<String, ASensor> item in this.sensors) {
LineSeries l = new LineSeries { Color = OxyColor.Parse(this.colors[i++ % this.colors.Length]), TrackerKey = item.Value.Name };
if (item.Value.Title != "") {
l.Title = item.Value.Title;
}
this.Model.Series.Add(l);
}
} else {
LineSeries l = new LineSeries { Color = OxyColor.FromRgb(0, 0, 255) };
l.CanTrackerInterpolatePoints = true;
if (this.sensor.Title != "") {
l.Title = this.sensor.Title;
}
this.Model.Series.Add(l);
}
Int32 fieldWidth = 200;
if(this.multi) {
fieldWidth = (this.sensors.Count * 200) + (this.sensors.Count-1)*6;
}
this.plot.Location = new System.Drawing.Point(0, 0);
this.plot.Size = new System.Drawing.Size(fieldWidth, 200);
this.plot.Dock = DockStyle.Fill;
this.plot.Model = this.Model;
panel.Controls.Add(this.plot);
panel.Size = new System.Drawing.Size(fieldWidth, 200);
return panel;
}
protected override void SensorUpdate(ASensor sender, EventArgs e) {
Single v = 0;
switch (sender.Datatypes) {
case ASensor.Types.Bool: v = sender.GetBool ? 1 : 0; break;
case ASensor.Types.Int: v = sender.GetInt; break;
case ASensor.Types.Float: v = sender.GetFloat; break;
}
this.hist.Enqueue(new Tuple<DateTime, Single>(sender.Timestamp, v));
if (this.MaximumDrawn < v) {
this.MaximumDrawn = v;
}
if (this.hist.Count > this.Chart_Items) {
this.hist.Dequeue();
}
if (this.Model.Series.Count != 0) {
this.plot.BeginInvoke((MethodInvoker)delegate {
this.Model.Axes[1].Maximum = this.MaximumDrawn * 1.1;
this.Model.Axes[1].AbsoluteMaximum = this.MaximumDrawn * 1.1;
this.Model.Axes[0].AbsoluteMaximum = DateTimeAxis.ToDouble(sender.Timestamp);
((LineSeries)this.Model.Series[0]).Points.Clear();
try {
foreach(Tuple<DateTime, Single> temp in this.hist) {
((LineSeries)this.Model.Series[0]).Points.Add(new DataPoint(DateTimeAxis.ToDouble(temp.Item1),temp.Item2));
}
this.Model.InvalidatePlot(true);
} catch(Exception) { };
});
}
}
protected override void SensorsUpdate(ASensor sender, EventArgs e) {
Single v = 0;
if (!this.hists.ContainsKey(sender.Name)) {
this.hists.Add(sender.Name, new Queue<Tuple<DateTime, Single>>());
this.hists_last.Add(sender.Name, 0);
}
switch (sender.Datatypes) {
case ASensor.Types.Bool:
v = sender.GetBool ? 1 : 0;
break;
case ASensor.Types.Int:
v = sender.GetInt;
break;
case ASensor.Types.Float:
v = sender.GetFloat;
break;
}
this.hists_last[sender.Name] = v;
foreach (KeyValuePair<String, Queue<Tuple<DateTime, Single>>> item in this.hists) {
item.Value.Enqueue(new Tuple<DateTime, Single>(sender.Timestamp, this.hists_last[item.Key]));
if (this.MaximumDrawn < this.hists_last[item.Key]) {
this.MaximumDrawn = this.hists_last[item.Key];
}
if (item.Value.Count > this.Chart_Items) {
item.Value.Dequeue();
}
}
foreach (Series item in this.Model.Series) {
if (this.hists.ContainsKey(item.TrackerKey)) {
this.plot.BeginInvoke((MethodInvoker)delegate {
try {
this.Model.Axes[1].Maximum = this.MaximumDrawn * 1.1;
this.Model.Axes[1].AbsoluteMaximum = this.MaximumDrawn * 1.1;
this.Model.Axes[0].AbsoluteMaximum = DateTimeAxis.ToDouble(sender.Timestamp);
((LineSeries)item).Points.Clear();
foreach (Tuple<DateTime, Single> temp in this.hists[item.TrackerKey]) {
((LineSeries)item).Points.Add(new DataPoint(DateTimeAxis.ToDouble(temp.Item1), temp.Item2));
}
this.Model.InvalidatePlot(true);
} catch (Exception) { };
});
}
}
}
public void Dispose() {
((LineSeries)this.Model.Series[0]).Points.Clear();
this.Model = null;
this.hist.Clear();
this.hist = null;
this.plot.Dispose();
}
}
}
@@ -0,0 +1,71 @@
using System.Collections.Generic;
using Dashboard.Sensor;
using System;
using System.Windows.Forms;
using System.Linq;
using System.Globalization;
namespace Dashboard.Tracings {
class Meter : ATracings {
protected Int32 DisplayItems;
protected Queue<Single> DisplayAverage = new Queue<Single>();
protected Label label1;
protected Label label2;
public Meter(ASensor sensor, Dictionary<String, String> settings) : base(sensor, settings) {
this.DisplayItems = (settings.Keys.Contains("items")) ? Int32.Parse(settings["items"]) : 1000;
this.label1 = new Label();
this.label2 = new Label();
}
public override Panel GetPanel() {
Panel panel = new Panel() {
BorderStyle = BorderStyle.FixedSingle,
Size = new System.Drawing.Size(200, 100)
};
this.label1 = new Label() {
Font = new System.Drawing.Font("Lucida Sans Typewriter", 27.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((Byte)(0))),
Location = new System.Drawing.Point(0, 0),
Size = new System.Drawing.Size(200, 43),
Text = "",
TextAlign = System.Drawing.ContentAlignment.TopCenter
};
panel.Controls.Add(this.label1);
this.label2 = new Label() {
AutoSize = true,
Location = new System.Drawing.Point(0, 50),
Size = new System.Drawing.Size(96, 13),
Text = ""
};
panel.Controls.Add(this.label2);
return panel;
}
protected override void SensorsUpdate(ASensor sender, EventArgs e) {
throw new NotImplementedException();
}
protected override void SensorUpdate(ASensor sender, EventArgs e) {
String value = "";
switch(sender.Datatypes) {
case ASensor.Types.Bool: this.DisplayAverage.Enqueue((sender.GetBool) ? 1 : 0); value = sender.GetBool.ToString(new CultureInfo("de-DE")); break;
case ASensor.Types.Int: this.DisplayAverage.Enqueue(sender.GetInt); value = sender.GetInt.ToString(); break;
case ASensor.Types.Float: this.DisplayAverage.Enqueue(sender.GetFloat); value = sender.GetFloat.ToString(new CultureInfo("de-DE")); break;
}
if(this.DisplayAverage.Count > this.DisplayItems) {
this.DisplayAverage.Dequeue();
}
Single average = this.DisplayAverage.Sum() / this.DisplayAverage.Count();
this.label1.BeginInvoke((MethodInvoker)delegate {
this.label1.Text = value;
});
this.label2.BeginInvoke((MethodInvoker)delegate {
this.label2.Text = "Durchschnitt: " + Math.Round(average, 2);
});
}
}
}
@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using Dashboard.Sensor;
namespace Dashboard.Tracings {
class Powermeter : Meter {
public Powermeter(ASensor sensor, Dictionary<String, String> settings) : base(sensor, settings) {
}
protected override void SensorUpdate(ASensor sender, EventArgs e) {
String value = "";
switch (sender.Datatypes) {
case ASensor.Types.Bool:
this.DisplayAverage.Enqueue((sender.GetBool) ? 1 : 0);
value = sender.GetBool.ToString(new CultureInfo("de-DE"));
break;
case ASensor.Types.Int:
this.DisplayAverage.Enqueue(sender.GetInt);
value = sender.GetInt.ToString();
break;
case ASensor.Types.Float:
this.DisplayAverage.Enqueue(sender.GetFloat);
value = sender.GetFloat.ToString(new CultureInfo("de-DE"));
break;
}
if (this.DisplayAverage.Count > this.DisplayItems) {
this.DisplayAverage.Dequeue();
}
Single average = this.DisplayAverage.Sum() / this.DisplayAverage.Count();
try {
this.label1.BeginInvoke((MethodInvoker)delegate {
this.label1.Text = value + " W";
});
this.label2.BeginInvoke((MethodInvoker)delegate {
this.label2.Text = "Durchschnitt: " + Math.Round(average, 2) + " W";
});
} catch (Exception) { }
}
}
}
@@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Forms;
using Dashboard.Connector;
using Dashboard.Sensor;
namespace Dashboard.Tracings {
class Switcher : ATracings {
private Label label;
private Button button1;
private Button button2;
public Switcher(ASensor sensor, Dictionary<System.String, System.String> settings) : base(sensor, settings) {
this.label = new Label();
this.button1 = new Button();
this.button2 = new Button();
}
public override Panel GetPanel() {
Panel panel = new Panel() {
BorderStyle = BorderStyle.FixedSingle,
Size = new System.Drawing.Size(200, 100)
};
this.label = new Label() {
AutoSize = true,
Location = new System.Drawing.Point(69, 16),
Size = new System.Drawing.Size(35, 13),
Text = ""
};
panel.Controls.Add(this.label);
this.button1 = new Button() {
BackColor = System.Drawing.Color.FromArgb(0, 192, 0),
Location = new System.Drawing.Point(94, 67),
Name = "on",
Size = new System.Drawing.Size(45, 23),
Text = "ON",
UseVisualStyleBackColor = false
};
this.button1.Click += this.ButtonClicker;
panel.Controls.Add(this.button1);
this.button2 = new Button() {
BackColor = System.Drawing.Color.Red,
Location = new System.Drawing.Point(145, 67),
Name = "off",
Size = new System.Drawing.Size(45, 23),
Text = "OFF",
UseVisualStyleBackColor = false
};
this.button2.Click += this.ButtonClicker;
panel.Controls.Add(this.button2);
return panel;
}
private void ButtonClicker(Object sender, EventArgs e) {
Button b = (Button)sender;
if (b.Name == "on") {
this.sensor.SetBool(true);
} else if(b.Name == "off") {
this.sensor.SetBool(false);
}
}
protected override void SensorUpdate(ASensor sender, EventArgs e) {
this.label.BeginInvoke((MethodInvoker)delegate {
this.label.Text = sender.GetBool?"Eingeschaltet":"Ausgeschaltet";
});
this.button1.BeginInvoke((MethodInvoker)delegate {
this.button1.Enabled = !sender.GetBool;
});
this.button2.BeginInvoke((MethodInvoker)delegate {
this.button2.Enabled = sender.GetBool;
});
}
protected override void SensorsUpdate(ASensor sender, EventArgs e) {
throw new NotImplementedException();
}
}
}
Binary file not shown.
@@ -0,0 +1,7 @@
<?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" />
<package id="OxyPlot.Core" version="1.0.0" targetFramework="net452" />
<package id="OxyPlot.WindowsForms" version="1.0.0" targetFramework="net452" />
</packages>
@@ -0,0 +1,24 @@
[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
@@ -0,0 +1,3 @@
[mqtt]
type=mqtt
server=localhost
@@ -0,0 +1,45 @@
[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