[NF] Aufgeräumt

This commit is contained in:
BlubbFish 2017-10-02 16:26:38 +00:00
parent d5ca3672e9
commit 086bc89c2d
20 changed files with 80 additions and 651 deletions

View File

@ -1,10 +1,14 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14 # Visual Studio 15
VisualStudioVersion = 14.0.25420.1 VisualStudioVersion = 15.0.26730.16
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IoT-Bot", "IoT-Bot\IoT-Bot.csproj", "{89077643-B472-419F-8EAB-56B9E2D13ABC}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IoT-Bot", "IoT-Bot\IoT-Bot.csproj", "{89077643-B472-419F-8EAB-56B9E2D13ABC}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Utils-IoT", "..\Utils\IoT\Utils-IoT.csproj", "{B870E4D5-6806-4A0B-B233-8907EEDC5AFC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Utils", "..\Utils\Utils\Utils.csproj", "{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -15,8 +19,19 @@ Global
{89077643-B472-419F-8EAB-56B9E2D13ABC}.Debug|Any CPU.Build.0 = Debug|Any CPU {89077643-B472-419F-8EAB-56B9E2D13ABC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{89077643-B472-419F-8EAB-56B9E2D13ABC}.Release|Any CPU.ActiveCfg = Release|Any CPU {89077643-B472-419F-8EAB-56B9E2D13ABC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{89077643-B472-419F-8EAB-56B9E2D13ABC}.Release|Any CPU.Build.0 = Release|Any CPU {89077643-B472-419F-8EAB-56B9E2D13ABC}.Release|Any CPU.Build.0 = Release|Any CPU
{B870E4D5-6806-4A0B-B233-8907EEDC5AFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B870E4D5-6806-4A0B-B233-8907EEDC5AFC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B870E4D5-6806-4A0B-B233-8907EEDC5AFC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B870E4D5-6806-4A0B-B233-8907EEDC5AFC}.Release|Any CPU.Build.0 = Release|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FAC8CE64-BF13-4ECE-8097-AEB5DD060098}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {868AF401-44D7-4E3C-826A-8FA1E24C850D}
EndGlobalSection
EndGlobal EndGlobal

View File

@ -1,6 +1,18 @@
<?xml version="1.0" encoding="utf-8" ?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<startup> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
</startup> </startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.1.0" newVersion="4.1.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration> </configuration>

View File

@ -1,7 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using IoTBot.Connector; using BlubbFish.Utils.IoT.Connector;
using IoTBot.Sensor; using BlubbFish.Utils.IoT.Sensor;
namespace IoTBot.Condition { namespace IoTBot.Condition {
abstract class ACondition { abstract class ACondition {

View File

@ -1,7 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using IoTBot.Connector; using BlubbFish.Utils.IoT.Connector;
using IoTBot.Sensor; using BlubbFish.Utils.IoT.Sensor;
namespace IoTBot.Condition { namespace IoTBot.Condition {
class Edge : ACondition { class Edge : ACondition {
@ -15,7 +15,7 @@ namespace IoTBot.Condition {
if(this.sensor.Datatypes == ASensor.Types.Bool) { if(this.sensor.Datatypes == ASensor.Types.Bool) {
if(this.sensor.GetBool == Boolean.Parse(this.settings["sensor_value"]) && this.histBool != this.sensor.GetBool) { if(this.sensor.GetBool == Boolean.Parse(this.settings["sensor_value"]) && this.histBool != this.sensor.GetBool) {
this.histBool = this.sensor.GetBool; this.histBool = this.sensor.GetBool;
IoTBot.Connector.Telegram.Instance.Send("Jemand ist DA!"); Telegram.Instance.Send("Jemand ist DA!");
} else { } else {
this.histBool = this.sensor.GetBool; this.histBool = this.sensor.GetBool;
} }

View File

@ -1,15 +1,15 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using BlubbFish.Utils; using BlubbFish.Utils;
using BlubbFish.Utils.IoT.Connector;
using IoTBot.Condition; using IoTBot.Condition;
using IoTBot.Connector;
namespace IoTBot { namespace IoTBot {
class ConditionWorker { class ConditionWorker {
private InIReader ini; private InIReader ini;
private static ConditionWorker instance; private static ConditionWorker instance;
private List<ACondition> conditions; private List<ACondition> conditions;
private Connector.Telegram telegram; private Telegram telegram;
public static ConditionWorker GetInstance(ADataBackend backend) { public static ConditionWorker GetInstance(ADataBackend backend) {
if (instance == null) { if (instance == null) {
@ -18,7 +18,7 @@ namespace IoTBot {
return instance; return instance;
} }
internal void Run(Connector.Telegram telegram) { internal void Run(Telegram telegram) {
this.telegram = telegram; this.telegram = telegram;
} }

View File

@ -1,38 +0,0 @@
using System;
using System.Collections.Generic;
namespace IoTBot.Connector {
public abstract class ADataBackend {
public abstract event MqttMessage MessageIncomming;
public abstract event MqttMessage MessageSending;
public delegate void MqttMessage(ADataBackend sender, MqttEventArgs e);
public static ADataBackend GetInstance(Dictionary<String, String> dictionary) {
String object_sensor = "IoTBot.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; }
}
}

View File

@ -1,121 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace IoTBot.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
}
}

View File

@ -1,65 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace IoTBot.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
}
}

View File

@ -1,54 +0,0 @@
using BlubbFish.Utils;
using System;
using Telegram.Bot;
using Telegram.Bot.Args;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Types;
namespace IoTBot.Connector {
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() {
this.bot = new TelegramBotClient(InIReader.GetInstance("settings.ini").GetValue("general", "telegram-key"));
this.bot.OnMessage += this.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() {
this.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;
}
}
}
}

View File

@ -9,9 +9,10 @@
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MqttToTelegram</RootNamespace> <RootNamespace>MqttToTelegram</RootNamespace>
<AssemblyName>MqttToTelegram</AssemblyName> <AssemblyName>MqttToTelegram</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion> <TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
@ -32,50 +33,12 @@
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<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>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.10.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.Core" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
<Private>True</Private>
</Reference>
<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" />
<Reference Include="Telegram.Bot, Version=13.0.1.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Telegram.Bot.13.1.0\lib\netstandard1.1\Telegram.Bot.dll</HintPath>
<Private>True</Private>
</Reference>
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="ConditionWorker.cs" /> <Compile Include="ConditionWorker.cs" />
<Compile Include="Condition\ACondition.cs" /> <Compile Include="Condition\ACondition.cs" />
<Compile Include="Condition\Edge.cs" /> <Compile Include="Condition\Edge.cs" />
<Compile Include="Connector\ADataBackend.cs" />
<Compile Include="Connector\Mqtt.cs" />
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Sensor\ASensor.cs" />
<Compile Include="Sensor\Luminanz.cs" />
<Compile Include="Sensor\Pir.cs" />
<Compile Include="Sensor\Power.cs" />
<Compile Include="Sensor\Switch.cs" />
<Compile Include="Sensor\Temperatur.cs" />
<Compile Include="Connector\Telegram.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="App.config" /> <None Include="App.config" />
@ -84,12 +47,15 @@
<None Include="settings.ini.example" /> <None Include="settings.ini.example" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\Utils\IoT\Utils-IoT.csproj">
<Project>{b870e4d5-6806-4a0b-b233-8907eedc5afc}</Project>
<Name>Utils-IoT</Name>
</ProjectReference>
<ProjectReference Include="..\..\Utils\Utils\Utils.csproj"> <ProjectReference Include="..\..\Utils\Utils\Utils.csproj">
<Project>{fac8ce64-bf13-4ece-8097-aeb5dd060098}</Project> <Project>{fac8ce64-bf13-4ece-8097-aeb5dd060098}</Project>
<Name>Utils</Name> <Name>Utils</Name>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -1,35 +1,35 @@
using System; using System;
using BlubbFish.Utils; using BlubbFish.Utils;
using IoTBot.Connector; using BlubbFish.Utils.IoT.Connector;
namespace IoTBot { namespace IoTBot {
class Program { class Program {
static void Main(String[] args) { static void Main(String[] args) {
ADataBackend mqtt = ADataBackend.GetInstance(InIReader.GetInstance("settings.ini").GetSection("mqtt")); ADataBackend mqtt = ADataBackend.GetInstance(InIReader.GetInstance("settings.ini").GetSection("mqtt"));
ConditionWorker.GetInstance(mqtt).Run(Connector.Telegram.Instance); ConditionWorker.GetInstance(mqtt).Run(Telegram.Instance);
mqtt.MessageIncomming += Mqtt_MessageIncomming; mqtt.MessageIncomming += Mqtt_MessageIncomming;
mqtt.MessageSending += Mqtt_MessageSending; mqtt.MessageSending += Mqtt_MessageSending;
Connector.Telegram.Instance.MessageIncomming += Telegram_MessageIncomming; Telegram.Instance.MessageIncomming += Telegram_MessageIncomming;
Connector.Telegram.Instance.MessageSending += Telegram_MessageSending; Telegram.Instance.MessageSending += Telegram_MessageSending;
while(true) { while(true) {
System.Threading.Thread.Sleep(100); System.Threading.Thread.Sleep(100);
} }
} }
private static void Mqtt_MessageSending(ADataBackend sender, MqttEventArgs e) { private static void Mqtt_MessageSending(Object sender, MqttEventArgs e) {
Console.WriteLine("-> [" + DateTime.Now.ToUniversalTime() + "] MQTT: " + e.Message + " on " + e.Topic); Console.WriteLine("-> [" + DateTime.Now.ToUniversalTime() + "] MQTT: " + e.Message + " on " + e.Topic);
} }
private static void Telegram_MessageSending(Object sender, global::Telegram.Bot.Types.Message e) { private static void Telegram_MessageSending(Object sender, TelegramEventArgs e) {
Console.WriteLine("-> [" + e.Date.ToUniversalTime() + "] Telegram: " + e.Text + " on " + e.Chat.Id); Console.WriteLine("-> [" + e.Date.ToUniversalTime() + "] Telegram: " + e.Message + " on " + e.UserId);
} }
private static void Telegram_MessageIncomming(Object sender, global::Telegram.Bot.Types.Message e) { private static void Telegram_MessageIncomming(Object sender, TelegramEventArgs e) {
Console.WriteLine("<- [" + e.Date.ToUniversalTime() + "] Telegram: " + e.Text + " on " + e.Chat.Id); Console.WriteLine("<- [" + e.Date.ToUniversalTime() + "] Telegram: " + e.Message + " on " + e.UserId);
} }
private static void Mqtt_MessageIncomming(ADataBackend sender, MqttEventArgs e) { private static void Mqtt_MessageIncomming(Object sender, MqttEventArgs e) {
Console.WriteLine("<- [" + DateTime.Now.ToUniversalTime() + "] MQTT: " + e.Message + " on " + e.Topic); Console.WriteLine("<- [" + DateTime.Now.ToUniversalTime() + "] MQTT: " + e.Message + " on " + e.Topic);
} }
} }

View File

@ -1,121 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using IoTBot.Connector;
namespace IoTBot.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 = "IoTBot.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
}
}

View File

@ -1,52 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using IoTBot.Connector;
using LitJson;
namespace IoTBot.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'") + "\"}");
}
}
}

View File

@ -1,34 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using IoTBot.Connector;
using LitJson;
namespace IoTBot.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;
}
}
}

View File

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using IoTBot.Connector;
namespace IoTBot.Sensor {
class Luminanz : ASensor {
public Luminanz(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.Int;
}
protected override Boolean UpdateValue(MqttEventArgs e) {
this.GetInt = Int32.Parse(e.Message, new CultureInfo("en-US"));
return true;
}
}
}

View File

@ -1,16 +0,0 @@
using System;
using System.Collections.Generic;
using IoTBot.Connector;
namespace IoTBot.Sensor {
class Pir : ASensor {
public Pir(Dictionary<String, 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;
}
}
}

View File

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using IoTBot.Connector;
namespace IoTBot.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;
}
}
}

View File

@ -1,16 +0,0 @@
using System;
using System.Collections.Generic;
using IoTBot.Connector;
namespace IoTBot.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;
}
}
}

View File

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using IoTBot.Connector;
namespace IoTBot.Sensor {
class Temperatur : ASensor {
public Temperatur(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;
}
}
}

View File

@ -1,38 +1,51 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="M2Mqtt" version="4.3.0.0" targetFramework="net452" /> <package id="M2Mqtt" version="4.3.0.0" targetFramework="net452" />
<package id="Microsoft.NETCore.Platforms" version="1.1.0" targetFramework="net452" /> <package id="Microsoft.NETCore.Platforms" version="2.0.0" targetFramework="net462" />
<package id="Microsoft.Win32.Primitives" version="4.3.0" targetFramework="net462" />
<package id="NETStandard.Library" version="1.6.1" targetFramework="net452" /> <package id="NETStandard.Library" version="1.6.1" targetFramework="net452" />
<package id="Newtonsoft.Json" version="10.0.3" targetFramework="net452" /> <package id="Newtonsoft.Json" version="10.0.3" targetFramework="net452" />
<package id="System.AppContext" version="4.3.0" targetFramework="net462" />
<package id="System.Collections" version="4.3.0" targetFramework="net452" /> <package id="System.Collections" version="4.3.0" targetFramework="net452" />
<package id="System.Collections.Concurrent" version="4.3.0" targetFramework="net452" /> <package id="System.Collections.Concurrent" version="4.3.0" targetFramework="net452" />
<package id="System.Console" version="4.3.0" targetFramework="net462" />
<package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="net452" /> <package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="net452" />
<package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="net452" /> <package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="net452" />
<package id="System.Diagnostics.Tracing" version="4.3.0" targetFramework="net452" /> <package id="System.Diagnostics.Tracing" version="4.3.0" targetFramework="net452" requireReinstallation="true" />
<package id="System.Globalization" version="4.3.0" targetFramework="net452" /> <package id="System.Globalization" version="4.3.0" targetFramework="net452" />
<package id="System.IO" version="4.3.0" targetFramework="net452" /> <package id="System.Globalization.Calendars" version="4.3.0" targetFramework="net462" />
<package id="System.IO.Compression" version="4.3.0" targetFramework="net452" /> <package id="System.IO" version="4.3.0" targetFramework="net452" requireReinstallation="true" />
<package id="System.IO.Compression" version="4.3.0" targetFramework="net452" requireReinstallation="true" />
<package id="System.IO.Compression.ZipFile" version="4.3.0" targetFramework="net462" />
<package id="System.IO.FileSystem" version="4.3.0" targetFramework="net462" />
<package id="System.IO.FileSystem.Primitives" version="4.3.0" targetFramework="net462" />
<package id="System.Linq" version="4.3.0" targetFramework="net452" /> <package id="System.Linq" version="4.3.0" targetFramework="net452" />
<package id="System.Linq.Expressions" version="4.3.0" targetFramework="net452" /> <package id="System.Linq.Expressions" version="4.3.0" targetFramework="net452" />
<package id="System.Net.Http" version="4.3.0" targetFramework="net452" /> <package id="System.Net.Http" version="4.3.3" targetFramework="net462" />
<package id="System.Net.Primitives" version="4.3.0" targetFramework="net452" /> <package id="System.Net.Primitives" version="4.3.0" targetFramework="net452" />
<package id="System.Net.Sockets" version="4.3.0" targetFramework="net462" />
<package id="System.ObjectModel" version="4.3.0" targetFramework="net452" /> <package id="System.ObjectModel" version="4.3.0" targetFramework="net452" />
<package id="System.Reflection" version="4.3.0" targetFramework="net452" /> <package id="System.Reflection" version="4.3.0" targetFramework="net452" requireReinstallation="true" />
<package id="System.Reflection.Extensions" version="4.3.0" targetFramework="net452" /> <package id="System.Reflection.Extensions" version="4.3.0" targetFramework="net452" />
<package id="System.Reflection.Primitives" version="4.3.0" targetFramework="net452" /> <package id="System.Reflection.Primitives" version="4.3.0" targetFramework="net452" />
<package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="net452" /> <package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="net452" />
<package id="System.Runtime" version="4.3.0" targetFramework="net452" /> <package id="System.Runtime" version="4.3.0" targetFramework="net452" requireReinstallation="true" />
<package id="System.Runtime.Extensions" version="4.3.0" targetFramework="net452" /> <package id="System.Runtime.Extensions" version="4.3.0" targetFramework="net452" requireReinstallation="true" />
<package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="net452" /> <package id="System.Runtime.Handles" version="4.3.0" targetFramework="net462" />
<package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="net452" requireReinstallation="true" />
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net452" /> <package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net452" />
<package id="System.Runtime.Numerics" version="4.3.0" targetFramework="net452" /> <package id="System.Runtime.Numerics" version="4.3.0" targetFramework="net452" />
<package id="System.Security.Cryptography.Algorithms" version="4.3.0" targetFramework="net462" />
<package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="net462" />
<package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="net462" />
<package id="System.Security.Cryptography.X509Certificates" version="4.3.0" targetFramework="net462" />
<package id="System.Text.Encoding" version="4.3.0" targetFramework="net452" /> <package id="System.Text.Encoding" version="4.3.0" targetFramework="net452" />
<package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="net452" /> <package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="net452" />
<package id="System.Text.RegularExpressions" version="4.3.0" targetFramework="net452" /> <package id="System.Text.RegularExpressions" version="4.3.0" targetFramework="net452" />
<package id="System.Threading" version="4.3.0" targetFramework="net452" /> <package id="System.Threading" version="4.3.0" targetFramework="net452" />
<package id="System.Threading.Tasks" version="4.3.0" targetFramework="net452" /> <package id="System.Threading.Tasks" version="4.3.0" targetFramework="net452" />
<package id="System.Threading.Timer" version="4.3.0" targetFramework="net452" /> <package id="System.Threading.Timer" version="4.3.0" targetFramework="net452" />
<package id="System.Xml.ReaderWriter" version="4.3.0" targetFramework="net452" /> <package id="System.Xml.ReaderWriter" version="4.3.0" targetFramework="net452" requireReinstallation="true" />
<package id="System.Xml.XDocument" version="4.3.0" targetFramework="net452" /> <package id="System.Xml.XDocument" version="4.3.0" targetFramework="net452" />
<package id="Telegram.Bot" version="13.1.0" targetFramework="net452" /> <package id="Telegram.Bot" version="13.2.1" targetFramework="net462" />
</packages> </packages>