Removing the folders that are now repositories

This commit is contained in:
BlubbFish 2019-02-14 17:28:48 +01:00
parent 2d4d4e28ea
commit eeece2a050
17 changed files with 0 additions and 980 deletions

View File

@ -1,43 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.136
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bot-Utils", "Bot-Utils\Bot-Utils.csproj", "{BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "litjson_4.7.1", "..\..\Librarys\litjson\litjson\litjson_4.7.1.csproj", "{91A14CD2-2940-4500-8193-56D37EDDDBAA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Utils-IoT", "..\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
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}.Release|Any CPU.Build.0 = Release|Any CPU
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{91A14CD2-2940-4500-8193-56D37EDDDBAA}.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
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {99DB6F34-BD41-4AFF-82B7-E4B3EFDF56DC}
EndGlobalSection
EndGlobal

View File

@ -1,82 +0,0 @@
<?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>{BB7BFCB5-3DB0-49E1-802A-3CE3EECC59F9}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>BlubbFish.Utils.IoT.Bots</RootNamespace>
<AssemblyName>Bot-Utils</AssemblyName>
<TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<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' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="Mono.Posix">
<HintPath>..\..\Zway-Bot\packages\Mono.Posix.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Bot.cs" />
<Compile Include="Events\CronEvent.cs" />
<Compile Include="Events\ModulEventArgs.cs" />
<Compile Include="Events\SenmlEvent.cs" />
<Compile Include="Events\MqttEvent.cs" />
<Compile Include="Events\OvertakerEvent.cs" />
<Compile Include="Events\StatusPollingEvent.cs" />
<Compile Include="Interfaces\IForceLoad.cs" />
<Compile Include="Moduls\AModul.cs" />
<Compile Include="Moduls\CronJob.cs" />
<Compile Include="Moduls\Mqtt.cs" />
<Compile Include="Moduls\Overtaker.cs" />
<Compile Include="Moduls\Statuspolling.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Webserver.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\Librarys\litjson\litjson\litjson_4.7.1.csproj">
<Project>{91a14cd2-2940-4500-8193-56d37edddbaa}</Project>
<Name>litjson_4.7.1</Name>
</ProjectReference>
<ProjectReference Include="..\..\Utils-IoT\Utils-IoT\Utils-IoT.csproj">
<Project>{b870e4d5-6806-4a0b-b233-8907eedc5afc}</Project>
<Name>Utils-IoT</Name>
</ProjectReference>
<ProjectReference Include="..\..\Utils\Utils\Utils.csproj">
<Project>{fac8ce64-bf13-4ece-8097-aeb5dd060098}</Project>
<Name>Utils</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -1,99 +0,0 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using BlubbFish.Utils.IoT.Bots.Moduls;
using BlubbFish.Utils.IoT.Bots.Events;
using BlubbFish.Utils.IoT.Bots.Interfaces;
namespace BlubbFish.Utils.IoT.Bots {
public abstract class Bot<T> {
private Thread sig_thread;
private Boolean RunningProcess = true;
protected ProgramLogger logger = new ProgramLogger();
protected readonly Dictionary<String, AModul<T>> moduls = new Dictionary<String, AModul<T>>();
protected void WaitForShutdown() {
if (Type.GetType("Mono.Runtime") != null) {
this.sig_thread = new Thread(delegate () {
Mono.Unix.UnixSignal[] signals = new Mono.Unix.UnixSignal[] {
new Mono.Unix.UnixSignal(Mono.Unix.Native.Signum.SIGTERM),
new Mono.Unix.UnixSignal(Mono.Unix.Native.Signum.SIGINT)
};
Console.WriteLine("BlubbFish.Utils.IoT.Bots.Bot.WaitForShutdown: Signalhandler Mono attached.");
while (true) {
Int32 i = Mono.Unix.UnixSignal.WaitAny(signals, -1);
Console.WriteLine("BlubbFish.Utils.IoT.Bots.Bot.WaitForShutdown: Signalhandler Mono INT recieved " + i + ".");
this.RunningProcess = false;
break;
}
});
this.sig_thread.Start();
} else {
Console.CancelKeyPress += new ConsoleCancelEventHandler(this.SetupShutdown);
Console.WriteLine("BlubbFish.Utils.IoT.Bots.Bot.WaitForShutdown: Signalhandler Windows attached.");
}
while (this.RunningProcess) {
Thread.Sleep(100);
}
}
private void SetupShutdown(Object sender, ConsoleCancelEventArgs e) {
e.Cancel = true;
Console.WriteLine("BlubbFish.Utils.IoT.Bots.Bot.SetupShutdown: Signalhandler Windows INT recieved.");
this.RunningProcess = false;
}
protected void ModulDispose() {
foreach (KeyValuePair<String, AModul<T>> item in this.moduls) {
item.Value.Dispose();
Console.WriteLine("BlubbFish.Utils.IoT.Bots.Bot.ModulDispose: Modul entladen: " + item.Key);
}
if (this.sig_thread != null && this.sig_thread.IsAlive) {
this.sig_thread.Abort();
}
}
protected void ModulLoader(String @namespace, Object library) {
Assembly asm = Assembly.GetEntryAssembly();
foreach (Type item in asm.GetTypes()) {
if (item.Namespace == @namespace) {
Type t = item;
String name = t.Name;
try {
if (InIReader.ConfigExist(name.ToLower())) {
Console.WriteLine("BlubbFish.Utils.IoT.Bots.Bot.ModulLoader: Load Modul " + name);
this.moduls.Add(name, (AModul<T>)t.GetConstructor(new Type[] { typeof(T), typeof(InIReader) }).Invoke(new Object[] { library, InIReader.GetInstance(name.ToLower()) }));
Console.WriteLine("BlubbFish.Utils.IoT.Bots.Bot.ModulLoader: Loaded Modul " + name);
} else if (t.HasInterface(typeof(IForceLoad))) {
Console.WriteLine("BlubbFish.Utils.IoT.Bots.Bot.ModulLoader: Load Modul Forced " + name);
this.moduls.Add(name, (AModul<T>)t.GetConstructor(new Type[] { typeof(T), typeof(InIReader) }).Invoke(new Object[] { library, null }));
Console.WriteLine("BlubbFish.Utils.IoT.Bots.Bot.ModulLoader: Loaded Modul Forced " + name);
}
} catch(Exception e) {
Helper.WriteError(e.InnerException.Message);
}
}
}
}
protected void ModulInterconnect() {
foreach (KeyValuePair<String, AModul<T>> item in this.moduls) {
item.Value.Interconnect(this.moduls);
Console.WriteLine("BlubbFish.Utils.IoT.Bots.Bot.ModulInterconnect: Interconnect Module " + item.Key);
}
}
protected void ModulEvents() {
foreach (KeyValuePair<String, AModul<T>> item in this.moduls) {
item.Value.EventLibSetter();
item.Value.Update += this.ModulUpdate;
Console.WriteLine("BlubbFish.Utils.IoT.Bots.Bot.ModulEvents: Attach Event " + item.Key);
}
}
protected void ModulUpdate(Object sender, ModulEventArgs e) {
Console.WriteLine(e.ToString());
}
}
}

View File

@ -1,16 +0,0 @@
using System;
namespace BlubbFish.Utils.IoT.Bots.Events {
public class CronEvent : ModulEventArgs {
public CronEvent() {
}
public CronEvent(String addr, String prop, String value) {
this.Address = addr;
this.Property = prop;
this.Value = value;
this.Source = "Cronjob";
}
}
}

View File

@ -1,21 +0,0 @@
using System;
namespace BlubbFish.Utils.IoT.Bots.Events {
public class ModulEventArgs : EventArgs {
public ModulEventArgs() {
}
public ModulEventArgs(String addr, String prop, String val, String src) {
this.Address = addr;
this.Property = prop;
this.Value = val;
this.Source = src;
}
public String Address { get; protected set; }
public String Property { get; protected set; }
public String Value { get; protected set; }
public String Source { get; protected set; }
public override String ToString() {
return this.Source + ": " + this.Address + " set " + this.Property + " to " + this.Value;
}
}
}

View File

@ -1,16 +0,0 @@
using System;
namespace BlubbFish.Utils.IoT.Bots.Events {
public class MqttEvent : ModulEventArgs {
public MqttEvent() {
}
public MqttEvent(String topic, String text) {
this.Address = topic;
this.Value = text;
this.Source = "MQTT";
}
public override String ToString() {
return this.Source + ": on " + this.Address + " set " + this.Value;
}
}
}

View File

@ -1,16 +0,0 @@
using System;
namespace BlubbFish.Utils.IoT.Bots.Events {
public class OvertakerEvent : ModulEventArgs {
public OvertakerEvent() {
}
public OvertakerEvent(String addr, String prop, String value) {
this.Address = addr;
this.Property = prop;
this.Value = value;
this.Source = "Overtaker";
}
}
}

View File

@ -1,16 +0,0 @@
using System;
namespace BlubbFish.Utils.IoT.Bots.Events {
public class SenmlEvent : ModulEventArgs {
public SenmlEvent() {
}
public SenmlEvent(String topic, String text) {
this.Address = topic;
this.Value = text;
this.Source = "Senml";
}
public override String ToString() {
return this.Source + ": on " + this.Address + " set " + this.Value;
}
}
}

View File

@ -1,18 +0,0 @@
using System;
namespace BlubbFish.Utils.IoT.Bots.Events {
public class StatusPollingEvent : ModulEventArgs {
public StatusPollingEvent() {
}
public StatusPollingEvent(String text, String node) {
this.Value = text;
this.Address = node;
this.Source = "POLLING";
}
public override String ToString() {
return this.Source + ": " + this.Value + " on " + this.Address;
}
}
}

View File

@ -1,4 +0,0 @@
namespace BlubbFish.Utils.IoT.Bots.Interfaces {
public interface IForceLoad {
}
}

View File

@ -1,79 +0,0 @@
using System;
using System.Collections.Generic;
using System.Threading;
using BlubbFish.Utils.IoT.Bots.Events;
namespace BlubbFish.Utils.IoT.Bots.Moduls {
public abstract class AModul<T> {
protected T library;
private readonly InIReader settings;
protected Dictionary<String, Dictionary<String, String>> config = new Dictionary<String, Dictionary<String, String>>();
public Boolean HasConfig { get; private set; }
public Boolean ConfigPublic { get; private set; }
public delegate void ModulEvent(Object sender, ModulEventArgs e);
public abstract event ModulEvent Update;
public AModul(T lib, InIReader settings) {
this.HasConfig = false;
this.ConfigPublic = false;
this.library = lib;
this.settings = settings;
this.ParseConfig();
}
private void ParseConfig() {
if (this.settings != null) {
this.HasConfig = true;
foreach (String item in this.settings.GetSections(false)) {
this.config.Add(item, this.settings.GetSection(item));
}
if (this.config.ContainsKey("modul")) {
this.ConfigPublic = this.config["modul"].ContainsKey("config") && this.config["modul"]["config"].ToLower() == "public";
}
}
}
public Dictionary<String, Dictionary<String, String>> GetConfig() {
if (this.HasConfig && this.ConfigPublic) {
Dictionary<String, Dictionary<String, String>> ret = new Dictionary<String, Dictionary<String, String>>(this.config);
if (ret.ContainsKey("modul")) {
ret.Remove("modul");
}
return ret;
}
return new Dictionary<String, Dictionary<String, String>>();
}
public virtual void Interconnect(Dictionary<String, AModul<T>> moduls) { }
public virtual void SetInterconnection(String param, Action<Object> hook, Object data) { }
public abstract void EventLibSetter();
protected abstract void LibUpadteThread(Object state);
protected void HandleLibUpdate(Object sender, EventArgs e) {
ThreadPool.QueueUserWorkItem(this.LibUpadteThread, e);
}
public abstract void Dispose();
public void SetConfig(Dictionary<String, Dictionary<String, String>> newconf) {
if (this.HasConfig && this.ConfigPublic) {
if (newconf.ContainsKey("modul")) {
newconf.Remove("modul");
}
if (this.config.ContainsKey("modul")) {
newconf.Add("modul", this.config["modul"]);
}
this.config = newconf;
this.settings.SetSections(this.config);
this.UpdateConfig();
}
}
protected abstract void UpdateConfig();
}
}

View File

@ -1,172 +0,0 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Threading;
using BlubbFish.Utils.IoT.Bots.Interfaces;
namespace BlubbFish.Utils.IoT.Bots.Moduls {
public abstract class CronJob<T> : AModul<T>, IDisposable, IForceLoad {
protected readonly List<Tuple<String, Action<Object>, Object>> internalCron = new List<Tuple<String, Action<Object>, Object>>();
protected Thread thread;
protected DateTime crontime;
protected readonly Dictionary<String, String> cron_named = new Dictionary<String, String> {
{ "@yearly", "0 0 1 1 *" },
{ "@annually", "0 0 1 1 *" },
{ "@monthly", "0 0 1 * *" },
{ "@weekly", "0 0 * * 0" },
{ "@daily", "0 0 * * *" },
{ "@hourly", "0 * * * *" }
};
#region Constructor
public CronJob(T lib, InIReader settings) : base(lib, settings) {
this.crontime = DateTime.Now;
this.thread = new Thread(this.Runner);
this.thread.Start();
}
#endregion
#region Cronjobrunner
protected void Runner() {
Thread.Sleep(DateTime.Now.AddMinutes(1).AddSeconds(DateTime.Now.Second * (-1)).AddMilliseconds(DateTime.Now.Millisecond * (-1)) - DateTime.Now);
while (true) {
if (this.crontime.Minute != DateTime.Now.Minute) {
this.crontime = DateTime.Now;
if (this.config.Count != 0) {
foreach (KeyValuePair<String, Dictionary<String, String>> item in this.config) {
if (item.Value.ContainsKey("cron") && item.Value.ContainsKey("set") && this.ParseCronString(item.Value["cron"])) {
this.SetValues(item.Value["set"]);
}
}
}
foreach (Tuple<String, Action<Object>, Object> item in this.internalCron) {
if (this.ParseCronString(item.Item1)) {
item.Item2?.Invoke(item.Item3);
}
}
}
Thread.Sleep(100);
}
}
protected abstract void SetValues(String value);
#endregion
#region CronFunctions
protected Boolean ParseCronString(String cronstring) {
cronstring = cronstring.Trim();
if (this.cron_named.ContainsKey(cronstring)) {
cronstring = this.cron_named[cronstring];
}
String[] value = cronstring.Split(' ');
if (value.Length != 5) {
return false;
}
if (!this.CheckDateStr(this.crontime.ToString("mm"), value[0], "0-59")) {
return false;
}
if (!this.CheckDateStr(this.crontime.ToString("HH"), value[1], "0-23")) {
return false;
}
if (!this.CheckDateStr(this.crontime.ToString("MM"), value[3], "1-12")) {
return false;
}
if (value[2] != "*" && value[4] != "*") {
if (!this.CheckDateStr(this.crontime.ToString("dd"), value[2], "1-31") && !this.CheckDateStr(((Int32)this.crontime.DayOfWeek).ToString(), value[4], "0-7")) {
return false;
}
} else {
if (!this.CheckDateStr(this.crontime.ToString("dd"), value[2], "1-31")) {
return false;
}
if (!this.CheckDateStr(((Int32)this.crontime.DayOfWeek).ToString(), value[4], "0-7")) {
return false;
}
}
return true;
}
protected Boolean CheckDateStr(String date, String cron, String limit) {
cron = cron.ToLower();
for (Int32 i = 0; i <= 6; i++) {
cron = cron.Replace(DateTime.Parse("2015-01-" + (4 + i) + "T00:00:00").ToString("ddd", CultureInfo.CreateSpecificCulture("en-US")), i.ToString());
cron = cron.Replace(DateTime.Parse("2015-01-" + (4 + i) + "T00:00:00").ToString("dddd", CultureInfo.CreateSpecificCulture("en-US")), i.ToString());
}
for (Int32 i = 1; i <= 12; i++) {
cron = cron.Replace(DateTime.Parse("2015-" + i + "-01T00:00:00").ToString("MMM", CultureInfo.CreateSpecificCulture("en-US")), i.ToString());
cron = cron.Replace(DateTime.Parse("2015-" + i + "-01T00:00:00").ToString("MMMM", CultureInfo.CreateSpecificCulture("en-US")), i.ToString());
}
if (cron.Contains("*")) {
cron = cron.Replace("*", limit);
}
if (cron.Contains("-")) {
MatchCollection m = new Regex("(\\d+)-(\\d+)").Matches(cron);
foreach (Match p in m) {
List<String> s = new List<String>();
for (Int32 i = Math.Min(Int32.Parse(p.Groups[1].Value), Int32.Parse(p.Groups[2].Value)); i <= Math.Max(Int32.Parse(p.Groups[1].Value), Int32.Parse(p.Groups[2].Value)); i++) {
s.Add(i.ToString());
}
cron = cron.Replace(p.Groups[0].Value, String.Join(",", s));
}
}
Int32 match = 0;
if (cron.Contains("/")) {
Match m = new Regex("/(\\d+)").Match(cron);
cron = cron.Replace(m.Groups[0].Value, "");
match = Int32.Parse(m.Groups[1].Value);
}
Dictionary<Int32, String> ret = new Dictionary<Int32, String>();
if (!cron.Contains(",")) {
ret.Add(Int32.Parse(cron), "");
} else {
foreach (String item in cron.Split(',')) {
if (!ret.ContainsKey(Int32.Parse(item))) {
ret.Add(Int32.Parse(item), "");
}
}
}
if (match != 0) {
Dictionary<Int32, String> r = new Dictionary<Int32, String>();
foreach (KeyValuePair<Int32, String> item in ret) {
if (item.Key % match == 0) {
r.Add(item.Key, "");
}
}
ret = r;
}
return ret.ContainsKey(Int32.Parse(date));
}
#endregion
#region AModul
public override void SetInterconnection(String cron, Action<Object> hook, Object data) {
this.internalCron.Add(new Tuple<String, Action<Object>, Object>(cron, hook, data));
}
protected override void UpdateConfig() { }
#endregion
#region IDisposable Support
private Boolean disposedValue = false;
protected virtual void Dispose(Boolean disposing) {
if (!this.disposedValue) {
if (disposing) {
if (this.thread != null) {
this.thread.Abort();
while (this.thread.ThreadState == ThreadState.Running) { Thread.Sleep(100); }
}
}
this.thread = null;
this.disposedValue = true;
}
}
public override void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}

View File

@ -1,119 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using BlubbFish.Utils.IoT.Bots.Events;
using BlubbFish.Utils.IoT.Connector;
using BlubbFish.Utils.IoT.Events;
using LitJson;
namespace BlubbFish.Utils.IoT.Bots.Moduls {
public abstract class Mqtt<T> : AModul<T>, IDisposable {
protected readonly Thread connectionWatcher;
protected ABackend mqtt;
protected Dictionary<String, AModul<T>> modules;
#region Constructor
public Mqtt(T lib, InIReader settings) : base(lib, settings) {
if (this.config.ContainsKey("settings")) {
this.connectionWatcher = new Thread(this.ConnectionWatcherRunner);
this.connectionWatcher.Start();
} else {
throw new ArgumentException("Setting section [settings] is missing!");
}
}
#endregion
#region Watcher
protected void ConnectionWatcherRunner() {
while (true) {
try {
if (this.mqtt == null || !this.mqtt.IsConnected) {
this.Reconnect();
}
Thread.Sleep(10000);
} catch (Exception) { }
}
}
protected void Reconnect() {
Console.WriteLine("BlubbFish.Utils.IoT.Bots.Moduls.Mqtt.Reconnect()");
this.Disconnect();
this.Connect();
}
protected abstract void Connect();
protected abstract void Disconnect();
#endregion
#region AModul
public override void Interconnect(Dictionary<String, AModul<T>> moduls) {
this.modules = moduls;
}
protected override void UpdateConfig() {
this.Reconnect();
}
#endregion
protected Tuple<Boolean, MqttEvent> ChangeConfig(BackendEvent e, String topic) {
if (e.From.ToString().StartsWith(topic) && (e.From.ToString().EndsWith("/set") || e.From.ToString().EndsWith("/get"))) {
Match m = new Regex("^"+ topic + "(\\w+)/[gs]et$|").Match(e.From.ToString());
if (!m.Groups[1].Success) {
return new Tuple<Boolean, MqttEvent>(false, null);
}
AModul<T> modul = null;
foreach (KeyValuePair<String, AModul<T>> item in this.modules) {
if (item.Key.ToLower() == m.Groups[1].Value) {
modul = item.Value;
}
}
if (modul == null) {
return new Tuple<Boolean, MqttEvent>(false, null);
}
if (e.From.ToString().EndsWith("/get") && modul.HasConfig && modul.ConfigPublic) {
String t = topic + m.Groups[1].Value;
String d = JsonMapper.ToJson(modul.GetConfig()).ToString();
((ADataBackend)this.mqtt).Send(t, d);
return new Tuple<Boolean, MqttEvent>(true, new MqttEvent(t, d));
} else if (e.From.ToString().EndsWith("/set") && modul.HasConfig && modul.ConfigPublic) {
try {
JsonData a = JsonMapper.ToObject(e.Message);
Dictionary<String, Dictionary<String, String>> newconf = new Dictionary<String, Dictionary<String, String>>();
foreach (String section in a.Keys) {
Dictionary<String, String> sectiondata = new Dictionary<String, String>();
foreach (String item in a[section].Keys) {
sectiondata.Add(item, a[section][item].ToString());
}
newconf.Add(section, sectiondata);
}
modul.SetConfig(newconf);
return new Tuple<Boolean, MqttEvent>(true, new MqttEvent("New Config", "Write"));
} catch (Exception) { }
}
}
return new Tuple<Boolean, MqttEvent>(false, null);
}
#region IDisposable Support
private Boolean disposedValue = false;
protected void Dispose(Boolean disposing) {
if (!this.disposedValue) {
if (disposing) {
this.connectionWatcher.Abort();
while (this.connectionWatcher.ThreadState == ThreadState.Running) { Thread.Sleep(10); }
this.Disconnect();
}
this.disposedValue = true;
}
}
public override void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}

View File

@ -1,88 +0,0 @@
using System;
using System.Collections.Generic;
namespace BlubbFish.Utils.IoT.Bots.Moduls {
public abstract class Overtaker<T> : AModul<T>, IDisposable {
protected readonly Dictionary<String, Dictionary<String, String>> events = new Dictionary<String, Dictionary<String, String>>();
#region Constructor
public Overtaker(T lib, InIReader settings) : base(lib, settings) {
this.ParseIni();
}
#endregion
#region Overtakerfunctions
protected void ParseIni() {
this.RemoveLibraryUpdateHooks();
foreach (KeyValuePair<String, Dictionary<String, String>> item in this.config) {
if (item.Value.ContainsKey("from")) {
String from = item.Value["from"];
String[] source = from.Split(':');
this.events.Add(source[0], item.Value);
this.AddLibraryUpdateHook(source[0]);
}
}
}
protected void SetValues(Object sender, String name, Dictionary<String, String> dictionary) {
String from = dictionary["from"];
String[] source = from.Split(':');
if (source.Length != 2) {
return;
}
String source_value;
if (sender.HasProperty(source[1])) {
source_value = sender.GetProperty(source[1]).ToString();
} else {
return;
}
if (dictionary.ContainsKey("convert")) {
foreach (String tuple in dictionary["convert"].Split(';')) {
String[] item = tuple.Split('-');
if (source_value == item[0]) {
source_value = item[1];
}
}
}
if (dictionary.ContainsKey("to")) {
foreach (String to in dictionary["to"].Split(';')) {
String[] target = to.Split(':');
if (target.Length == 2) {
this.SetValueHook(target[0], target[1], source_value);
}
}
}
}
protected abstract void AddLibraryUpdateHook(String id);
protected abstract void RemoveLibraryUpdateHooks();
protected abstract void SetValueHook(String id, String prop, String value);
#endregion
#region AModul
public override void Interconnect(Dictionary<String, AModul<T>> moduls) { }
protected override void UpdateConfig() {
this.ParseIni();
}
#endregion
#region IDisposable Support
private Boolean disposedValue = false;
protected virtual void Dispose(Boolean disposing) {
if (!this.disposedValue) {
if (disposing) {
}
this.disposedValue = true;
}
}
public override void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}

View File

@ -1,53 +0,0 @@
using System;
using System.Collections.Generic;
using BlubbFish.Utils.IoT.Bots.Interfaces;
namespace BlubbFish.Utils.IoT.Bots.Moduls {
public abstract class Statuspolling<T> : AModul<T>, IDisposable, IForceLoad {
#region Constructor
public Statuspolling(T lib, InIReader settings) : base(lib, settings) { }
#endregion
#region Statuspollingfunctions
protected abstract void PollSpecific(Object obj);
protected abstract void PollAll(Object obj);
#endregion
#region AModul
public override void Interconnect(Dictionary<String, AModul<T>> moduls) {
foreach (KeyValuePair<String, AModul<T>> item in moduls) {
if (item.Value is CronJob<T>) {
item.Value.SetInterconnection("0 0 * * *", new Action<Object>(this.PollAll), null);
if (this.config.Count != 0) {
foreach (KeyValuePair<String, Dictionary<String, String>> section in this.config) {
if (section.Value.ContainsKey("cron") && section.Value.ContainsKey("devices")) {
item.Value.SetInterconnection(section.Value["cron"], new Action<Object>(this.PollSpecific), section.Value["devices"]);
}
}
}
}
}
}
protected override void UpdateConfig() { }
#endregion
#region IDisposable Support
private Boolean disposedValue = false;
protected virtual void Dispose(Boolean disposing) {
if (!this.disposedValue) {
if (disposing) {
}
this.disposedValue = true;
}
}
public override void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}

View File

@ -1,40 +0,0 @@
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("Bot-Utils")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Bot-Utils")]
[assembly: AssemblyCopyright("Copyright © 2018 - 02.10.2018")]
[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("bb7bfcb5-3db0-49e1-802a-3ce3eecc59f9")]
// 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,
// indem Sie "*" wie unten gezeigt eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0")]
[assembly: AssemblyFileVersion("1.1.0")]
/*
* 1.1.0 Remove Helper from Bot-Utils
*/

View File

@ -1,98 +0,0 @@
using BlubbFish.Utils.IoT.Connector;
using BlubbFish.Utils.IoT.Events;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace BlubbFish.Utils.IoT.Bots
{
public abstract class Webserver
{
protected Dictionary<String, String> config;
protected InIReader requests;
protected HttpListener httplistener;
public Webserver(ABackend backend, Dictionary<String, String> settings, InIReader requests) {
this.config = settings;
this.requests = requests;
backend.MessageIncomming += this.Backend_MessageIncomming;
this.httplistener = new HttpListener();
this.httplistener.Prefixes.Add(this.config["prefix"]);
this.httplistener.Start();
ThreadPool.QueueUserWorkItem((o) => {
Console.WriteLine("Webserver is Running...");
try {
while (this.httplistener.IsListening) {
ThreadPool.QueueUserWorkItem((state) => {
HttpListenerContext httplistenercontext = state as HttpListenerContext;
try {
this.SendResponse(httplistenercontext);
} catch { } finally {
httplistenercontext.Response.OutputStream.Close();
}
}, this.httplistener.GetContext());
}
} catch { };
});
}
protected virtual void SendResponse(HttpListenerContext cont) {
String restr = cont.Request.Url.PathAndQuery;
if (restr.StartsWith("/")) {
if(restr.IndexOf("?") != -1) {
restr = restr.Substring(1, restr.IndexOf("?")-1);
} else {
restr = restr.Substring(1);
}
if(restr == "") {
restr = "index.html";
}
String end = restr.IndexOf('.') != -1 ? restr.Substring(restr.IndexOf('.')+1) : "";
if (File.Exists("resources/"+ restr)) {
try {
if (end == "png" || end == ".jpg" || end == ".jpeg" || end == ".ico") {
Byte[] output = File.ReadAllBytes("resources/" + restr);
cont.Response.OutputStream.Write(output, 0, output.Length);
cont.Response.ContentType = "image/"+end;
return;
} else {
String file = File.ReadAllText("resources/" + restr);
if (this.requests.GetSections(false).Contains(restr)) {
Dictionary<String, String> vars = this.requests.GetSection(restr);
foreach (KeyValuePair<String, String> item in vars) {
file = file.Replace("{%" + item.Key.ToUpper() + "%}", item.Value);
}
}
file = file.Replace("{%REQUEST_URL_HOST%}", cont.Request.Url.Host);
Byte[] buf = Encoding.UTF8.GetBytes(file);
cont.Response.ContentLength64 = buf.Length;
cont.Response.OutputStream.Write(buf, 0, buf.Length);
Console.WriteLine("200 - " + cont.Request.Url.PathAndQuery);
return;
}
} catch(Exception e) {
Helper.WriteError("500 - " + e.Message);
cont.Response.StatusCode = 500;
return;
}
}
Helper.WriteError("404 - " + cont.Request.Url.PathAndQuery + " not found!");
cont.Response.StatusCode = 404;
return;
}
return;
}
public void Dispose() {
this.httplistener.Stop();
this.httplistener.Close();
}
protected abstract void Backend_MessageIncomming(Object sender, BackendEvent e);
}
}