Compare commits

..

No commits in common. "master" and "1.0.8" have entirely different histories.

114 changed files with 2691 additions and 8680 deletions

4
.gitignore vendored
View file

@ -1,4 +0,0 @@
bin/
obj/
packages/
.vs

View file

@ -1,3 +0,0 @@
# Contributing
When you contribute code, you affirm that the contribution is your original work and that you license the work to the project under the project's open source license. Whether or not you state this explicitly, by submitting any copyrighted material via pull request, email, or other means you agree to license the material under the project's open source license and warrant that you have the legal authority to do so.

View file

@ -1,39 +0,0 @@
FROM mono:latest AS build
ARG TARGETPLATFORM
ENV TARGETPLATFORM=${TARGETPLATFORM:-linux/amd64}
RUN apt-get update && \
apt-get install -y unixodbc
WORKDIR /build
ADD https://dev.mysql.com/get/Downloads/Connector-ODBC/8.0/mysql-connector-odbc-8.0.18-linux-debian9-x86-64bit.tar.gz /build
RUN if [ "$TARGETPLATFORM" = "linux/amd64" ]; then \
tar zxf mysql-connector-odbc-8.0.18-linux-debian9-x86-64bit.tar.gz && \
mkdir -p /usr/lib/odbc/ && \
cp mysql-connector-odbc-8.0.18-linux-debian9-x86-64bit/lib/* /usr/lib/odbc/ && \
mysql-connector-odbc-8.0.18-linux-debian9-x86-64bit/bin/myodbc-installer -d -a -n "MySQL" -t "DRIVER=/usr/lib/odbc/libmyodbc8w.so"; \
else \
mkdir -p /usr/lib/odbc/ && \
touch /etc/odbcinst.ini; \
fi
COPY . .
RUN nuget restore /build/OmniLinkBridge.sln
RUN msbuild /build/OmniLinkBridge.sln /t:Build /p:Configuration=Release
RUN mv /build/OmniLinkBridge/bin/Release /app
FROM mono:latest AS runtime
RUN apt-get update && \
apt-get install -y unixodbc
COPY --from=build /usr/lib/odbc /usr/lib/odbc
COPY --from=build /etc/odbcinst.ini /etc/odbcinst.ini
COPY --from=build /app/OmniLinkBridge.ini /config/OmniLinkBridge.ini
EXPOSE 8000/tcp
VOLUME /config
WORKDIR /app
COPY --from=build /app .
CMD [ "mono", "OmniLinkBridge.exe", "-i", "-c", "/config/OmniLinkBridge.ini", "-e", "-s", "/config/WebSubscriptions.json", "-lf", "disable" ]

22
HAILogger.sln Normal file
View file

@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25123.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HAILogger", "HAILogger\HAILogger.csproj", "{0A636707-98BA-45AB-9843-AED430933CEE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0A636707-98BA-45AB-9843-AED430933CEE}.Debug|x86.ActiveCfg = Debug|x86
{0A636707-98BA-45AB-9843-AED430933CEE}.Debug|x86.Build.0 = Debug|x86
{0A636707-98BA-45AB-9843-AED430933CEE}.Release|x86.ActiveCfg = Release|x86
{0A636707-98BA-45AB-9843-AED430933CEE}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

16
HAILogger/App.config Normal file
View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.diagnostics>
<switches>
<!-- This switch controls data messages. In order to receive data
trace messages, change value="0" to value="1" -->
<add name="DataMessagesSwitch" value="0"/>
<!-- This switch controls general messages. In order to
receive general trace messages change the value to the
appropriate level. "1" gives error messages, "2" gives errors
and warnings, "3" gives more detailed error information, and
"4" gives verbose trace information -->
<add name="TraceLevelSwitch" value="3"/>
</switches>
</system.diagnostics>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

View file

@ -1,6 +1,6 @@
using System.Runtime.Serialization; using System.Runtime.Serialization;
namespace OmniLinkBridge.WebAPI namespace HAILogger
{ {
[DataContract] [DataContract]
public class AreaContract public class AreaContract

View file

@ -1,6 +1,6 @@
using System.Runtime.Serialization; using System.Runtime.Serialization;
namespace OmniLinkBridge.WebAPI namespace HAILogger
{ {
[DataContract] [DataContract]
public class CommandContract public class CommandContract

1245
HAILogger/CoreServer.cs Normal file

File diff suppressed because it is too large Load diff

165
HAILogger/Event.cs Normal file
View file

@ -0,0 +1,165 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Mail;
namespace HAILogger
{
static class Event
{
public static void WriteVerbose(string value)
{
Trace.WriteLine(value);
LogFile(TraceLevel.Verbose, "VERBOSE", value);
}
public static void WriteVerbose(string source, string value)
{
Trace.WriteLine("VERBOSE: " + source + ": " + value);
LogFile(TraceLevel.Verbose, "VERBOSE: " + source, value);
}
public static void WriteInfo(string source, string value, bool alert)
{
WriteInfo(source, value);
if (alert)
{
LogEvent(EventLogEntryType.Information, source, value);
SendMail("Info", source, value);
}
}
public static void WriteInfo(string source, string value)
{
Trace.WriteLine("INFO: " + source + ": " + value);
LogFile(TraceLevel.Info, "INFO: " + source, value);
}
public static void WriteWarn(string source, string value, bool alert)
{
WriteWarn(source, value);
if (alert)
SendMail("Warn", source, value);
}
public static void WriteWarn(string source, string value)
{
Trace.WriteLine("WARN: " + source + ": " + value);
LogFile(TraceLevel.Warning, "WARN: " + source, value);
LogEvent(EventLogEntryType.Warning, source, value);
}
public static void WriteError(string source, string value)
{
Trace.WriteLine("ERROR: " + source + ": " + value);
LogFile(TraceLevel.Error, "ERROR: " + source, value);
LogEvent(EventLogEntryType.Error, source, value);
SendMail("Error", source, value);
}
public static void WriteAlarm(string source, string value)
{
Trace.WriteLine("ALARM: " + source + ": " + value);
LogFile(TraceLevel.Error, "ALARM: " + source, value);
LogEvent(EventLogEntryType.Warning, source, value);
if (Global.mail_alarm_to != null && Global.mail_alarm_to.Length > 0)
{
MailMessage mail = new MailMessage();
mail.From = Global.mail_from;
foreach (MailAddress address in Global.mail_alarm_to)
mail.To.Add(address);
mail.Priority = MailPriority.High;
mail.Subject = value;
mail.Body = value;
SmtpClient smtp = new SmtpClient(Global.mail_server, Global.mail_port);
if (!string.IsNullOrEmpty(Global.mail_username))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(Global.mail_username, Global.mail_password);
}
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
string error = "An error occurred sending email notification\r\n" + ex.Message;
LogFile(TraceLevel.Error, "ERROR: " + source, error);
LogEvent(EventLogEntryType.Error, "EventNotification", error);
}
}
}
private static void SendMail(string level, string source, string value)
{
if (Global.mail_to == null || Global.mail_to.Length == 0)
return;
MailMessage mail = new MailMessage();
mail.From = Global.mail_from;
foreach (MailAddress address in Global.mail_to)
mail.To.Add(address);
mail.Subject = Global.event_source + " - " + level;
mail.Body = source + ": " + value;
SmtpClient smtp = new SmtpClient(Global.mail_server, Global.mail_port);
if (!string.IsNullOrEmpty(Global.mail_username))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(Global.mail_username, Global.mail_password);
}
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
string error = "An error occurred sending email notification\r\n" + ex.Message;
LogFile(TraceLevel.Error, "ERROR: " + source, error);
LogEvent(EventLogEntryType.Error, "EventNotification", error);
}
}
private static void LogEvent(EventLogEntryType type, string source, string value)
{
string event_log = "Application";
if (!EventLog.SourceExists(Global.event_source))
EventLog.CreateEventSource(Global.event_source, event_log);
string event_msg = source + ": " + value;
EventLog.WriteEntry(Global.event_source, event_msg, type, 234);
}
private static void LogFile(TraceLevel level, string source, string value)
{
TraceSwitch tswitch = new TraceSwitch("TraceLevelSwitch", "Trace Level for Entire Application");
if (tswitch.Level < level)
return;
try
{
FileStream fs = new FileStream(Global.log_file, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss ") + source + ": " + value);
sw.Close();
fs.Close();
}
catch
{
LogEvent(EventLogEntryType.Error, "EventLogger", "Unable to write to the file log.");
}
}
}
}

54
HAILogger/Global.cs Normal file
View file

@ -0,0 +1,54 @@
using System.Net.Mail;
namespace HAILogger
{
public abstract class Global
{
// Events
public static string event_source;
// Files
public static string config_file;
public static string log_file;
// HAI Controller
public static string hai_address;
public static int hai_port;
public static string hai_key1;
public static string hai_key2;
public static bool hai_time_sync;
public static int hai_time_interval;
public static int hai_time_drift;
// mySQL Database
public static bool mysql_logging;
public static string mysql_connection;
// Events
public static string mail_server;
public static int mail_port;
public static string mail_username;
public static string mail_password;
public static MailAddress mail_from;
public static MailAddress[] mail_to;
public static MailAddress[] mail_alarm_to;
// Prowl Notifications
public static string[] prowl_key;
public static bool prowl_messages;
// Web Service
public static bool webapi_enabled;
public static int webapi_port;
// Verbose Output
public static bool verbose_unhandled;
public static bool verbose_event;
public static bool verbose_area;
public static bool verbose_zone;
public static bool verbose_thermostat_timer;
public static bool verbose_thermostat;
public static bool verbose_unit;
public static bool verbose_message;
}
}

107
HAILogger/HAILogger.csproj Normal file
View file

@ -0,0 +1,107 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{0A636707-98BA-45AB-9843-AED430933CEE}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HAILogger</RootNamespace>
<AssemblyName>HAILogger</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</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|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="HAI.Controller">
<HintPath>.\HAI.Controller.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Data" />
<Reference Include="System.Management" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.ServiceModel.Web" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CoreServer.cs" />
<Compile Include="Event.cs" />
<Compile Include="Global.cs" />
<Compile Include="HAIService.cs" />
<Compile Include="Helper.cs" />
<Compile Include="CommandContract.cs" />
<Compile Include="IHAIService.cs" />
<Compile Include="Program.cs" />
<Compile Include="ProjectInstaller.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ProjectInstaller.Designer.cs">
<DependentUpon>ProjectInstaller.cs</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Prowl.cs" />
<Compile Include="Service.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Service.Designer.cs">
<DependentUpon>Service.cs</DependentUpon>
</Compile>
<Compile Include="Settings.cs" />
<Compile Include="SubscribeContract.cs" />
<Compile Include="ThermostatContract.cs" />
<Compile Include="NameContract.cs" />
<Compile Include="AreaContract.cs" />
<Compile Include="ZoneContract.cs" />
<Compile Include="UnitContract.cs" />
<Compile Include="WebNotification.cs" />
<Compile Include="WebService.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config">
<SubType>Designer</SubType>
</None>
<None Include="HAILogger.ini">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="ProjectInstaller.resx">
<DependentUpon>ProjectInstaller.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Service.resx">
<DependentUpon>Service.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- 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.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

55
HAILogger/HAILogger.ini Normal file
View file

@ -0,0 +1,55 @@
# HAI Controller
hai_address =
hai_port = 4369
hai_key1 = 00-00-00-00-00-00-00-00
hai_key2 = 00-00-00-00-00-00-00-00
# HAI Controller Time Sync (yes/no)
# hai_time_check is interval in minutes to check controller time
# hai_time_adj is the drift in seconds to allow before an adjustment is made
hai_time_sync = yes
hai_time_interval = 60
hai_time_drift = 10
# mySQL Database Logging (yes/no)
mysql_logging = no
mysql_server =
mysql_database =
mysql_user =
mysql_password =
# Event Notifications
# mail_username and mail_password optional for authenticated mail
# mail_to sent for service notifications
# mail_alarm_to sent for FIRE, BURGLARY, AUX, DURESS
mail_server =
mail_port = 25
mail_username =
mail_password =
mail_from =
#mail_to =
#mail_to =
#mail_alarm_to =
#mail_alarm_to =
# Prowl Notifications
# Register for API key at http://www.prowlapp.com
# Sent for FIRE, BURGLARY, AUX, DURESS
# prowl_messages (yes/no) for console message notifications
#prowl_key =
#prowl_key =
prowl_messages = no
# Web service
# Used for integration with Samsung SmartThings
webapi_enabled = yes
webapi_port = 8000
# Verbose Output (yes/no)
verbose_unhandled = yes
verbose_area = yes
verbose_zone = yes
verbose_thermostat_timer = yes
verbose_thermostat = yes
verbose_unit = yes
verbose_message = yes

309
HAILogger/HAIService.cs Normal file
View file

@ -0,0 +1,309 @@
using HAI_Shared;
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace HAILogger
{
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class HAIService : IHAIService
{
public void Subscribe(SubscribeContract contract)
{
Event.WriteVerbose("WebService", "Subscribe");
WebNotification.AddSubscription(contract.callback);
}
public List<NameContract> ListAreas()
{
Event.WriteVerbose("WebService", "ListAreas");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebService.HAC.Areas.Count; i++)
{
clsArea area = WebService.HAC.Areas[i];
if (area.DefaultProperties == false)
names.Add(new NameContract() { id = i, name = area.Name });
}
return names;
}
public AreaContract GetArea(ushort id)
{
Event.WriteVerbose("WebService", "GetArea: " + id);
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.Headers.Add("type", "area");
clsArea area = WebService.HAC.Areas[id];
return Helper.ConvertArea(id, area);
}
public List<NameContract> ListZonesContact()
{
Event.WriteVerbose("WebService", "ListZonesContact");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebService.HAC.Zones.Count; i++)
{
clsZone zone = WebService.HAC.Zones[i];
if ((zone.ZoneType == enuZoneType.EntryExit ||
zone.ZoneType == enuZoneType.X2EntryDelay ||
zone.ZoneType == enuZoneType.X4EntryDelay ||
zone.ZoneType == enuZoneType.Perimeter ||
zone.ZoneType == enuZoneType.Tamper ||
zone.ZoneType == enuZoneType.Auxiliary) && zone.DefaultProperties == false)
names.Add(new NameContract() { id = i, name = zone.Name });
}
return names;
}
public List<NameContract> ListZonesMotion()
{
Event.WriteVerbose("WebService", "ListZonesMotion");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebService.HAC.Zones.Count; i++)
{
clsZone zone = WebService.HAC.Zones[i];
if ((zone.ZoneType == enuZoneType.AwayInt ||
zone.ZoneType == enuZoneType.NightInt) && zone.DefaultProperties == false)
names.Add(new NameContract() { id = i, name = zone.Name });
}
return names;
}
public List<NameContract> ListZonesWater()
{
Event.WriteVerbose("WebService", "ListZonesWater");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebService.HAC.Zones.Count; i++)
{
clsZone zone = WebService.HAC.Zones[i];
if (zone.ZoneType == enuZoneType.Water && zone.DefaultProperties == false)
names.Add(new NameContract() { id = i, name = zone.Name });
}
return names;
}
public List<NameContract> ListZonesSmoke()
{
Event.WriteVerbose("WebService", "ListZonesSmoke");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebService.HAC.Zones.Count; i++)
{
clsZone zone = WebService.HAC.Zones[i];
if (zone.ZoneType == enuZoneType.Fire && zone.DefaultProperties == false)
names.Add(new NameContract() { id = i, name = zone.Name });
}
return names;
}
public List<NameContract> ListZonesCO()
{
Event.WriteVerbose("WebService", "ListZonesCO");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebService.HAC.Zones.Count; i++)
{
clsZone zone = WebService.HAC.Zones[i];
if (zone.ZoneType == enuZoneType.Gas && zone.DefaultProperties == false)
names.Add(new NameContract() { id = i, name = zone.Name });
}
return names;
}
public List<NameContract> ListZonesTemp()
{
Event.WriteVerbose("WebService", "ListZonesTemp");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebService.HAC.Zones.Count; i++)
{
clsZone zone = WebService.HAC.Zones[i];
if (zone.IsTemperatureZone() && zone.DefaultProperties == false)
names.Add(new NameContract() { id = i, name = zone.Name });
}
return names;
}
public ZoneContract GetZone(ushort id)
{
Event.WriteVerbose("WebService", "GetZone: " + id);
WebOperationContext ctx = WebOperationContext.Current;
if (WebService.HAC.Zones[id].IsTemperatureZone())
{
ctx.OutgoingResponse.Headers.Add("type", "temp");
}
else
{
switch (WebService.HAC.Zones[id].ZoneType)
{
case enuZoneType.EntryExit:
case enuZoneType.X2EntryDelay:
case enuZoneType.X4EntryDelay:
case enuZoneType.Perimeter:
case enuZoneType.Tamper:
case enuZoneType.Auxiliary:
ctx.OutgoingResponse.Headers.Add("type", "contact");
break;
case enuZoneType.AwayInt:
case enuZoneType.NightInt:
ctx.OutgoingResponse.Headers.Add("type", "motion");
break;
case enuZoneType.Water:
ctx.OutgoingResponse.Headers.Add("type", "water");
break;
case enuZoneType.Fire:
ctx.OutgoingResponse.Headers.Add("type", "smoke");
break;
case enuZoneType.Gas:
ctx.OutgoingResponse.Headers.Add("type", "co");
break;
default:
ctx.OutgoingResponse.Headers.Add("type", "unknown");
break;
}
}
clsZone unit = WebService.HAC.Zones[id];
return Helper.ConvertZone(id, unit);
}
public List<NameContract> ListUnits()
{
Event.WriteVerbose("WebService", "ListUnits");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebService.HAC.Units.Count; i++)
{
clsUnit unit = WebService.HAC.Units[i];
if (unit.DefaultProperties == false)
names.Add(new NameContract() { id = i, name = unit.Name });
}
return names;
}
public UnitContract GetUnit(ushort id)
{
Event.WriteVerbose("WebService", "GetUnit: " + id);
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.Headers.Add("type", "unit");
clsUnit unit = WebService.HAC.Units[id];
return Helper.ConvertUnit(id, unit);
}
public void SetUnit(CommandContract unit)
{
Event.WriteVerbose("WebService", "SetUnit: " + unit.id + " to " + unit.value + "%");
if (unit.value == 0)
WebService.HAC.SendCommand(enuUnitCommand.Off, 0, unit.id);
else if (unit.value == 100)
WebService.HAC.SendCommand(enuUnitCommand.On, 0, unit.id);
else
WebService.HAC.SendCommand(enuUnitCommand.Level, BitConverter.GetBytes(unit.value)[0], unit.id);
}
public void SetUnitKeypadPress(CommandContract unit)
{
Event.WriteVerbose("WebService", "SetUnitKeypadPress: " + unit.id + " to " + unit.value + " button");
WebService.HAC.SendCommand(enuUnitCommand.LutronHomeWorksKeypadButtonPress, BitConverter.GetBytes(unit.value)[0], unit.id);
}
public List<NameContract> ListThermostats()
{
Event.WriteVerbose("WebService", "ListThermostats");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebService.HAC.Thermostats.Count; i++)
{
clsThermostat unit = WebService.HAC.Thermostats[i];
if (unit.DefaultProperties == false)
names.Add(new NameContract() { id = i, name = unit.Name });
}
return names;
}
public ThermostatContract GetThermostat(ushort id)
{
Event.WriteVerbose("WebService", "GetThermostat: " + id);
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.Headers.Add("type", "thermostat");
clsThermostat unit = WebService.HAC.Thermostats[id];
return Helper.ConvertThermostat(id, unit);
}
public void SetThermostatCoolSetpoint(CommandContract unit)
{
int temp = Helper.ConvertTemperature(unit.value);
Event.WriteVerbose("WebService", "SetThermostatCoolSetpoint: " + unit.id + " to " + unit.value + "F (" + temp + ")");
WebService.HAC.SendCommand(enuUnitCommand.SetHighSetPt, BitConverter.GetBytes(temp)[0], unit.id);
}
public void SetThermostatHeatSetpoint(CommandContract unit)
{
int temp = Helper.ConvertTemperature(unit.value);
Event.WriteVerbose("WebService", "SetThermostatCoolSetpoint: " + unit.id + " to " + unit.value + "F (" + temp + ")");
WebService.HAC.SendCommand(enuUnitCommand.SetLowSetPt, BitConverter.GetBytes(temp)[0], unit.id);
}
public void SetThermostatMode(CommandContract unit)
{
Event.WriteVerbose("WebService", "SetThermostatMode: " + unit.id + " to " + unit.value);
WebService.HAC.SendCommand(enuUnitCommand.Mode, BitConverter.GetBytes(unit.value)[0], unit.id);
}
public void SetThermostatFanMode(CommandContract unit)
{
Event.WriteVerbose("WebService", "SetThermostatFanMode: " + unit.id + " to " + unit.value);
WebService.HAC.SendCommand(enuUnitCommand.Fan, BitConverter.GetBytes(unit.value)[0], unit.id);
}
public void SetThermostatHold(CommandContract unit)
{
Event.WriteVerbose("WebService", "SetThermostatHold: " + unit.id + " to " + unit.value);
WebService.HAC.SendCommand(enuUnitCommand.Hold, BitConverter.GetBytes(unit.value)[0], unit.id);
}
public List<NameContract> ListButtons()
{
Event.WriteVerbose("WebService", "ListButtons");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebService.HAC.Buttons.Count; i++)
{
clsButton unit = WebService.HAC.Buttons[i];
if (unit.DefaultProperties == false)
names.Add(new NameContract() { id = i, name = unit.Name });
}
return names;
}
public void PushButton(CommandContract unit)
{
Event.WriteVerbose("WebService", "PushButton: " + unit.id);
WebService.HAC.SendCommand(enuUnitCommand.Button, 0, unit.id);
}
}
}

118
HAILogger/Helper.cs Normal file
View file

@ -0,0 +1,118 @@
using HAI_Shared;
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
namespace HAILogger
{
static class Helper
{
private static string lastmode = "OFF";
public static AreaContract ConvertArea(ushort id, clsArea area)
{
AreaContract ret = new AreaContract();
ret.id = id;
ret.name = area.Name;
ret.burglary = area.AreaBurglaryAlarmText;
ret.co = area.AreaGasAlarmText;
ret.fire = area.AreaFireAlarmText;
ret.water = area.AreaWaterAlarmText;
if (area.ExitTimer > 0)
{
ret.mode = lastmode;
}
else
{
ret.mode = area.ModeText();
lastmode = ret.mode;
}
return ret;
}
public static ZoneContract ConvertZone(ushort id, clsZone zone)
{
ZoneContract ret = new ZoneContract();
ret.id = id;
ret.zonetype = zone.ZoneType;
ret.name = zone.Name;
ret.status = zone.StatusText();
ret.temp = zone.TempText();
return ret;
}
public static UnitContract ConvertUnit(ushort id, clsUnit unit)
{
UnitContract ret = new UnitContract();
ret.id = id;
ret.name = unit.Name;
if (unit.Status > 100)
ret.level = (ushort)(unit.Status - 100);
else if (unit.Status == 1)
ret.level = 100;
else
ret.level = 0;
return ret;
}
public static ThermostatContract ConvertThermostat(ushort id, clsThermostat unit)
{
ThermostatContract ret = new ThermostatContract();
ret.id = id;
ret.name = unit.Name;
ushort temp, heat, cool, humidity;
ushort.TryParse(unit.TempText(), out temp);
ushort.TryParse(unit.HeatSetpointText(), out heat);
ushort.TryParse(unit.CoolSetpointText(), out cool);
ushort.TryParse(unit.HumidityText(), out humidity);
ret.temp = temp;
ret.humidity = humidity;
ret.heatsetpoint = heat;
ret.coolsetpoint = cool;
ret.mode = unit.Mode;
ret.fanmode = unit.FanMode;
ret.hold = unit.HoldStatus;
string status = unit.HorC_StatusText();
if (status.Contains("COOLING"))
ret.status = "COOLING";
else if (status.Contains("HEATING"))
ret.status = "HEATING";
else
ret.status = "OFF";
return ret;
}
public static int ConvertTemperature(int f)
{
// Convert to celsius
double c = 5.0 / 9.0 * (f - 32);
// Convert to omni temp (0 is -40C and 255 is 87.5C)
return (int)Math.Round((c + 40) * 2, 0);
}
public static string Serialize<T>(T obj)
{
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
ser.WriteObject(stream, obj);
return Encoding.UTF8.GetString(stream.ToArray());
}
}
}

View file

@ -2,10 +2,10 @@
using System.ServiceModel; using System.ServiceModel;
using System.ServiceModel.Web; using System.ServiceModel.Web;
namespace OmniLinkBridge.WebAPI namespace HAILogger
{ {
[ServiceContract] [ServiceContract]
public interface IOmniLinkService public interface IHAIService
{ {
[OperationContract] [OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]

View file

@ -1,6 +1,6 @@
using System.Runtime.Serialization; using System.Runtime.Serialization;
namespace OmniLinkBridge.WebAPI namespace HAILogger
{ {
[DataContract] [DataContract]
public class NameContract public class NameContract

98
HAILogger/Program.cs Normal file
View file

@ -0,0 +1,98 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.ServiceProcess;
namespace HAILogger
{
class Program
{
static CoreServer server;
static void Main(string[] args)
{
bool interactive = false;
for (int i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "/?":
case "-h":
case "-help":
ShowHelp();
return;
case "-c":
Global.config_file = args[++i];
break;
case "-l":
Global.config_file = args[++i];
break;
case "-i":
interactive = true;
break;
}
}
if (string.IsNullOrEmpty(Global.log_file))
Global.log_file = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) +
Path.DirectorySeparatorChar + "EventLog.txt";
if (string.IsNullOrEmpty(Global.config_file))
Global.config_file = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) +
Path.DirectorySeparatorChar + "HAILogger.ini";
Global.event_source = "HAI Logger";
try
{
Settings.LoadSettings();
}
catch
{
// Errors are logged in LoadSettings();
Environment.Exit(1);
}
if (Environment.UserInteractive || interactive)
{
Console.TreatControlCAsInput = false;
Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler);
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
server = new CoreServer();
}
else
{
ServiceBase[] ServicesToRun;
// More than one user Service may run within the same process. To add
// another service to this process, change the following line to
// create a second service object. For example,
//
// ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
//
ServicesToRun = new ServiceBase[] { new Service() };
ServiceBase.Run(ServicesToRun);
}
}
protected static void myHandler(object sender, ConsoleCancelEventArgs args)
{
server.Shutdown();
args.Cancel = true;
}
static void ShowHelp()
{
Console.WriteLine(
AppDomain.CurrentDomain.FriendlyName + " [-c config_file] [-l log_file] [-i]\n" +
"\t-c Specifies the name of the config file. Default is HAILogger.ini\n" +
"\t-l Specifies the name of the log file. Default is EventLog.txt\n" +
"\t-i Run in interactive mode");
}
}
}

View file

@ -1,4 +1,4 @@
namespace OmniLinkBridge namespace HAILogger
{ {
partial class ProjectInstaller partial class ProjectInstaller
{ {
@ -38,7 +38,7 @@
// //
// serviceInstaller // serviceInstaller
// //
this.serviceInstaller.ServiceName = "OmniLinkBridge"; this.serviceInstaller.ServiceName = "HAILogger";
// //
// ProjectInstaller // ProjectInstaller
// //

View file

@ -4,7 +4,7 @@ using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Configuration.Install; using System.Configuration.Install;
namespace OmniLinkBridge namespace HAILogger
{ {
[RunInstaller(true)] [RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer public partial class ProjectInstaller : System.Configuration.Install.Installer

View file

@ -5,12 +5,12 @@ using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following // General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information // set of attributes. Change these attribute values to modify the information
// associated with an assembly. // associated with an assembly.
[assembly: AssemblyTitle("OmniLink Bridge")] [assembly: AssemblyTitle("HAILogger")]
[assembly: AssemblyDescription("")] [assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Excalibur Partners, LLC")] [assembly: AssemblyCompany("Excalibur Partners, LLC")]
[assembly: AssemblyProduct("OmniLinkBridge")] [assembly: AssemblyProduct("HAILogger")]
[assembly: AssemblyCopyright("Copyright © Excalibur Partners, LLC 2024")] [assembly: AssemblyCopyright("Copyright © Excalibur Partners, LLC 2016")]
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers // You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.19.0")] [assembly: AssemblyVersion("1.0.8.0")]
[assembly: AssemblyFileVersion("1.1.19.0")] [assembly: AssemblyFileVersion("1.0.8.0")]

50
HAILogger/Prowl.cs Normal file
View file

@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Net;
namespace HAILogger
{
public enum ProwlPriority
{
VeryLow = -2,
Moderate = -1,
Normal = 0,
High = 1,
Emergency = 2,
};
static class Prowl
{
public static void Notify(string source, string description)
{
Notify(source, description, ProwlPriority.Normal);
}
public static void Notify(string source, string description, ProwlPriority priority)
{
Uri URI = new Uri("https://api.prowlapp.com/publicapi/add");
foreach (string key in Global.prowl_key)
{
List<string> parameters = new List<string>();
parameters.Add("apikey=" + key);
parameters.Add("priority= " + (int)priority);
parameters.Add("application=" + Global.event_source);
parameters.Add("event=" + source);
parameters.Add("description=" + description);
WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
client.UploadStringAsync(URI, string.Join("&", parameters.ToArray()));
client.UploadStringCompleted += client_UploadStringCompleted;
}
}
static void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if(e.Error != null)
Event.WriteError("ProwlNotification", "An error occurred sending notification\r\n" + e.Error.Message);
}
}
}

View file

@ -1,4 +1,4 @@
namespace OmniLinkBridge namespace HAILogger
{ {
partial class Service partial class Service
{ {
@ -33,7 +33,7 @@
// //
this.AutoLog = false; this.AutoLog = false;
this.CanShutdown = true; this.CanShutdown = true;
this.ServiceName = "OmniLinkBridge"; this.ServiceName = "HAILogger";
} }

View file

@ -6,7 +6,7 @@ using System.Diagnostics;
using System.ServiceProcess; using System.ServiceProcess;
using System.Text; using System.Text;
namespace OmniLinkBridge namespace HAILogger
{ {
partial class Service : ServiceBase partial class Service : ServiceBase
{ {

243
HAILogger/Settings.cs Normal file
View file

@ -0,0 +1,243 @@
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Mail;
namespace HAILogger
{
static class Settings
{
public static void LoadSettings()
{
NameValueCollection settings = LoadCollection(Global.config_file);
// HAI Controller
Global.hai_address = settings["hai_address"];
Global.hai_port = ValidatePort(settings, "hai_port");
Global.hai_key1 = settings["hai_key1"];
Global.hai_key2 = settings["hai_key2"];
Global.hai_time_sync = ValidateYesNo(settings, "hai_time_sync");
Global.hai_time_interval = ValidateInt(settings, "hai_time_interval");
Global.hai_time_drift = ValidateInt(settings, "hai_time_drift");
// mySQL Database
Global.mysql_logging = ValidateYesNo(settings, "mysql_logging");
Global.mysql_connection = settings["mysql_connection"];
// Events
Global.mail_server = settings["mail_server"];
Global.mail_port = ValidatePort(settings, "mail_port");
Global.mail_username = settings["mail_username"];
Global.mail_password = settings["mail_password"];
Global.mail_from = ValidateMailFrom(settings, "mail_from");
Global.mail_to = ValidateMailTo(settings, "mail_to");
Global.mail_alarm_to = ValidateMailTo(settings, "mail_alarm_to");
// Prowl Notifications
Global.prowl_key = ValidateMultipleStrings(settings, "prowl_key");
Global.prowl_messages = ValidateYesNo(settings, "prowl_messages");
// Web Service
Global.webapi_enabled = ValidateYesNo(settings, "webapi_enabled");
Global.webapi_port = ValidatePort(settings, "webapi_port");
// Verbose Output
Global.verbose_unhandled = ValidateYesNo(settings, "verbose_unhandled");
Global.verbose_event = ValidateYesNo(settings, "verbose_event");
Global.verbose_area = ValidateYesNo(settings, "verbose_area");
Global.verbose_zone = ValidateYesNo(settings, "verbose_zone");
Global.verbose_thermostat_timer = ValidateYesNo(settings, "verbose_thermostat_timer");
Global.verbose_thermostat = ValidateYesNo(settings, "verbose_thermostat");
Global.verbose_unit = ValidateYesNo(settings, "verbose_unit");
Global.verbose_message = ValidateYesNo(settings, "verbose_message");
}
private static int ValidateInt(NameValueCollection settings, string section)
{
try
{
return Int32.Parse(settings[section]);
}
catch
{
Event.WriteError("Settings", "Invalid integer specified for " + section);
throw;
}
}
private static int ValidatePort(NameValueCollection settings, string section)
{
try
{
int port = Int32.Parse(settings[section]);
if (port < 1 || port > 65534)
throw new Exception();
return port;
}
catch
{
Event.WriteError("Settings", "Invalid port specified for " + section);
throw;
}
}
private static bool ValidateBool(NameValueCollection settings, string section)
{
try
{
return Boolean.Parse(settings[section]);
}
catch
{
Event.WriteError("Settings", "Invalid bool specified for " + section);
throw;
}
}
private static IPAddress ValidateIP(NameValueCollection settings, string section)
{
if (settings[section] == "*")
return IPAddress.Any;
if (settings[section] == "")
return IPAddress.None;
try
{
return IPAddress.Parse(section);
}
catch
{
Event.WriteError("Settings", "Invalid IP specified for " + section);
throw;
}
}
private static string ValidateDirectory(NameValueCollection settings, string section)
{
try
{
if (!Directory.Exists(settings[section]))
Directory.CreateDirectory(settings[section]);
return settings[section];
}
catch
{
Event.WriteError("Settings", "Invalid directory specified for " + section);
throw;
}
}
private static MailAddress ValidateMailFrom(NameValueCollection settings, string section)
{
try
{
return new MailAddress(settings[section]);
}
catch
{
Event.WriteError("Settings", "Invalid email specified for " + section);
throw;
}
}
private static MailAddress[] ValidateMailTo(NameValueCollection settings, string section)
{
try
{
if(settings[section] == null)
return new MailAddress[] {};
string[] emails = settings[section].Split(',');
MailAddress[] addresses = new MailAddress[emails.Length];
for(int i=0; i < emails.Length; i++)
addresses[i] = new MailAddress(emails[i]);
return addresses;
}
catch
{
Event.WriteError("Settings", "Invalid email specified for " + section);
throw;
}
}
private static string[] ValidateMultipleStrings(NameValueCollection settings, string section)
{
try
{
if (settings[section] == null)
return new string[] { };
return settings[section].Split(',');
}
catch
{
Event.WriteError("Settings", "Invalid string specified for " + section);
throw;
}
}
private static bool ValidateYesNo (NameValueCollection settings, string section)
{
if (settings[section] == null)
return false;
if (string.Compare(settings[section], "yes", true) == 0)
return true;
else if (string.Compare(settings[section], "no", true) == 0)
return false;
else
{
Event.WriteError("Settings", "Invalid yes/no specified for " + section);
throw new Exception();
}
}
private static NameValueCollection LoadCollection(string sFile)
{
NameValueCollection settings = new NameValueCollection();
try
{
FileStream fs = new FileStream(sFile, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
while (true)
{
string line = sr.ReadLine();
if (line == null)
break;
if (line.StartsWith("#"))
continue;
int pos = line.IndexOf('=', 0);
if (pos == -1)
continue;
string key = line.Substring(0, pos).Trim();
string value = line.Substring(pos + 1).Trim();
settings.Add(key, value);
}
sr.Close();
fs.Close();
}
catch (FileNotFoundException)
{
Event.WriteError("Settings", "Unable to parse settings file " + sFile);
throw;
}
return settings;
}
}
}

View file

@ -1,6 +1,6 @@
using System.Runtime.Serialization; using System.Runtime.Serialization;
namespace OmniLinkBridge.WebAPI namespace HAILogger
{ {
[DataContract] [DataContract]
public class SubscribeContract public class SubscribeContract

View file

@ -1,7 +1,7 @@
using HAI_Shared; using HAI_Shared;
using System.Runtime.Serialization; using System.Runtime.Serialization;
namespace OmniLinkBridge.WebAPI namespace HAILogger
{ {
[DataContract] [DataContract]
public class ThermostatContract public class ThermostatContract

View file

@ -1,6 +1,6 @@
using System.Runtime.Serialization; using System.Runtime.Serialization;
namespace OmniLinkBridge.WebAPI namespace HAILogger
{ {
[DataContract] [DataContract]
public class UnitContract public class UnitContract

View file

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Net;
namespace HAILogger
{
static class WebNotification
{
private static List<string> subscriptions = new List<string>();
private static object subscriptions_lock = new object();
public static void AddSubscription(string callback)
{
lock (subscriptions_lock)
{
if (!subscriptions.Contains(callback))
{
Event.WriteVerbose("WebNotification", "Adding subscription to " + callback);
subscriptions.Add(callback);
}
}
}
public static void Send(string type, string body)
{
string[] send;
lock (subscriptions_lock)
send = subscriptions.ToArray();
foreach (string subscription in send)
{
WebClient client = new WebClient();
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.Headers.Add("type", type);
client.UploadStringCompleted += client_UploadStringCompleted;
try
{
client.UploadStringAsync(new Uri(subscription), "POST", body, subscription);
}
catch (Exception ex)
{
Event.WriteError("WebNotification", "An error occurred sending notification to " + subscription + "\r\n" + ex.ToString());
subscriptions.Remove(subscription);
}
}
}
static void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error != null)
{
Event.WriteError("WebNotification", "An error occurred sending notification to " + e.UserState.ToString() + "\r\n" + e.Error.Message);
lock (subscriptions_lock)
subscriptions.Remove(e.UserState.ToString());
}
}
}
}

44
HAILogger/WebService.cs Normal file
View file

@ -0,0 +1,44 @@
using HAI_Shared;
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
namespace HAILogger
{
public class WebService
{
public static clsHAC HAC;
WebServiceHost host;
public WebService(clsHAC hac)
{
HAC = hac;
}
public void Start()
{
Uri uri = new Uri("http://0.0.0.0:" + Global.webapi_port + "/");
host = new WebServiceHost(typeof(HAIService), uri);
try
{
ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IHAIService), new WebHttpBinding(), "");
host.Open();
Event.WriteInfo("WebService", "Listening on " + uri.ToString());
}
catch (CommunicationException ex)
{
Event.WriteError("WebService", "An exception occurred: " + ex.Message);
host.Abort();
}
}
public void Stop()
{
if (host != null)
host.Close();
}
}
}

View file

@ -1,7 +1,7 @@
using HAI_Shared; using HAI_Shared;
using System.Runtime.Serialization; using System.Runtime.Serialization;
namespace OmniLinkBridge.WebAPI namespace HAILogger
{ {
[DataContract] [DataContract]
public class ZoneContract public class ZoneContract

View file

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View file

@ -1,31 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27703.2026
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OmniLinkBridge", "OmniLinkBridge\OmniLinkBridge.csproj", "{0A636707-98BA-45AB-9843-AED430933CEE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OmniLinkBridgeTest", "OmniLinkBridgeTest\OmniLinkBridgeTest.csproj", "{6E6950E4-35F9-4D99-8ADA-B7E2F29D4172}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0A636707-98BA-45AB-9843-AED430933CEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0A636707-98BA-45AB-9843-AED430933CEE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0A636707-98BA-45AB-9843-AED430933CEE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0A636707-98BA-45AB-9843-AED430933CEE}.Release|Any CPU.Build.0 = Release|Any CPU
{6E6950E4-35F9-4D99-8ADA-B7E2F29D4172}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6E6950E4-35F9-4D99-8ADA-B7E2F29D4172}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6E6950E4-35F9-4D99-8ADA-B7E2F29D4172}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6E6950E4-35F9-4D99-8ADA-B7E2F29D4172}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C65BDBEF-1B50-442F-BC26-3A5FE3EDFCA3}
EndGlobalSection
EndGlobal

View file

@ -1,128 +0,0 @@
-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Dec 29, 2012 at 10:51 AM
-- Server version: 5.0.95
-- PHP Version: 5.2.10
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `hai`
--
-- --------------------------------------------------------
--
-- Table structure for table `log_areas`
--
CREATE TABLE IF NOT EXISTS `log_areas` (
`log_area_id` int(10) unsigned NOT NULL auto_increment,
`timestamp` datetime NOT NULL,
`id` tinyint(4) NOT NULL,
`name` varchar(12) NOT NULL,
`fire` varchar(10) NOT NULL,
`police` varchar(10) NOT NULL,
`auxiliary` varchar(10) NOT NULL,
`duress` varchar(10) NOT NULL,
`security` varchar(20) NOT NULL,
PRIMARY KEY (`log_area_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `log_events`
--
CREATE TABLE IF NOT EXISTS `log_events` (
`log_event_id` int(10) unsigned NOT NULL auto_increment,
`timestamp` datetime NOT NULL,
`name` varchar(12) NOT NULL,
`status` varchar(10) NOT NULL,
PRIMARY KEY (`log_event_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `log_messages`
--
CREATE TABLE IF NOT EXISTS `log_messages` (
`log_message_id` int(10) unsigned NOT NULL auto_increment,
`timestamp` datetime NOT NULL,
`id` smallint(6) NOT NULL,
`name` varchar(12) NOT NULL,
`status` varchar(10) NOT NULL,
PRIMARY KEY (`log_message_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `log_thermostats`
--
CREATE TABLE IF NOT EXISTS `log_thermostats` (
`log_tstat_id` int(10) unsigned NOT NULL auto_increment,
`timestamp` datetime NOT NULL,
`id` tinyint(4) NOT NULL,
`name` varchar(12) NOT NULL,
`status` varchar(10) NOT NULL,
`temp` smallint(6) NOT NULL,
`heat` smallint(6) NOT NULL,
`cool` smallint(6) NOT NULL,
`humidity` smallint(6) NOT NULL,
`humidify` smallint(6) NOT NULL,
`dehumidify` smallint(6) NOT NULL,
`mode` varchar(14) NOT NULL,
`fan` varchar(5) NOT NULL,
`hold` varchar(8) NOT NULL,
PRIMARY KEY (`log_tstat_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `log_units`
--
CREATE TABLE IF NOT EXISTS `log_units` (
`log_unit_id` int(10) unsigned NOT NULL auto_increment,
`timestamp` datetime NOT NULL,
`id` smallint(6) NOT NULL,
`name` varchar(12) NOT NULL,
`status` varchar(15) NOT NULL,
`statusvalue` smallint(6) NOT NULL,
`statustime` smallint(6) NOT NULL,
PRIMARY KEY (`log_unit_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Table structure for table `log_zones`
--
CREATE TABLE IF NOT EXISTS `log_zones` (
`log_zone_id` int(10) unsigned NOT NULL auto_increment,
`timestamp` datetime NOT NULL,
`id` smallint(6) NOT NULL,
`name` varchar(16) NOT NULL,
`status` varchar(10) NOT NULL,
PRIMARY KEY (`log_zone_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

View file

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
</startup>
</configuration>

View file

@ -1,16 +0,0 @@
using System;
using Serilog.Core;
using Serilog.Events;
namespace OmniLinkBridge
{
public class ControllerEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if(Global.controller_id != Guid.Empty)
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
"ControllerId", Global.controller_id));
}
}
}

View file

@ -1,83 +0,0 @@
using OmniLinkBridge.Modules;
using Serilog;
using Serilog.Context;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace OmniLinkBridge
{
public class CoreServer
{
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
private OmniLinkII omnilink;
private readonly List<IModule> modules = new List<IModule>();
private readonly List<Task> tasks = new List<Task>();
private readonly ManualResetEvent quitEvent = new ManualResetEvent(false);
private DateTime startTime;
public CoreServer()
{
Thread handler = new Thread(Server);
handler.Start();
}
private void Server()
{
// Controller connection
modules.Add(omnilink = new OmniLinkII(Global.controller_address, Global.controller_port, Global.controller_key1, Global.controller_key2));
// Initialize modules
modules.Add(new LoggerModule(omnilink));
if (Global.time_sync)
modules.Add(new TimeSyncModule(omnilink));
if (Global.webapi_enabled)
modules.Add(new WebServiceModule(omnilink));
if(Global.mqtt_enabled)
modules.Add(new MQTTModule(omnilink));
startTime = DateTime.Now;
Program.ShowSendLogsWarning();
using (LogContext.PushProperty("Telemetry", "Startup"))
log.Information("Started version {Version} in {Environment} on {OperatingSystem} with {Modules}",
Assembly.GetExecutingAssembly().GetName().Version, Program.GetEnvironment(), Environment.OSVersion, modules);
// Startup modules
foreach (IModule module in modules)
{
tasks.Add(Task.Factory.StartNew(() =>
{
module.Startup();
}));
}
quitEvent.WaitOne();
}
public void Shutdown()
{
// Shutdown modules
foreach (IModule module in modules)
module.Shutdown();
// Wait for all threads to stop
if (tasks != null)
Task.WaitAll(tasks.ToArray());
using (LogContext.PushProperty("Telemetry", "Shutdown"))
log.Information("Shutdown completed with uptime {Uptime}", (DateTime.Now - startTime).ToString());
Log.CloseAndFlush();
quitEvent.Set();
}
}
}

View file

@ -1,63 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace OmniLinkBridge
{
public static class Extensions
{
public static string Truncate(this string value, int maxLength)
{
return value?.Length > maxLength ? value.Substring(0, maxLength) : value;
}
public static double ToCelsius(this double f)
{
// Convert to celsius
return (5.0 / 9.0 * (f - 32));
}
public static int ToOmniTemp(this double c)
{
// Convert to omni temp (0 is -40C and 255 is 87.5C)
return (int)Math.Round((c + 40) * 2, 0);
}
public static bool IsBitSet(this byte b, int pos)
{
return (b & (1 << pos)) != 0;
}
public static string ToSpaceTitleCase(this string phrase)
{
return Regex.Replace(phrase, "(\\B[A-Z])", " $1");
}
public static List<int> ParseRanges(this string ranges)
{
string[] groups = ranges.Split(',');
return groups.SelectMany(t => ParseRange(t)).ToList();
}
private static List<int> ParseRange(string range)
{
List<int> RangeNums = range
.Split('-')
.Select(t => new String(t.Where(Char.IsDigit).ToArray())) // Digits Only
.Where(t => !string.IsNullOrWhiteSpace(t)) // Only if has a value
.Select(t => int.Parse(t)).ToList(); // digit to int
return RangeNums.Count.Equals(2) ? Enumerable.Range(RangeNums.Min(), (RangeNums.Max() + 1) - RangeNums.Min()).ToList() : RangeNums;
}
public static Guid ComputeGuid(this string data)
{
using SHA256 hash = SHA256.Create();
byte[] bytes = hash.ComputeHash(Encoding.UTF8.GetBytes(data));
byte[] guidBytes = new byte[16];
Array.Copy(bytes, guidBytes, 16);
return new Guid(guidBytes);
}
}
}

View file

@ -1,94 +0,0 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Mail;
using System.Reflection;
namespace OmniLinkBridge
{
public abstract class Global
{
public static bool DebugSettings { get; set; }
public static bool UseEnvironment { get; set; }
public static bool SendLogs { get; set; }
public static Guid SessionID { get; } = Guid.NewGuid();
// HAI / Leviton Omni Controller
public static string controller_address;
public static int controller_port;
public static string controller_key1;
public static string controller_key2;
public static string controller_name;
public static Guid controller_id;
// Time Sync
public static bool time_sync;
public static int time_interval;
public static int time_drift;
// Verbose Console
public static bool verbose_unhandled;
public static bool verbose_event;
public static bool verbose_area;
public static bool verbose_zone;
public static bool verbose_thermostat_timer;
public static bool verbose_thermostat;
public static bool verbose_unit;
public static bool verbose_message;
public static bool verbose_lock;
public static bool verbose_audio;
// mySQL Logging
public static bool mysql_logging;
public static string mysql_connection;
// Web Service
public static bool webapi_enabled;
public static int webapi_port;
public static ConcurrentDictionary<int, WebAPI.OverrideZone> webapi_override_zone;
public static string webapi_subscriptions_file;
// MQTT
public static bool mqtt_enabled;
public static string mqtt_server;
public static int mqtt_port;
public static string mqtt_username;
public static string mqtt_password;
public static string mqtt_prefix;
public static string mqtt_discovery_prefix;
public static string mqtt_discovery_name_prefix;
public static HashSet<int> mqtt_discovery_ignore_zones;
public static HashSet<int> mqtt_discovery_ignore_units;
public static ConcurrentDictionary<int, MQTT.OverrideArea> mqtt_discovery_override_area;
public static ConcurrentDictionary<int, MQTT.OverrideZone> mqtt_discovery_override_zone;
public static ConcurrentDictionary<int, MQTT.OverrideUnit> mqtt_discovery_override_unit;
public static Type mqtt_discovery_button_type;
public static bool mqtt_audio_local_mute;
public static bool mqtt_audio_volume_media_player;
// Notifications
public static bool notify_area;
public static bool notify_message;
// Email Notifications
public static string mail_server;
public static bool mail_tls;
public static int mail_port;
public static string mail_username;
public static string mail_password;
public static MailAddress mail_from;
public static MailAddress[] mail_to;
// Prowl Notifications
public static string[] prowl_key;
// Pushover Notifications
public static string pushover_token;
public static string[] pushover_user;
public static object GetValue(string propName)
{
return typeof(Global).GetField(propName, BindingFlags.Public | BindingFlags.Static).GetValue(null);
}
}
}

View file

@ -1,10 +0,0 @@
namespace OmniLinkBridge.MQTT
{
public class AreaCommandCode
{
public bool Success { get; set; } = true;
public string Command { get; set; }
public bool Validate { get; set; }
public int Code { get; set; }
}
}

View file

@ -1,16 +0,0 @@
namespace OmniLinkBridge.MQTT
{
public class AreaState
{
public string mode { get; set; }
public bool arming { get; set; }
public bool burglary_alarm { get; set; }
public bool fire_alarm { get; set; }
public bool gas_alarm { get; set; }
public bool auxiliary_alarm { get; set; }
public bool freeze_alarm { get; set; }
public bool water_alarm { get; set; }
public bool duress_alarm { get; set; }
public bool temperature_alarm { get; set; }
}
}

View file

@ -1,7 +0,0 @@
namespace OmniLinkBridge.MQTT
{
public class Availability
{
public string topic { get; set; } = $"{Global.mqtt_prefix}/status";
}
}

View file

@ -1,66 +0,0 @@
using HAI_Shared;
namespace OmniLinkBridge.MQTT
{
public static class Extensions
{
public static AreaCommandCode ToCommandCode(this string payload, bool supportValidate = false)
{
string[] payloads = payload.Split(',');
int code = 0;
AreaCommandCode ret = new AreaCommandCode()
{
Command = payloads[0]
};
if (payload.Length == 1)
return ret;
if (payloads.Length == 2)
{
ret.Success = int.TryParse(payloads[1], out code);
}
else if (supportValidate && payloads.Length == 3)
{
// Special case for Home Assistant when code not required
if (string.Compare(payloads[1], "validate", true) == 0 &&
string.Compare(payloads[2], "None", true) == 0)
{
ret.Success = true;
}
else if (string.Compare(payloads[1], "validate", true) == 0)
{
ret.Validate = true;
ret.Success = int.TryParse(payloads[2], out code);
}
else
ret.Success = false;
}
ret.Code = code;
return ret;
}
public static UnitType ToUnitType(this clsUnit unit)
{
Global.mqtt_discovery_override_unit.TryGetValue(unit.Number, out OverrideUnit override_unit);
if (unit.Type == enuOL2UnitType.Output)
return UnitType.@switch;
if (unit.Type == enuOL2UnitType.Flag)
{
if (override_unit != null && override_unit.type == UnitType.number)
return UnitType.number;
return UnitType.@switch;
}
if (override_unit != null && override_unit.type == UnitType.@switch)
return UnitType.@switch;
return UnitType.light;
}
}
}

View file

@ -1,30 +0,0 @@
using Newtonsoft.Json;
using System.Collections.Generic;
namespace OmniLinkBridge.MQTT.HomeAssistant
{
public class Alarm : Device
{
public Alarm(DeviceRegistry deviceRegistry) : base(deviceRegistry)
{
}
public string command_topic { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string command_template { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string code { get; set; }
public bool code_arm_required { get; set; } = false;
public bool code_disarm_required { get; set; } = false;
public bool code_trigger_required { get; set; } = false;
public List<string> supported_features { get; set; } = new List<string>(new string[] {
"arm_home", "arm_away", "arm_night", "arm_vacation" });
}
}

View file

@ -1,42 +0,0 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace OmniLinkBridge.MQTT.HomeAssistant
{
public class BinarySensor : Device
{
public BinarySensor(DeviceRegistry deviceRegistry) : base(deviceRegistry)
{
}
[JsonConverter(typeof(StringEnumConverter))]
public enum DeviceClass
{
battery,
cold,
door,
garage_door,
gas,
heat,
moisture,
motion,
problem,
safety,
smoke,
window
}
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public DeviceClass? device_class { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string value_template { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string payload_off { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string payload_on { get; set; }
}
}

View file

@ -1,17 +0,0 @@
using Newtonsoft.Json;
namespace OmniLinkBridge.MQTT.HomeAssistant
{
public class Button : Device
{
public Button(DeviceRegistry deviceRegistry) : base(deviceRegistry)
{
}
public string command_topic { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string payload_press { get; set; }
}
}

View file

@ -1,38 +0,0 @@
using System.Collections.Generic;
namespace OmniLinkBridge.MQTT.HomeAssistant
{
public class Climate : Device
{
public Climate(DeviceRegistry deviceRegistry) : base(deviceRegistry)
{
}
public string status { get; set; }
public string action_topic { get; set; }
public string current_temperature_topic { get; set; }
public string temperature_low_state_topic { get; set; }
public string temperature_low_command_topic { get; set; }
public string temperature_high_state_topic { get; set; }
public string temperature_high_command_topic { get; set; }
public string min_temp { get; set; } = "45";
public string max_temp { get; set; } = "95";
public string mode_state_topic { get; set; }
public string mode_command_topic { get; set; }
public List<string> modes { get; set; } = new List<string>(new string[] { "auto", "off", "cool", "heat" });
public string fan_mode_state_topic { get; set; }
public string fan_mode_command_topic { get; set; }
public List<string> fan_modes { get; set; } = new List<string>(new string[] { "auto", "on", "cycle" });
public string preset_mode_state_topic { get; set; }
public string preset_mode_command_topic { get; set; }
public List<string> preset_modes { get; set; } = new List<string>(new string[] { "off", "on", "vacation" });
}
}

View file

@ -1,44 +0,0 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
namespace OmniLinkBridge.MQTT.HomeAssistant
{
public class Device
{
public Device(DeviceRegistry deviceRegistry)
{
device = deviceRegistry;
}
[JsonConverter(typeof(StringEnumConverter))]
public enum AvailabilityMode
{
all,
any,
latest
}
public string unique_id { get; set; }
public string name { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string icon { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string state_topic { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string availability_topic { get; set; } = $"{Global.mqtt_prefix}/status";
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<Availability> availability { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public AvailabilityMode? availability_mode { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public DeviceRegistry device { get; set; }
}
}

View file

@ -1,11 +0,0 @@
namespace OmniLinkBridge.MQTT.HomeAssistant
{
public class DeviceRegistry
{
public string identifiers { get; set; }
public string name { get; set; }
public string sw_version { get; set; }
public string model { get; set; }
public string manufacturer { get; set; }
}
}

View file

@ -1,18 +0,0 @@
namespace OmniLinkBridge.MQTT.HomeAssistant
{
public class Light : Device
{
public Light(DeviceRegistry deviceRegistry) : base(deviceRegistry)
{
}
public string command_topic { get; set; }
public string brightness_state_topic { get; set; }
public string brightness_command_topic { get; set; }
public int brightness_scale { get; private set; } = 100;
}
}

View file

@ -1,26 +0,0 @@
using Newtonsoft.Json;
namespace OmniLinkBridge.MQTT.HomeAssistant
{
public class Lock : Device
{
public Lock(DeviceRegistry deviceRegistry) : base(deviceRegistry)
{
}
public string command_topic { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string payload_lock { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string payload_unlock { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string state_locked { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string state_unlocked { get; set; }
}
}

View file

@ -1,23 +0,0 @@
using Newtonsoft.Json;
namespace OmniLinkBridge.MQTT.HomeAssistant
{
public class Number : Device
{
public Number(DeviceRegistry deviceRegistry) : base(deviceRegistry)
{
}
public string command_topic { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int? min { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int? max { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public double? step { get; set; }
}
}

View file

@ -1,16 +0,0 @@
using System.Collections.Generic;
namespace OmniLinkBridge.MQTT.HomeAssistant
{
public class Select : Device
{
public Select(DeviceRegistry deviceRegistry) : base(deviceRegistry)
{
}
public string command_topic { get; set; }
public List<string> options { get; set; } = null;
}
}

View file

@ -1,29 +0,0 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace OmniLinkBridge.MQTT.HomeAssistant
{
public class Sensor : Device
{
public Sensor(DeviceRegistry deviceRegistry) : base(deviceRegistry)
{
}
[JsonConverter(typeof(StringEnumConverter))]
public enum DeviceClass
{
humidity,
temperature
}
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public DeviceClass? device_class { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string unit_of_measurement { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string value_template { get; set; }
}
}

View file

@ -1,23 +0,0 @@
using Newtonsoft.Json;
namespace OmniLinkBridge.MQTT.HomeAssistant
{
public class Switch : Device
{
public Switch(DeviceRegistry deviceRegistry) : base(deviceRegistry)
{
}
public string command_topic { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string payload_off { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string payload_on { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string value_template { get; set; }
}
}

View file

@ -1,769 +0,0 @@
using HAI_Shared;
using Newtonsoft.Json;
using System.Collections.Generic;
using OmniLinkBridge.MQTT.HomeAssistant;
using OmniLinkBridge.MQTT.Parser;
using OmniLinkBridge.Modules;
namespace OmniLinkBridge.MQTT
{
public static class MappingExtensions
{
public static string ToTopic(this clsArea area, Topic topic)
{
return $"{Global.mqtt_prefix}/area{area.Number}/{topic}";
}
public static Alarm ToConfig(this clsArea area)
{
Alarm ret = new Alarm(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}area{area.Number}",
name = Global.mqtt_discovery_name_prefix + area.Name,
state_topic = area.ToTopic(Topic.basic_state),
command_topic = area.ToTopic(Topic.command),
};
Global.mqtt_discovery_override_area.TryGetValue(area.Number, out OverrideArea override_area);
if (override_area != null)
{
if(override_area.code_arm || override_area.code_disarm)
{
ret.command_template = "{{ action }},validate,{{ code }}";
ret.code = "REMOTE_CODE";
}
ret.code_arm_required = override_area.code_arm;
ret.code_disarm_required = override_area.code_disarm;
ret.supported_features.Clear();
if (override_area.arm_home)
ret.supported_features.Add("arm_home");
if (override_area.arm_away)
ret.supported_features.Add("arm_away");
if (override_area.arm_night)
ret.supported_features.Add("arm_night");
if (override_area.arm_vacation)
ret.supported_features.Add("arm_vacation");
}
return ret;
}
public static string ToState(this clsArea area)
{
if (area.AreaAlarms.IsBitSet(0) || // Burgulary
area.AreaAlarms.IsBitSet(3) || // Auxiliary
area.AreaAlarms.IsBitSet(6)) // Duress
return "triggered";
else if (area.ExitTimer > 0)
return "arming";
return area.AreaMode switch
{
enuSecurityMode.Night => "armed_night",
enuSecurityMode.NightDly => "armed_night_delay",
enuSecurityMode.Day => "armed_home",
enuSecurityMode.DayInst => "armed_home_instant",
enuSecurityMode.Away => "armed_away",
enuSecurityMode.Vacation => "armed_vacation",
_ => "disarmed",
};
}
public static string ToBasicState(this clsArea area)
{
if (area.AreaAlarms.IsBitSet(0) || // Burgulary
area.AreaAlarms.IsBitSet(3) || // Auxiliary
area.AreaAlarms.IsBitSet(6)) // Duress
return "triggered";
else if (area.ExitTimer > 0)
return "arming";
switch (area.AreaMode)
{
case enuSecurityMode.Night:
case enuSecurityMode.NightDly:
return "armed_night";
case enuSecurityMode.Day:
case enuSecurityMode.DayInst:
return "armed_home";
case enuSecurityMode.Away:
return "armed_away";
case enuSecurityMode.Vacation:
return "armed_vacation";
case enuSecurityMode.Off:
default:
return "disarmed";
}
}
public static BinarySensor ToConfigBurglary(this clsArea area)
{
BinarySensor ret = new BinarySensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}area{area.Number}burglary",
name = $"{Global.mqtt_discovery_name_prefix}{area.Name} Burglary",
device_class = BinarySensor.DeviceClass.safety,
state_topic = area.ToTopic(Topic.json_state),
value_template = "{% if value_json.burglary_alarm %} ON {%- else -%} OFF {%- endif %}"
};
return ret;
}
public static BinarySensor ToConfigFire(this clsArea area)
{
BinarySensor ret = new BinarySensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}area{area.Number}fire",
name = $"{Global.mqtt_discovery_name_prefix}{area.Name} Fire",
device_class = BinarySensor.DeviceClass.smoke,
state_topic = area.ToTopic(Topic.json_state),
value_template = "{% if value_json.fire_alarm %} ON {%- else -%} OFF {%- endif %}"
};
return ret;
}
public static BinarySensor ToConfigGas(this clsArea area)
{
BinarySensor ret = new BinarySensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}area{area.Number}gas",
name = $"{Global.mqtt_discovery_name_prefix}{area.Name} Gas",
device_class = BinarySensor.DeviceClass.gas,
state_topic = area.ToTopic(Topic.json_state),
value_template = "{% if value_json.gas_alarm %} ON {%- else -%} OFF {%- endif %}"
};
return ret;
}
public static BinarySensor ToConfigAux(this clsArea area)
{
BinarySensor ret = new BinarySensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}area{area.Number}auxiliary",
name = $"{Global.mqtt_discovery_name_prefix}{area.Name} Auxiliary",
device_class = BinarySensor.DeviceClass.problem,
state_topic = area.ToTopic(Topic.json_state),
value_template = "{% if value_json.burglary_alarm %} ON {%- else -%} OFF {%- endif %}"
};
return ret;
}
public static BinarySensor ToConfigFreeze(this clsArea area)
{
BinarySensor ret = new BinarySensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}area{area.Number}freeze",
name = $"{Global.mqtt_discovery_name_prefix}{area.Name} Freeze",
device_class = BinarySensor.DeviceClass.cold,
state_topic = area.ToTopic(Topic.json_state),
value_template = "{% if value_json.freeze_alarm %} ON {%- else -%} OFF {%- endif %}"
};
return ret;
}
public static BinarySensor ToConfigWater(this clsArea area)
{
BinarySensor ret = new BinarySensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}area{area.Number}water",
name = $"{Global.mqtt_discovery_name_prefix}{area.Name} Water",
device_class = BinarySensor.DeviceClass.moisture,
state_topic = area.ToTopic(Topic.json_state),
value_template = "{% if value_json.water_alarm %} ON {%- else -%} OFF {%- endif %}"
};
return ret;
}
public static BinarySensor ToConfigDuress(this clsArea area)
{
BinarySensor ret = new BinarySensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}area{area.Number}duress",
name = $"{Global.mqtt_discovery_name_prefix}{area.Name} Duress",
device_class = BinarySensor.DeviceClass.safety,
state_topic = area.ToTopic(Topic.json_state),
value_template = "{% if value_json.duress_alarm %} ON {%- else -%} OFF {%- endif %}"
};
return ret;
}
public static BinarySensor ToConfigTemp(this clsArea area)
{
BinarySensor ret = new BinarySensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}area{area.Number}temp",
name = $"{Global.mqtt_discovery_name_prefix}{area.Name} Temp",
device_class = BinarySensor.DeviceClass.heat,
state_topic = area.ToTopic(Topic.json_state),
value_template = "{% if value_json.temperature_alarm %} ON {%- else -%} OFF {%- endif %}"
};
return ret;
}
public static string ToJsonState(this clsArea area)
{
AreaState state = new AreaState
{
arming = area.ExitTimer > 0,
burglary_alarm = area.AreaAlarms.IsBitSet(0),
fire_alarm = area.AreaAlarms.IsBitSet(1),
gas_alarm = area.AreaAlarms.IsBitSet(2),
auxiliary_alarm = area.AreaAlarms.IsBitSet(3),
freeze_alarm = area.AreaAlarms.IsBitSet(4),
water_alarm = area.AreaAlarms.IsBitSet(5),
duress_alarm = area.AreaAlarms.IsBitSet(6),
temperature_alarm = area.AreaAlarms.IsBitSet(7),
mode = area.AreaMode switch
{
enuSecurityMode.Night => "night",
enuSecurityMode.NightDly => "night_delay",
enuSecurityMode.Day => "home",
enuSecurityMode.DayInst => "home_instant",
enuSecurityMode.Away => "away",
enuSecurityMode.Vacation => "vacation",
_ => "off",
}
};
return JsonConvert.SerializeObject(state);
}
public static string ToTopic(this clsZone zone, Topic topic)
{
return $"{Global.mqtt_prefix}/zone{zone.Number}/{topic}";
}
public static Sensor ToConfigTemp(this clsZone zone, enuTempFormat format)
{
Sensor ret = new Sensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}zone{zone.Number}temp",
name = $"{Global.mqtt_discovery_name_prefix}{zone.Name} Temp",
device_class = Sensor.DeviceClass.temperature,
state_topic = zone.ToTopic(Topic.current_temperature),
unit_of_measurement = (format == enuTempFormat.Fahrenheit ? "°F" : "°C")
};
return ret;
}
public static Sensor ToConfigHumidity(this clsZone zone)
{
Sensor ret = new Sensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}zone{zone.Number}humidity",
name = $"{Global.mqtt_discovery_name_prefix}{zone.Name} Humidity",
device_class = Sensor.DeviceClass.humidity,
state_topic = zone.ToTopic(Topic.current_humidity),
unit_of_measurement = "%"
};
return ret;
}
public static Sensor ToConfigSensor(this clsZone zone)
{
Sensor ret = new Sensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}zone{zone.Number}",
name = Global.mqtt_discovery_name_prefix + zone.Name
};
switch (zone.ZoneType)
{
case enuZoneType.EntryExit:
case enuZoneType.X2EntryDelay:
case enuZoneType.X4EntryDelay:
ret.icon = "mdi:door";
break;
case enuZoneType.Perimeter:
ret.icon = "mdi:window-closed";
break;
case enuZoneType.Tamper:
ret.icon = "mdi:shield";
break;
case enuZoneType.AwayInt:
case enuZoneType.NightInt:
ret.icon = "mdi:walk";
break;
case enuZoneType.Water:
ret.icon = "mdi:water";
break;
case enuZoneType.Fire:
ret.icon = "mdi:fire";
break;
case enuZoneType.Gas:
ret.icon = "mdi:gas-cylinder";
break;
}
ret.value_template = @"{{ value|replace(""_"", "" "")|title }}";
ret.state_topic = zone.ToTopic(Topic.state);
return ret;
}
public static Switch ToConfigSwitch(this clsZone zone)
{
Switch ret = new Switch(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}zone{zone.Number}switch",
name = $"{Global.mqtt_discovery_name_prefix}{zone.Name} Bypass",
state_topic = zone.ToTopic(Topic.state),
command_topic = zone.ToTopic(Topic.command),
payload_off = "restore",
payload_on = "bypass",
value_template = "{% if value == 'bypassed' %} bypass {%- else -%} restore {%- endif %}"
};
return ret;
}
public static BinarySensor ToConfig(this clsZone zone)
{
BinarySensor ret = new BinarySensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}zone{zone.Number}binary",
name = Global.mqtt_discovery_name_prefix + zone.Name
};
Global.mqtt_discovery_override_zone.TryGetValue(zone.Number, out OverrideZone override_zone);
if (override_zone != null)
{
ret.device_class = override_zone.device_class;
}
else
{
switch (zone.ZoneType)
{
case enuZoneType.EntryExit:
case enuZoneType.X2EntryDelay:
case enuZoneType.X4EntryDelay:
ret.device_class = BinarySensor.DeviceClass.door;
break;
case enuZoneType.Perimeter:
ret.device_class = BinarySensor.DeviceClass.window;
break;
case enuZoneType.Tamper:
ret.device_class = BinarySensor.DeviceClass.problem;
break;
case enuZoneType.AwayInt:
case enuZoneType.NightInt:
ret.device_class = BinarySensor.DeviceClass.motion;
break;
case enuZoneType.Water:
ret.device_class = BinarySensor.DeviceClass.moisture;
break;
case enuZoneType.Fire:
ret.device_class = BinarySensor.DeviceClass.smoke;
break;
case enuZoneType.Gas:
ret.device_class = BinarySensor.DeviceClass.gas;
break;
}
}
ret.state_topic = zone.ToTopic(Topic.basic_state);
return ret;
}
public static string ToState(this clsZone zone)
{
if (zone.Status.IsBitSet(5))
return "bypassed";
else if (zone.Status.IsBitSet(2))
return "tripped";
else if (zone.Status.IsBitSet(4))
return "armed";
else if (zone.Status.IsBitSet(1))
return "trouble";
else if (zone.Status.IsBitSet(0))
return "not_ready";
else
return "secure";
}
public static string ToBasicState(this clsZone zone)
{
return zone.Status.IsBitSet(0) ? "ON" : "OFF";
}
public static string ToTopic(this clsUnit unit, Topic topic)
{
return $"{Global.mqtt_prefix}/unit{unit.Number}/{topic}";
}
public static Light ToConfig(this clsUnit unit)
{
Light ret = new Light(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}unit{unit.Number}light",
name = Global.mqtt_discovery_name_prefix + unit.Name,
state_topic = unit.ToTopic(Topic.state),
command_topic = unit.ToTopic(Topic.command),
brightness_state_topic = unit.ToTopic(Topic.brightness_state),
brightness_command_topic = unit.ToTopic(Topic.brightness_command)
};
return ret;
}
public static Switch ToConfigSwitch(this clsUnit unit)
{
Switch ret = new Switch(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}unit{unit.Number}switch",
name = Global.mqtt_discovery_name_prefix + unit.Name,
state_topic = unit.ToTopic(Topic.state),
command_topic = unit.ToTopic(Topic.command)
};
return ret;
}
public static Number ToConfigNumber(this clsUnit unit)
{
Number ret = new Number(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}unit{unit.Number}number",
name = Global.mqtt_discovery_name_prefix + unit.Name,
state_topic = unit.ToTopic(Topic.flag_state),
command_topic = unit.ToTopic(Topic.flag_command),
min = 0,
max = 255
};
return ret;
}
public static string ToState(this clsUnit unit)
{
return unit.Status == 0 || unit.Status == 100 ? UnitCommands.OFF.ToString() : UnitCommands.ON.ToString();
}
public static int ToBrightnessState(this clsUnit unit)
{
if (unit.Status > 100)
return (ushort)(unit.Status - 100);
else if (unit.Status == 1)
return 100;
else
return 0;
}
public static string ToSceneState(this clsUnit unit)
{
if (unit.Status >= 2 && unit.Status <= 13)
// 2-13 maps to scene A-L respectively
return ((char)(unit.Status + 63)).ToString();
return string.Empty;
}
public static string ToTopic(this clsThermostat thermostat, Topic topic)
{
return $"{Global.mqtt_prefix}/thermostat{thermostat.Number}/{topic}";
}
public static Sensor ToConfigTemp(this clsThermostat thermostat, enuTempFormat format)
{
Sensor ret = new Sensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}thermostat{thermostat.Number}temp",
name = $"{Global.mqtt_discovery_name_prefix}{thermostat.Name} Temp",
device_class = Sensor.DeviceClass.temperature,
state_topic = thermostat.ToTopic(Topic.current_temperature),
unit_of_measurement = (format == enuTempFormat.Fahrenheit ? "°F" : "°C")
};
return ret;
}
public static Number ToConfigHumidify(this clsThermostat thermostat)
{
Number ret = new Number(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}thermostat{thermostat.Number}humidify",
name = $"{Global.mqtt_discovery_name_prefix}{thermostat.Name} Humidify",
icon = "mdi:water-percent",
state_topic = thermostat.ToTopic(Topic.humidify_state),
command_topic = thermostat.ToTopic(Topic.humidify_command),
};
return ret;
}
public static Number ToConfigDehumidify(this clsThermostat thermostat)
{
Number ret = new Number(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}thermostat{thermostat.Number}dehumidify",
name = $"{Global.mqtt_discovery_name_prefix}{thermostat.Name} Dehumidify",
icon = "mdi:water-percent",
state_topic = thermostat.ToTopic(Topic.dehumidify_state),
command_topic = thermostat.ToTopic(Topic.dehumidify_command),
};
return ret;
}
public static Sensor ToConfigHumidity(this clsThermostat thermostat)
{
Sensor ret = new Sensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}thermostat{thermostat.Number}humidity",
name = $"{Global.mqtt_discovery_name_prefix}{thermostat.Name} Humidity",
device_class = Sensor.DeviceClass.humidity,
state_topic = thermostat.ToTopic(Topic.current_humidity),
unit_of_measurement = "%"
};
return ret;
}
public static Climate ToConfig(this clsThermostat thermostat, enuTempFormat format)
{
Climate ret = new Climate(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}thermostat{thermostat.Number}",
name = Global.mqtt_discovery_name_prefix + thermostat.Name,
availability_topic = null,
availability_mode = Device.AvailabilityMode.all,
availability = new List<Availability>()
{
new Availability(),
new Availability() { topic = thermostat.ToTopic(Topic.status) }
},
modes = thermostat.Type switch
{
enuThermostatType.AutoHeatCool => new List<string>(new string[] { "auto", "off", "cool", "heat" }),
enuThermostatType.HeatCool => new List<string>(new string[] { "off", "cool", "heat" }),
enuThermostatType.HeatOnly => new List<string>(new string[] { "off", "heat" }),
enuThermostatType.CoolOnly => new List<string>(new string[] { "off", "cool" }),
_ => new List<string>(new string[] { "off" }),
},
action_topic = thermostat.ToTopic(Topic.current_operation),
current_temperature_topic = thermostat.ToTopic(Topic.current_temperature),
temperature_low_state_topic = thermostat.ToTopic(Topic.temperature_heat_state),
temperature_low_command_topic = thermostat.ToTopic(Topic.temperature_heat_command),
temperature_high_state_topic = thermostat.ToTopic(Topic.temperature_cool_state),
temperature_high_command_topic = thermostat.ToTopic(Topic.temperature_cool_command),
mode_state_topic = thermostat.ToTopic(Topic.mode_basic_state),
mode_command_topic = thermostat.ToTopic(Topic.mode_command),
fan_mode_state_topic = thermostat.ToTopic(Topic.fan_mode_state),
fan_mode_command_topic = thermostat.ToTopic(Topic.fan_mode_command),
preset_mode_state_topic = thermostat.ToTopic(Topic.hold_state),
preset_mode_command_topic = thermostat.ToTopic(Topic.hold_command)
};
if (format == enuTempFormat.Celsius)
{
ret.min_temp = "7";
ret.max_temp = "35";
}
return ret;
}
public static string ToOperationState(this clsThermostat thermostat)
{
if (thermostat.HorC_Status.IsBitSet(0))
return "heating";
else if (thermostat.HorC_Status.IsBitSet(1))
return "cooling";
else
return "idle";
}
public static string ToModeState(this clsThermostat thermostat)
{
if (thermostat.Mode == enuThermostatMode.E_Heat)
return "e_heat";
else
return thermostat.ModeText().ToLower();
}
public static string ToModeBasicState(this clsThermostat thermostat)
{
if (thermostat.Mode == enuThermostatMode.E_Heat)
return "heat";
else
return thermostat.ModeText().ToLower();
}
public static string ToTopic(this clsButton button, Topic topic)
{
return $"{Global.mqtt_prefix}/button{button.Number}/{topic}";
}
public static Switch ToConfigSwitch(this clsButton button)
{
Switch ret = new Switch(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}button{button.Number}",
name = Global.mqtt_discovery_name_prefix + button.Name,
state_topic = button.ToTopic(Topic.state),
command_topic = button.ToTopic(Topic.command)
};
return ret;
}
public static Button ToConfigButton(this clsButton button)
{
Button ret = new Button(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}button{button.Number}",
name = Global.mqtt_discovery_name_prefix + button.Name,
command_topic = button.ToTopic(Topic.command),
payload_press = "ON"
};
return ret;
}
public static string ToTopic(this clsMessage message, Topic topic)
{
return $"{Global.mqtt_prefix}/message{message.Number}/{topic}";
}
public static string ToState(this clsMessage message)
{
if (message.Status == enuMessageStatus.Displayed)
return "displayed";
else if (message.Status == enuMessageStatus.NotAcked)
return "displayed_not_acknowledged";
else
return "off";
}
public static string ToTopic(this clsAccessControlReader reader, Topic topic)
{
return $"{Global.mqtt_prefix}/lock{reader.Number}/{topic}";
}
public static Lock ToConfig(this clsAccessControlReader reader)
{
Lock ret = new Lock(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}lock{reader.Number}",
name = Global.mqtt_discovery_name_prefix + reader.Name,
state_topic = reader.ToTopic(Topic.state),
command_topic = reader.ToTopic(Topic.command),
payload_lock = "lock",
payload_unlock = "unlock",
state_locked = "locked",
state_unlocked = "unlocked"
};
return ret;
}
public static string ToState(this clsAccessControlReader reader)
{
if (reader.LockStatus == 0)
return "locked";
else
return "unlocked";
}
public static string ToTopic(this clsAudioSource audioSource, Topic topic)
{
return $"{Global.mqtt_prefix}/source{audioSource.Number}/{topic}";
}
public static string ToTopic(this clsAudioZone audioZone, Topic topic)
{
return $"{Global.mqtt_prefix}/audio{audioZone.Number}/{topic}";
}
public static Switch ToConfig(this clsAudioZone audioZone)
{
Switch ret = new Switch(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}audio{audioZone.Number}",
name = Global.mqtt_discovery_name_prefix + audioZone.rawName,
icon = "mdi:speaker",
state_topic = audioZone.ToTopic(Topic.state),
command_topic = audioZone.ToTopic(Topic.command)
};
return ret;
}
public static string ToState(this clsAudioZone audioZone)
{
return audioZone.Power ? "ON" : "OFF";
}
public static Switch ToConfigMute(this clsAudioZone audioZone)
{
Switch ret = new Switch(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}audio{audioZone.Number}mute",
name = $"{Global.mqtt_discovery_name_prefix}{audioZone.rawName} Mute",
icon = "mdi:volume-mute",
state_topic = audioZone.ToTopic(Topic.mute_state),
command_topic = audioZone.ToTopic(Topic.mute_command)
};
return ret;
}
public static string ToMuteState(this clsAudioZone audioZone)
{
if(Global.mqtt_audio_local_mute)
return audioZone.Volume == 0 ? "ON" : "OFF";
else
return audioZone.Mute ? "ON" : "OFF";
}
public static Select ToConfigSource(this clsAudioZone audioZone, List<string> audioSources)
{
Select ret = new Select(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}audio{audioZone.Number}source",
name = $"{Global.mqtt_discovery_name_prefix}{audioZone.rawName} Source",
icon = "mdi:volume-source",
state_topic = audioZone.ToTopic(Topic.source_state),
command_topic = audioZone.ToTopic(Topic.source_command),
options = audioSources
};
return ret;
}
public static int ToSourceState(this clsAudioZone audioZone)
{
return audioZone.Source;
}
public static Number ToConfigVolume(this clsAudioZone audioZone)
{
Number ret = new Number(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}audio{audioZone.Number}volume",
name = $"{Global.mqtt_discovery_name_prefix}{audioZone.rawName} Volume",
icon = "mdi:volume-low",
state_topic = audioZone.ToTopic(Topic.volume_state),
command_topic = audioZone.ToTopic(Topic.volume_command),
min = 0,
max = 100,
step = 1,
};
if(Global.mqtt_audio_volume_media_player)
{
ret.min = 0;
ret.max = 1;
ret.step = 0.01;
}
return ret;
}
public static double ToVolumeState(this clsAudioZone audioZone)
{
if (Global.mqtt_audio_volume_media_player)
return audioZone.Volume * 0.01;
else
return audioZone.Volume;
}
}
}

View file

@ -1,416 +0,0 @@
using HAI_Shared;
using OmniLinkBridge.MQTT.Parser;
using OmniLinkBridge.OmniLink;
using Serilog;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
namespace OmniLinkBridge.MQTT
{
public class MessageProcessor
{
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Regex regexTopic = new Regex(Global.mqtt_prefix + "/([A-Za-z]+)([0-9]+)/(.*)", RegexOptions.Compiled);
private readonly int[] audioMuteVolumes;
private const int VOLUME_DEFAULT = 10;
private IOmniLinkII OmniLink { get; }
private Dictionary<string, int> AudioSources { get; }
public MessageProcessor(IOmniLinkII omni, Dictionary<string, int> audioSources, int numAudioZones)
{
OmniLink = omni;
AudioSources = audioSources;
audioMuteVolumes = new int[numAudioZones];
}
public void Process(string messageTopic, string payload)
{
Match match = regexTopic.Match(messageTopic);
if (!match.Success)
return;
if (!Enum.TryParse(match.Groups[1].Value, true, out CommandTypes type)
|| !Enum.TryParse(match.Groups[3].Value, true, out Topic topic)
|| !ushort.TryParse(match.Groups[2].Value, out ushort id))
return;
log.Debug("Received: Type: {type}, Id: {id}, Command: {command}, Value: {value}",
type.ToString(), id, topic.ToString(), payload);
if (type == CommandTypes.area && id <= OmniLink.Controller.Areas.Count)
ProcessAreaReceived(OmniLink.Controller.Areas[id], topic, payload);
else if (type == CommandTypes.zone && id <= OmniLink.Controller.Zones.Count)
ProcessZoneReceived(OmniLink.Controller.Zones[id], topic, payload);
else if (type == CommandTypes.unit && id > 0 && id <= OmniLink.Controller.Units.Count)
ProcessUnitReceived(OmniLink.Controller.Units[id], topic, payload);
else if (type == CommandTypes.thermostat && id > 0 && id <= OmniLink.Controller.Thermostats.Count)
ProcessThermostatReceived(OmniLink.Controller.Thermostats[id], topic, payload);
else if (type == CommandTypes.button && id > 0 && id <= OmniLink.Controller.Buttons.Count)
ProcessButtonReceived(OmniLink.Controller.Buttons[id], topic, payload);
else if (type == CommandTypes.message && id > 0 && id <= OmniLink.Controller.Messages.Count)
ProcessMessageReceived(OmniLink.Controller.Messages[id], topic, payload);
else if (type == CommandTypes.@lock && id <= OmniLink.Controller.AccessControlReaders.Count)
ProcessLockReceived(OmniLink.Controller.AccessControlReaders[id], topic, payload);
else if (type == CommandTypes.audio && id <= OmniLink.Controller.AudioZones.Count)
ProcessAudioReceived(OmniLink.Controller.AudioZones[id], topic, payload);
}
private static readonly IDictionary<AreaCommands, enuUnitCommand> AreaMapping = new Dictionary<AreaCommands, enuUnitCommand>
{
{ AreaCommands.disarm, enuUnitCommand.SecurityOff },
{ AreaCommands.arm_home, enuUnitCommand.SecurityDay },
{ AreaCommands.arm_away, enuUnitCommand.SecurityAway },
{ AreaCommands.arm_night, enuUnitCommand.SecurityNight },
{ AreaCommands.arm_vacation, enuUnitCommand.SecurityVac },
// The below aren't supported by Home Assistant
{ AreaCommands.arm_home_instant, enuUnitCommand.SecurityDyi },
{ AreaCommands.arm_night_delay, enuUnitCommand.SecurityNtd }
};
private void ProcessAreaReceived(clsArea area, Topic command, string payload)
{
AreaCommandCode parser = payload.ToCommandCode(supportValidate: true);
if (parser.Success && command == Topic.command && Enum.TryParse(parser.Command, true, out AreaCommands cmd))
{
if (area.Number == 0)
log.Debug("SetArea: 0 implies all areas will be changed");
if (parser.Validate)
{
string sCode = parser.Code.ToString();
if (sCode.Length != 4)
{
log.Warning("SetArea: {id}, Invalid security code: must be 4 digits", area.Number);
return;
}
OmniLink.Controller.Connection.Send(new clsOL2MsgRequestValidateCode(OmniLink.Controller.Connection)
{
Area = (byte)area.Number,
Digit1 = (byte)int.Parse(sCode[0].ToString()),
Digit2 = (byte)int.Parse(sCode[1].ToString()),
Digit3 = (byte)int.Parse(sCode[2].ToString()),
Digit4 = (byte)int.Parse(sCode[3].ToString())
}, (M, B, Timeout) =>
{
if (Timeout || !((B.Length > 3) && (B[0] == 0x21) && (enuOmniLink2MessageType)B[2] == enuOmniLink2MessageType.ValidateCode))
return;
var validateCode = new clsOL2MsgValidateCode(OmniLink.Controller.Connection, B);
if (validateCode.AuthorityLevel == 0)
{
log.Warning("SetArea: {id}, Invalid security code: validation failed", area.Number);
return;
}
log.Debug("SetArea: {id}, Validated security code, Code Number: {code}, Authority: {authority}",
area.Number, validateCode.CodeNumber, validateCode.AuthorityLevel.ToString());
log.Debug("SetArea: {id} to {value}, Code Number: {code}",
area.Number, cmd.ToString().Replace("arm_", "").Replace("_", " "), validateCode.CodeNumber);
OmniLink.SendCommand(AreaMapping[cmd], validateCode.CodeNumber, (ushort)area.Number);
});
return;
}
log.Debug("SetArea: {id} to {value}, Code Number: {code}",
area.Number, cmd.ToString().Replace("arm_", "").Replace("_", " "), parser.Code);
OmniLink.SendCommand(AreaMapping[cmd], (byte)parser.Code, (ushort)area.Number);
}
else if (command == Topic.alarm_command && area.Number > 0 && Enum.TryParse(parser.Command, true, out AlarmCommands alarm))
{
log.Debug("SetAreaAlarm: {id} to {value}", area.Number, parser.Command);
OmniLink.Controller.Connection.Send(new clsOL2MsgActivateKeypadEmg(OmniLink.Controller.Connection)
{
Area = (byte)area.Number,
EmgType = (byte)alarm
}, (M, B, Timeout) => { });
}
}
private static readonly IDictionary<ZoneCommands, enuUnitCommand> ZoneMapping = new Dictionary<ZoneCommands, enuUnitCommand>
{
{ ZoneCommands.restore, enuUnitCommand.Restore },
{ ZoneCommands.bypass, enuUnitCommand.Bypass },
};
private void ProcessZoneReceived(clsZone zone, Topic command, string payload)
{
AreaCommandCode parser = payload.ToCommandCode();
if (parser.Success && command == Topic.command && Enum.TryParse(parser.Command, true, out ZoneCommands cmd) &&
!(zone.Number == 0 && cmd == ZoneCommands.bypass))
{
if (zone.Number == 0)
log.Debug("SetZone: 0 implies all zones will be restored");
log.Debug("SetZone: {id} to {value}", zone.Number, parser.Command);
OmniLink.SendCommand(ZoneMapping[cmd], (byte)parser.Code, (ushort)zone.Number);
}
}
private static readonly IDictionary<UnitCommands, enuUnitCommand> UnitMapping = new Dictionary<UnitCommands, enuUnitCommand>
{
{ UnitCommands.OFF, enuUnitCommand.Off },
{ UnitCommands.ON, enuUnitCommand.On }
};
private void ProcessUnitReceived(clsUnit unit, Topic command, string payload)
{
if (command == Topic.command && Enum.TryParse(payload, true, out UnitCommands cmd))
{
if (string.Compare(unit.ToState(), cmd.ToString()) != 0)
{
log.Debug("SetUnit: {id} to {value}", unit.Number, cmd.ToString());
OmniLink.SendCommand(UnitMapping[cmd], 0, (ushort)unit.Number);
}
}
else if (unit.Type == enuOL2UnitType.Flag &&
command == Topic.flag_command && int.TryParse(payload, out int flagValue))
{
log.Debug("SetUnit: {id} to {value}", unit.Number, payload);
OmniLink.SendCommand(enuUnitCommand.Set, BitConverter.GetBytes(flagValue)[0], (ushort)unit.Number);
}
else if (unit.Type != enuOL2UnitType.Output &&
command == Topic.brightness_command && int.TryParse(payload, out int unitValue))
{
log.Debug("SetUnit: {id} to {value}%", unit.Number, payload);
OmniLink.SendCommand(enuUnitCommand.Level, BitConverter.GetBytes(unitValue)[0], (ushort)unit.Number);
// Force status change instead of waiting on controller to update
// Home Assistant sends brightness immediately followed by ON,
// which will cause light to go to 100% brightness
unit.Status = (byte)(100 + unitValue);
}
else if (unit.Type != enuOL2UnitType.Output &&
command == Topic.scene_command && char.TryParse(payload, out char scene))
{
log.Debug("SetUnit: {id} to {value}", unit.Number, payload);
OmniLink.SendCommand(enuUnitCommand.Compose, (byte)(scene - 63), (ushort)unit.Number);
}
}
private void ProcessThermostatReceived(clsThermostat thermostat, Topic command, string payload)
{
if (command == Topic.temperature_heat_command && double.TryParse(payload, out double tempLow))
{
string tempUnit = "C";
if (OmniLink.Controller.TempFormat == enuTempFormat.Fahrenheit)
{
tempLow = tempLow.ToCelsius();
tempUnit = "F";
}
int temp = tempLow.ToOmniTemp();
log.Debug("SetThermostatHeatSetpoint: {id} to {value}{temperatureUnit} ({temp})",
thermostat.Number, payload, tempUnit, temp);
OmniLink.SendCommand(enuUnitCommand.SetLowSetPt, BitConverter.GetBytes(temp)[0], (ushort)thermostat.Number);
}
else if (command == Topic.temperature_cool_command && double.TryParse(payload, out double tempHigh))
{
string tempUnit = "C";
if (OmniLink.Controller.TempFormat == enuTempFormat.Fahrenheit)
{
tempHigh = tempHigh.ToCelsius();
tempUnit = "F";
}
int temp = tempHigh.ToOmniTemp();
log.Debug("SetThermostatCoolSetpoint: {id} to {value}{temperatureUnit} ({temp})",
thermostat.Number, payload, tempUnit, temp);
OmniLink.SendCommand(enuUnitCommand.SetHighSetPt, BitConverter.GetBytes(temp)[0], (ushort)thermostat.Number);
}
else if (command == Topic.humidify_command && double.TryParse(payload, out double humidify))
{
// Humidity is reported where Fahrenheit temperatures 0-100 correspond to 0-100% relative humidity
int level = humidify.ToCelsius().ToOmniTemp();
log.Debug("SetThermostatHumidifySetpoint: {id} to {value}% ({level})", thermostat.Number, payload, level);
OmniLink.SendCommand(enuUnitCommand.SetHumidifySetPt, BitConverter.GetBytes(level)[0], (ushort)thermostat.Number);
}
else if (command == Topic.dehumidify_command && double.TryParse(payload, out double dehumidify))
{
int level = dehumidify.ToCelsius().ToOmniTemp();
log.Debug("SetThermostatDehumidifySetpoint: {id} to {value}% ({level})", thermostat.Number, payload, level);
OmniLink.SendCommand(enuUnitCommand.SetDeHumidifySetPt, BitConverter.GetBytes(level)[0], (ushort)thermostat.Number);
}
else if (command == Topic.mode_command && Enum.TryParse(payload, true, out enuThermostatMode mode))
{
if (thermostat.Type == enuThermostatType.AutoHeatCool ||
(thermostat.Type == enuThermostatType.HeatCool && mode != enuThermostatMode.Auto) ||
(thermostat.Type == enuThermostatType.CoolOnly &&
(mode == enuThermostatMode.Off || mode == enuThermostatMode.Cool)) ||
(thermostat.Type == enuThermostatType.HeatOnly &&
(mode == enuThermostatMode.Off || mode == enuThermostatMode.Heat || mode == enuThermostatMode.E_Heat)) ||
mode == enuThermostatMode.Off)
{
log.Debug("SetThermostatMode: {id} to {value}", thermostat.Number, payload);
OmniLink.SendCommand(enuUnitCommand.Mode, BitConverter.GetBytes((int)mode)[0], (ushort)thermostat.Number);
}
}
else if (command == Topic.fan_mode_command && Enum.TryParse(payload, true, out enuThermostatFanMode fanMode))
{
log.Debug("SetThermostatFanMode: {id} to {value}", thermostat.Number, payload);
OmniLink.SendCommand(enuUnitCommand.Fan, BitConverter.GetBytes((int)fanMode)[0], (ushort)thermostat.Number);
}
else if (command == Topic.hold_command && Enum.TryParse(payload, true, out enuThermostatHoldMode holdMode))
{
log.Debug("SetThermostatHold: {id} to {value}", thermostat.Number, payload);
OmniLink.SendCommand(enuUnitCommand.Hold, BitConverter.GetBytes((int)holdMode)[0], (ushort)thermostat.Number);
}
}
private void ProcessButtonReceived(clsButton button, Topic command, string payload)
{
if (command == Topic.command && Enum.TryParse(payload, true, out UnitCommands cmd) && cmd == UnitCommands.ON)
{
log.Debug("PushButton: {id}", button.Number);
OmniLink.SendCommand(enuUnitCommand.Button, 0, (ushort)button.Number);
}
}
private static readonly IDictionary<MessageCommands, enuUnitCommand> MessageMapping = new Dictionary<MessageCommands, enuUnitCommand>
{
{ MessageCommands.show, enuUnitCommand.ShowMsgWBeep },
{ MessageCommands.show_no_beep, enuUnitCommand.ShowMsgNoBeep },
{ MessageCommands.show_no_beep_or_led, enuUnitCommand.ShowMsgNoBeep },
{ MessageCommands.clear, enuUnitCommand.ClearMsg },
};
private void ProcessMessageReceived(clsMessage message, Topic command, string payload)
{
if (command == Topic.command && Enum.TryParse(payload, true, out MessageCommands cmd))
{
log.Debug("SetMessage: {id} to {value}", message.Number, cmd.ToString().Replace("_", " "));
byte par = 0;
if (cmd == MessageCommands.show_no_beep)
par = 1;
else if (cmd == MessageCommands.show_no_beep_or_led)
par = 2;
OmniLink.SendCommand(MessageMapping[cmd], par, (ushort)message.Number);
}
}
private static readonly IDictionary<LockCommands, enuUnitCommand> LockMapping = new Dictionary<LockCommands, enuUnitCommand>
{
{ LockCommands.@lock, enuUnitCommand.Lock },
{ LockCommands.unlock, enuUnitCommand.Unlock },
};
private void ProcessLockReceived(clsAccessControlReader reader, Topic command, string payload)
{
if (command == Topic.command && Enum.TryParse(payload, true, out LockCommands cmd))
{
if (reader.Number == 0)
log.Debug("SetLock: 0 implies all locks will be changed");
log.Debug("SetLock: {id} to {value}", reader.Number, payload);
OmniLink.SendCommand(LockMapping[cmd], 0, (ushort)reader.Number);
}
}
private void ProcessAudioReceived(clsAudioZone audioZone, Topic command, string payload)
{
if (command == Topic.command && Enum.TryParse(payload, true, out UnitCommands cmd))
{
if (audioZone.Number == 0)
log.Debug("SetAudio: 0 implies all audio zones will be changed");
log.Debug("SetAudio: {id} to {value}", audioZone.Number, payload);
OmniLink.SendCommand(enuUnitCommand.AudioZone, (byte)cmd, (ushort)audioZone.Number);
// Send power ON twice to workaround Russound standby
if(cmd == UnitCommands.ON)
{
Thread.Sleep(500);
OmniLink.SendCommand(enuUnitCommand.AudioZone, (byte)cmd, (ushort)audioZone.Number);
}
}
else if (command == Topic.mute_command && Enum.TryParse(payload, true, out UnitCommands mute))
{
if (audioZone.Number == 0)
{
if (Global.mqtt_audio_local_mute)
{
log.Warning("SetAudioMute: 0 not supported with local mute");
return;
}
else
log.Debug("SetAudioMute: 0 implies all audio zones will be changed");
}
if (Global.mqtt_audio_local_mute)
{
if (mute == UnitCommands.ON)
{
log.Debug("SetAudioMute: {id} local mute, previous volume {level}",
audioZone.Number, audioZone.Volume);
audioMuteVolumes[audioZone.Number] = audioZone.Volume;
OmniLink.SendCommand(enuUnitCommand.AudioVolume, 0, (ushort)audioZone.Number);
}
else
{
if (audioMuteVolumes[audioZone.Number] == 0)
{
log.Debug("SetAudioMute: {id} local mute, defaulting to volume {level}",
audioZone.Number, VOLUME_DEFAULT);
audioMuteVolumes[audioZone.Number] = VOLUME_DEFAULT;
}
else
{
log.Debug("SetAudioMute: {id} local mute, restoring to volume {level}",
audioZone.Number, audioMuteVolumes[audioZone.Number]);
}
OmniLink.SendCommand(enuUnitCommand.AudioVolume, (byte)audioMuteVolumes[audioZone.Number], (ushort)audioZone.Number);
}
}
else
{
log.Debug("SetAudioMute: {id} to {value}", audioZone.Number, payload);
OmniLink.SendCommand(enuUnitCommand.AudioZone, (byte)(mute + 2), (ushort)audioZone.Number);
}
}
else if (command == Topic.source_command && AudioSources.TryGetValue(payload, out int source))
{
log.Debug("SetAudioSource: {id} to {value}", audioZone.Number, payload);
OmniLink.SendCommand(enuUnitCommand.AudioSource, (byte)source, (ushort)audioZone.Number);
}
else if (command == Topic.volume_command && double.TryParse(payload, out double volume))
{
if (Global.mqtt_audio_volume_media_player)
volume *= 100;
if (volume > 100)
volume = 100;
else if (volume < 0)
volume = 0;
log.Debug("SetAudioVolume: {id} to {value}", audioZone.Number, volume);
OmniLink.SendCommand(enuUnitCommand.AudioVolume, (byte)volume, (ushort)audioZone.Number);
}
}
}
}

View file

@ -1,19 +0,0 @@
using System.Collections.Generic;
namespace OmniLinkBridge.MQTT
{
public class OverrideArea
{
public bool code_arm { get; set; }
public bool code_disarm { get; set; }
public bool arm_home { get; set; } = true;
public bool arm_away { get; set; } = true;
public bool arm_night { get; set; } = true;
public bool arm_vacation { get; set; } = true;
}
}

View file

@ -1,7 +0,0 @@
namespace OmniLinkBridge.MQTT
{
public class OverrideUnit
{
public UnitType type { get; set; }
}
}

View file

@ -1,9 +0,0 @@
using OmniLinkBridge.MQTT.HomeAssistant;
namespace OmniLinkBridge.MQTT
{
public class OverrideZone
{
public BinarySensor.DeviceClass device_class { get; set; }
}
}

View file

@ -1,9 +0,0 @@
namespace OmniLinkBridge.MQTT.Parser
{
enum AlarmCommands
{
burglary = 1,
fire = 2,
auxiliary = 3
}
}

View file

@ -1,14 +0,0 @@
namespace OmniLinkBridge.MQTT.Parser
{
enum AreaCommands
{
disarm,
arm_home,
arm_away,
arm_night,
arm_vacation,
// The below aren't supported by Home Assistant
arm_home_instant,
arm_night_delay
}
}

View file

@ -1,14 +0,0 @@
namespace OmniLinkBridge.MQTT.Parser
{
enum CommandTypes
{
area,
zone,
unit,
thermostat,
button,
message,
@lock,
audio
}
}

View file

@ -1,8 +0,0 @@
namespace OmniLinkBridge.MQTT.Parser
{
enum LockCommands
{
@lock,
unlock
}
}

View file

@ -1,10 +0,0 @@
namespace OmniLinkBridge.MQTT.Parser
{
enum MessageCommands
{
show,
show_no_beep,
show_no_beep_or_led,
clear
}
}

View file

@ -1,43 +0,0 @@
namespace OmniLinkBridge.MQTT.Parser
{
public enum Topic
{
name,
status,
state,
command,
alarm_command,
basic_state,
json_state,
brightness_state,
brightness_command,
flag_state,
flag_command,
scene_state,
scene_command,
current_operation,
current_temperature,
current_humidity,
temperature_heat_state,
temperature_heat_command,
temperature_cool_state,
temperature_cool_command,
humidify_state,
humidify_command,
dehumidify_state,
dehumidify_command,
mode_state,
mode_basic_state,
mode_command,
fan_mode_state,
fan_mode_command,
hold_state,
hold_command,
mute_state,
mute_command,
source_state,
source_command,
volume_state,
volume_command,
}
}

View file

@ -1,8 +0,0 @@
namespace OmniLinkBridge.MQTT.Parser
{
enum UnitCommands
{
OFF,
ON
}
}

View file

@ -1,8 +0,0 @@
namespace OmniLinkBridge.MQTT.Parser
{
enum ZoneCommands
{
restore,
bypass,
}
}

View file

@ -1,9 +0,0 @@
namespace OmniLinkBridge.MQTT
{
public enum UnitType
{
@switch,
light,
number
}
}

View file

@ -1,8 +0,0 @@
namespace OmniLinkBridge.Modules
{
interface IModule
{
void Startup();
void Shutdown();
}
}

View file

@ -1,457 +0,0 @@
using HAI_Shared;
using OmniLinkBridge.Notifications;
using OmniLinkBridge.OmniLink;
using Serilog;
using Serilog.Context;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Odbc;
using System.Reflection;
using System.Threading;
namespace OmniLinkBridge.Modules
{
public class LoggerModule : IModule
{
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
private bool running = true;
private readonly OmniLinkII omnilink;
private readonly List<string> alarms = new List<string>();
// mySQL Database
private OdbcConnection mysql_conn = null;
private DateTime mysql_retry = DateTime.MinValue;
private OdbcCommand mysql_command = null;
private readonly Queue<string> mysql_queue = new Queue<string>();
private readonly object mysql_lock = new object();
private readonly AutoResetEvent trigger = new AutoResetEvent(false);
public LoggerModule(OmniLinkII omni)
{
omnilink = omni;
omnilink.OnConnect += Omnilink_OnConnect;
omnilink.OnAreaStatus += Omnilink_OnAreaStatus;
omnilink.OnZoneStatus += Omnilink_OnZoneStatus;
omnilink.OnThermostatStatus += Omnilink_OnThermostatStatus;
omnilink.OnUnitStatus += Omnilink_OnUnitStatus;
omnilink.OnMessageStatus += Omnilink_OnMessageStatus;
omnilink.OnLockStatus += Omnilink_OnLockStatus;
omnilink.OnAudioZoneStatus += Omnilink_OnAudioZoneStatus;
omnilink.OnSystemStatus += Omnilink_OnSystemStatus;
}
public void Startup()
{
if (Global.mysql_logging)
{
log.Warning("MySQL logging is deprecated");
log.Information("Connecting to database");
mysql_conn = new OdbcConnection(Global.mysql_connection);
}
while (true)
{
// End gracefully when not logging or database queue empty
if (!running && (!Global.mysql_logging || DBQueueCount() == 0))
break;
// Make sure database connection is active
if (Global.mysql_logging && mysql_conn.State != ConnectionState.Open)
{
// Nothing we can do if shutting down
if (!running)
break;
if (mysql_retry < DateTime.Now)
DBOpen();
if (mysql_conn.State != ConnectionState.Open)
{
// Loop to prevent database queries from executing
trigger.WaitOne(new TimeSpan(0, 0, 1));
continue;
}
}
// Sleep when not logging or database queue empty
if (!Global.mysql_logging || DBQueueCount() == 0)
{
trigger.WaitOne(new TimeSpan(0, 0, 1));
continue;
}
// Grab a copy in case the database query fails
string query;
lock (mysql_lock)
query = mysql_queue.Peek();
try
{
// Execute the database query
mysql_command = new OdbcCommand(query, mysql_conn);
mysql_command.ExecuteNonQuery();
// Successful remove query from queue
lock (mysql_lock)
mysql_queue.Dequeue();
}
catch (Exception ex)
{
if (mysql_conn.State != ConnectionState.Open)
{
log.Warning("Lost connection to database");
}
else
{
log.Error(ex, "Error executing {query}", query);
// Prevent an endless loop from failed query
lock (mysql_lock)
mysql_queue.Dequeue();
}
}
}
if (Global.mysql_logging)
DBClose();
}
public void Shutdown()
{
running = false;
trigger.Set();
}
private void Omnilink_OnConnect(object sender, EventArgs e)
{
ushort areaUsage = 0;
for (ushort i = 1; i <= omnilink.Controller.Areas.Count; i++)
{
clsArea area = omnilink.Controller.Areas[i];
if (i > 1 && area.DefaultProperties == true)
continue;
areaUsage++;
if (Global.verbose_area)
{
string status = area.ModeText();
if (area.ExitTimer > 0)
status = "ARMING " + status;
if (area.EntryTimer > 0)
status = "TRIPPED " + status;
log.Verbose("Initial AreaStatus {id} {name}, Status: {status}, Alarms: {alarms}", i, area.Name, status, area.AreaAlarms);
}
}
ushort zoneUsage = 0;
for (ushort i = 1; i <= omnilink.Controller.Zones.Count; i++)
{
clsZone zone = omnilink.Controller.Zones[i];
if (zone.DefaultProperties == true)
continue;
zoneUsage++;
if (Global.verbose_zone)
{
if (zone.IsTemperatureZone())
log.Verbose("Initial ZoneStatus {id} {name}, Temp: {temp}", i, zone.Name, zone.TempText());
else
log.Verbose("Initial ZoneStatus {id} {name}, Status: {status}", i, zone.Name, zone.StatusText());
}
}
ushort unitUsage = 0, outputUsage = 0, flagUsage = 0;
for (ushort i = 1; i <= omnilink.Controller.Units.Count; i++)
{
clsUnit unit = omnilink.Controller.Units[i];
if (unit.DefaultProperties == true)
continue;
if (unit.Type == enuOL2UnitType.Output)
outputUsage++;
else if (unit.Type == enuOL2UnitType.Flag)
flagUsage++;
else
unitUsage++;
if (Global.verbose_unit)
log.Verbose("Initial UnitStatus {id} {name}, Status: {status}", i, unit.Name, unit.StatusText);
}
ushort thermostatUsage = 0;
for (ushort i = 1; i <= omnilink.Controller.Thermostats.Count; i++)
{
clsThermostat thermostat = omnilink.Controller.Thermostats[i];
if (thermostat.DefaultProperties == true)
continue;
thermostatUsage++;
}
ushort lockUsage = 0;
for (ushort i = 1; i <= omnilink.Controller.AccessControlReaders.Count; i++)
{
clsAccessControlReader reader = omnilink.Controller.AccessControlReaders[i];
if (reader.DefaultProperties == true)
continue;
lockUsage++;
if(Global.verbose_lock)
log.Verbose("Initial LockStatus {id} {name}, Status: {status}", i, reader.Name, reader.LockStatusText());
}
ushort audioSourceUsage = 0;
for (ushort i = 1; i <= omnilink.Controller.AudioSources.Count; i++)
{
clsAudioSource audioSource = omnilink.Controller.AudioSources[i];
if (audioSource.DefaultProperties == true)
continue;
audioSourceUsage++;
if (Global.verbose_audio)
log.Verbose("Initial AudioSource {id} {name}", i, audioSource.rawName);
}
ushort audioZoneUsage = 0;
for (ushort i = 1; i <= omnilink.Controller.AudioZones.Count; i++)
{
clsAudioZone audioZone = omnilink.Controller.AudioZones[i];
if (audioZone.DefaultProperties == true)
continue;
audioZoneUsage++;
if (Global.verbose_audio)
log.Verbose("Initial AudioZoneStatus {id} {name}, Power: {power}, Source: {source}, Volume: {volume}, Mute: {mute}",
i, audioZone.rawName, audioZone.Power, audioZone.Source, audioZone.Volume, audioZone.Mute);
}
using (LogContext.PushProperty("Telemetry", "ControllerUsage"))
log.Debug("Controller has {AreaUsage} areas, {ZoneUsage} zones, {UnitUsage} units, " +
"{OutputUsage} outputs, {FlagUsage} flags, {ThermostatUsage} thermostats, {LockUsage} locks, " +
"{AudioSourceUsage} audio sources, {AudioZoneUsage} audio zones",
areaUsage, zoneUsage, unitUsage, outputUsage, flagUsage, thermostatUsage, lockUsage,
audioSourceUsage, audioZoneUsage);
}
private void Omnilink_OnAreaStatus(object sender, AreaStatusEventArgs e)
{
AlarmNotification(e, 0, "BURGLARY", e.Area.AreaBurglaryAlarmText);
AlarmNotification(e, 1, "FIRE", e.Area.AreaFireAlarmText);
AlarmNotification(e, 2, "GAS", e.Area.AreaGasAlarmText);
AlarmNotification(e, 3, "AUX", e.Area.AreaAuxAlarmText);
AlarmNotification(e, 6, "DURESS", e.Area.AreaDuressAlarmText);
string status = e.Area.ModeText();
if (e.Area.ExitTimer > 0)
status = "ARMING " + status;
if (e.Area.EntryTimer > 0)
status = "TRIPPED " + status;
DBQueue(@"
INSERT INTO log_areas (timestamp, id, name,
fire, police, auxiliary,
duress, security)
VALUES ('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + e.ID.ToString() + "','" + e.Area.Name + "','" +
e.Area.AreaFireAlarmText + "','" + e.Area.AreaBurglaryAlarmText + "','" + e.Area.AreaAuxAlarmText + "','" +
e.Area.AreaDuressAlarmText + "','" + status + "')");
if (Global.verbose_area)
log.Verbose("AreaStatus {id} {name}, Status: {status}, Alarms: {alarms}", e.ID, e.Area.Name, status, e.Area.AreaAlarms);
if (Global.notify_area && e.Area.LastMode != e.Area.AreaMode)
Notification.Notify("Security", e.Area.Name + " " + e.Area.ModeText());
}
private void AlarmNotification(AreaStatusEventArgs e, int alarmBit, string alarmType, string alarmText)
{
if (e.Area.AreaAlarms.IsBitSet(alarmBit))
{
Notification.Notify("ALARM", $"{alarmType} {e.Area.Name} {alarmText}", NotificationPriority.Emergency);
if (!alarms.Contains(alarmType + e.ID))
alarms.Add(alarmType + e.ID);
}
else if (alarms.Contains(alarmType + e.ID))
{
Notification.Notify("ALARM CLEARED", $"{alarmType} {e.Area.Name} {alarmText}", NotificationPriority.High);
alarms.Remove(alarmType + e.ID);
}
}
private void Omnilink_OnZoneStatus(object sender, ZoneStatusEventArgs e)
{
DBQueue(@"
INSERT INTO log_zones (timestamp, id, name, status)
VALUES ('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + e.ID + "','" + e.Zone.Name + "','" + e.Zone.StatusText() + "')");
if (Global.verbose_zone)
{
if (e.Zone.IsTemperatureZone())
log.Verbose("ZoneStatus {id} {name}, Temp: {temp}", e.ID, e.Zone.Name, e.Zone.TempText());
else
log.Verbose("ZoneStatus {id} {name}, Status: {status}", e.ID, e.Zone.Name, e.Zone.StatusText());
}
}
private void Omnilink_OnThermostatStatus(object sender, ThermostatStatusEventArgs e)
{
int.TryParse(e.Thermostat.TempText(), out int temp);
int.TryParse(e.Thermostat.HeatSetpointText(), out int heat);
int.TryParse(e.Thermostat.CoolSetpointText(), out int cool);
int.TryParse(e.Thermostat.HumidityText(), out int humidity);
int.TryParse(e.Thermostat.HumidifySetpointText(), out int humidify);
int.TryParse(e.Thermostat.DehumidifySetpointText(), out int dehumidify);
// Log all events including thermostat polling
DBQueue(@"
INSERT INTO log_thermostats (timestamp, id, name,
status, temp, heat, cool,
humidity, humidify, dehumidify,
mode, fan, hold)
VALUES ('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "','" + e.ID + "','" + e.Thermostat.Name + "','" +
e.Thermostat.HorC_StatusText() + "','" + temp.ToString() + "','" + heat + "','" + cool + "','" +
humidity + "','" + humidify + "','" + dehumidify + "','" +
e.Thermostat.ModeText() + "','" + e.Thermostat.FanModeText() + "','" + e.Thermostat.HoldStatusText() + "')");
if (e.Offline)
log.Warning("Unknown temp for Thermostat {thermostatName}, verify thermostat is online",
e.Thermostat.Name);
// Ignore events fired by thermostat polling
if (!e.EventTimer && Global.verbose_thermostat)
log.Verbose("ThermostatStatus {id} {name}, Status: {temp} {status}, " +
"Heat {heat}, Cool: {cool}, Mode: {mode}, Fan: {fan}, Hold: {hold}",
e.ID, e.Thermostat.Name,
e.Thermostat.TempText(), e.Thermostat.HorC_StatusText(),
e.Thermostat.HeatSetpointText(),
e.Thermostat.CoolSetpointText(),
e.Thermostat.ModeText(),
e.Thermostat.FanModeText(),
e.Thermostat.HoldStatusText());
}
private void Omnilink_OnUnitStatus(object sender, UnitStatusEventArgs e)
{
string status = e.Unit.StatusText;
if (e.Unit.Status == 100 && e.Unit.StatusTime == 0)
status = "OFF";
else if (e.Unit.Status == 200 && e.Unit.StatusTime == 0)
status = "ON";
DBQueue(@"
INSERT INTO log_units (timestamp, id, name,
status, statusvalue, statustime)
VALUES ('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + e.ID + "','" + e.Unit.Name + "','" +
status + "','" + e.Unit.Status + "','" + e.Unit.StatusTime + "')");
if (Global.verbose_unit)
log.Verbose("UnitStatus {id} {name}, Status: {status}, Value: {value}", e.ID, e.Unit.Name, status, e.Unit.Status);
}
private void Omnilink_OnMessageStatus(object sender, MessageStatusEventArgs e)
{
DBQueue(@"
INSERT INTO log_messages (timestamp, id, name, status)
VALUES ('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + e.ID + "','" + e.Message.Name + "','" + e.Message.StatusText() + "')");
if (Global.verbose_message)
log.Verbose("MessageStatus {id} {name}, Status: {status}", e.ID, e.Message.Name, e.Message.StatusText());
if (Global.notify_message)
Notification.Notify("Message", e.ID + " " + e.Message.Name + ", " + e.Message.StatusText());
}
private void Omnilink_OnLockStatus(object sender, LockStatusEventArgs e)
{
if (Global.verbose_lock)
log.Verbose("LockStatus {id} {name}, Status: {status}", e.ID, e.Reader.Name, e.Reader.LockStatusText());
}
private void Omnilink_OnAudioZoneStatus(object sender, AudioZoneStatusEventArgs e)
{
if (Global.verbose_audio)
log.Verbose("AudioZoneStatus {id} {name}, Power: {power}, Source: {source}, Volume: {volume}, Mute: {mute}",
e.ID, e.AudioZone.rawName, e.AudioZone.Power, e.AudioZone.Source, e.AudioZone.Volume, e.AudioZone.Mute);
}
private void Omnilink_OnSystemStatus(object sender, SystemStatusEventArgs e)
{
DBQueue(@"
INSERT INTO log_events (timestamp, name, status)
VALUES ('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + e.Type.ToString() + "','" + e.Value + "')");
if (Global.verbose_event)
log.Verbose("SystemEvent {name}, Status: {status}", e.Type.ToString(), e.Value);
if (e.SendNotification)
Notification.Notify("SystemEvent", e.Type.ToString() + " " + e.Value);
}
public bool DBOpen()
{
try
{
if (mysql_conn.State != ConnectionState.Open)
mysql_conn.Open();
mysql_retry = DateTime.MinValue;
}
catch (Exception ex)
{
log.Error(ex, "Failed to connect to database");
mysql_retry = DateTime.Now.AddMinutes(1);
return false;
}
return true;
}
public void DBClose()
{
if (mysql_conn.State != ConnectionState.Closed)
mysql_conn.Close();
}
public void DBQueue(string query)
{
if (!Global.mysql_logging)
return;
lock (mysql_lock)
mysql_queue.Enqueue(query);
}
private int DBQueueCount()
{
int count;
lock (mysql_lock)
count = mysql_queue.Count;
return count;
}
}
}

View file

@ -1,747 +0,0 @@
using HAI_Shared;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Options;
using MQTTnet.Client.Receiving;
using MQTTnet.Extensions.ManagedClient;
using MQTTnet.Protocol;
using Newtonsoft.Json;
using OmniLinkBridge.MQTT;
using OmniLinkBridge.MQTT.HomeAssistant;
using OmniLinkBridge.MQTT.Parser;
using OmniLinkBridge.OmniLink;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace OmniLinkBridge.Modules
{
public class MQTTModule : IModule
{
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
public static DeviceRegistry MqttDeviceRegistry { get; set; }
private OmniLinkII OmniLink { get; set; }
private IManagedMqttClient MqttClient { get; set; }
private bool ControllerConnected { get; set; }
private MessageProcessor MessageProcessor { get; set; }
private Dictionary<string, int> AudioSources { get; set; } = new Dictionary<string, int>();
private readonly AutoResetEvent trigger = new AutoResetEvent(false);
private const string ONLINE = "online";
private const string OFFLINE = "offline";
private const string SECURE = "secure";
private const string TROUBLE = "trouble";
public MQTTModule(OmniLinkII omni)
{
OmniLink = omni;
OmniLink.OnConnect += OmniLink_OnConnect;
OmniLink.OnDisconnect += OmniLink_OnDisconnect;
OmniLink.OnAreaStatus += Omnilink_OnAreaStatus;
OmniLink.OnZoneStatus += Omnilink_OnZoneStatus;
OmniLink.OnUnitStatus += Omnilink_OnUnitStatus;
OmniLink.OnThermostatStatus += Omnilink_OnThermostatStatus;
OmniLink.OnButtonStatus += OmniLink_OnButtonStatus;
OmniLink.OnMessageStatus += OmniLink_OnMessageStatus;
OmniLink.OnLockStatus += OmniLink_OnLockStatus;
OmniLink.OnAudioZoneStatus += OmniLink_OnAudioZoneStatus;
OmniLink.OnSystemStatus += OmniLink_OnSystemStatus;
MessageProcessor = new MessageProcessor(omni, AudioSources, omni.Controller.CAP.numAudioZones);
}
public void Startup()
{
MqttApplicationMessage lastwill = new MqttApplicationMessage()
{
Topic = $"{Global.mqtt_prefix}/status",
Payload = Encoding.UTF8.GetBytes(OFFLINE),
QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
Retain = true
};
MqttClientOptionsBuilder options = new MqttClientOptionsBuilder()
.WithTcpServer(Global.mqtt_server)
.WithWillMessage(lastwill);
if (!string.IsNullOrEmpty(Global.mqtt_username))
options = options
.WithCredentials(Global.mqtt_username, Global.mqtt_password);
ManagedMqttClientOptions manoptions = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithClientOptions(options.Build())
.Build();
MqttClient = new MqttFactory().CreateManagedMqttClient();
MqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate((e) =>
{
log.Debug("Connected");
MqttDeviceRegistry = new DeviceRegistry()
{
identifiers = Global.mqtt_prefix,
name = Global.mqtt_prefix,
sw_version = $"{OmniLink.Controller.GetVersionText()} - OmniLinkBridge {Assembly.GetExecutingAssembly().GetName().Version}",
model = OmniLink.Controller.GetModelText(),
manufacturer = "Leviton"
};
// For the initial connection wait for the controller connected event to publish config
// For subsequent connections publish config immediately
if (ControllerConnected)
PublishConfig();
});
MqttClient.ConnectingFailedHandler = new ConnectingFailedHandlerDelegate((e) => log.Error("Error connecting {reason}", e.Exception.Message));
MqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate((e) => log.Debug("Disconnected"));
MqttClient.StartAsync(manoptions).Wait();
MqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate((e) =>
MessageProcessor.Process(e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload)));
// Subscribe to notifications for these command topics
List<Topic> toSubscribe = new List<Topic>()
{
Topic.command,
Topic.alarm_command,
Topic.brightness_command,
Topic.flag_command,
Topic.scene_command,
Topic.temperature_heat_command,
Topic.temperature_cool_command,
Topic.humidify_command,
Topic.dehumidify_command,
Topic.mode_command,
Topic.fan_mode_command,
Topic.hold_command,
Topic.mute_command,
Topic.source_command,
Topic.volume_command
};
toSubscribe.ForEach((command) => MqttClient.SubscribeAsync(
new MqttTopicFilterBuilder().WithTopic($"{Global.mqtt_prefix}/+/{command}").Build()));
// Wait until shutdown
trigger.WaitOne();
PublishControllerStatus(OFFLINE);
MqttClient.StopAsync().Wait();
}
public void Shutdown()
{
trigger.Set();
}
private void OmniLink_OnConnect(object sender, EventArgs e)
{
if(MqttClient.IsConnected)
PublishConfig();
ControllerConnected = true;
}
private void OmniLink_OnDisconnect(object sender, EventArgs e)
{
ControllerConnected = false;
if (MqttClient.IsConnected)
PublishControllerStatus(OFFLINE);
}
private void PublishControllerStatus(string status)
{
log.Information("Publishing controller {status}", status);
PublishAsync($"{Global.mqtt_prefix}/{Topic.status}", status);
}
private void PublishConfig()
{
PublishSystem();
PublishAreas();
PublishZones();
PublishUnits();
PublishThermostats();
PublishButtons();
PublishMessages();
PublishLocks();
PublishAudioSources();
PublishAudioZones();
PublishControllerStatus(ONLINE);
PublishAsync($"{Global.mqtt_prefix}/model", OmniLink.Controller.GetModelText());
PublishAsync($"{Global.mqtt_prefix}/version", OmniLink.Controller.GetVersionText());
}
private void PublishSystem()
{
log.Debug("Publishing {type}", "system");
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/system_phone/config",
JsonConvert.SerializeObject(SystemTroubleConfig("phone", "Phone")));
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/system_ac/config",
JsonConvert.SerializeObject(SystemTroubleConfig("ac", "AC")));
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/system_battery/config",
JsonConvert.SerializeObject(SystemTroubleConfig("battery", "Battery")));
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/system_dcm/config",
JsonConvert.SerializeObject(SystemTroubleConfig("dcm", "DCM")));
PublishAsync(SystemTroubleTopic("phone"), OmniLink.TroublePhone ? TROUBLE : SECURE);
PublishAsync(SystemTroubleTopic("ac"), OmniLink.TroubleAC ? TROUBLE : SECURE);
PublishAsync(SystemTroubleTopic("battery"), OmniLink.TroubleBattery ? TROUBLE : SECURE);
PublishAsync(SystemTroubleTopic("dcm"), OmniLink.TroubleDCM ? TROUBLE : SECURE);
}
public string SystemTroubleTopic(string type)
{
return $"{Global.mqtt_prefix}/system/{type}/{Topic.state}";
}
public BinarySensor SystemTroubleConfig(string type, string name)
{
return new BinarySensor(MQTTModule.MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}system{type}",
name = $"{Global.mqtt_discovery_name_prefix}System {name}",
state_topic = SystemTroubleTopic(type),
device_class = BinarySensor.DeviceClass.problem,
payload_off = SECURE,
payload_on = TROUBLE
};
}
private void PublishAreas()
{
log.Debug("Publishing {type}", "areas");
for (ushort i = 1; i <= OmniLink.Controller.Areas.Count; i++)
{
clsArea area = OmniLink.Controller.Areas[i];
// PC Access doesn't let you customize the area name when configured for one area.
// Ignore default properties for the first area.
if (i > 1 && area.DefaultProperties == true)
{
PublishAsync(area.ToTopic(Topic.name), null);
PublishAsync($"{Global.mqtt_discovery_prefix}/alarm_control_panel/{Global.mqtt_prefix}/area{i}/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}burglary/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}fire/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}gas/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}aux/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}freeze/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}water/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}duress/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}temp/config", null);
continue;
}
PublishAreaState(area);
PublishAsync(area.ToTopic(Topic.name), area.Name);
PublishAsync($"{Global.mqtt_discovery_prefix}/alarm_control_panel/{Global.mqtt_prefix}/area{i}/config",
JsonConvert.SerializeObject(area.ToConfig()));
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}burglary/config",
JsonConvert.SerializeObject(area.ToConfigBurglary()));
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}fire/config",
JsonConvert.SerializeObject(area.ToConfigFire()));
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}gas/config",
JsonConvert.SerializeObject(area.ToConfigGas()));
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}aux/config",
JsonConvert.SerializeObject(area.ToConfigAux()));
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}freeze/config",
JsonConvert.SerializeObject(area.ToConfigFreeze()));
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}water/config",
JsonConvert.SerializeObject(area.ToConfigWater()));
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}duress/config",
JsonConvert.SerializeObject(area.ToConfigDuress()));
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/area{i}temp/config",
JsonConvert.SerializeObject(area.ToConfigTemp()));
}
}
private void PublishZones()
{
log.Debug("Publishing {type}", "zones");
for (ushort i = 1; i <= OmniLink.Controller.Zones.Count; i++)
{
clsZone zone = OmniLink.Controller.Zones[i];
if (zone.DefaultProperties == true)
{
PublishAsync(zone.ToTopic(Topic.name), null);
}
else
{
PublishZoneState(zone);
PublishAsync(zone.ToTopic(Topic.name), zone.Name);
}
if (zone.DefaultProperties == true || Global.mqtt_discovery_ignore_zones.Contains(zone.Number))
{
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/zone{i}/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/sensor/{Global.mqtt_prefix}/zone{i}/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/switch/{Global.mqtt_prefix}/zone{i}/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/sensor/{Global.mqtt_prefix}/zone{i}temp/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/sensor/{Global.mqtt_prefix}/zone{i}humidity/config", null);
continue;
}
PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/{Global.mqtt_prefix}/zone{i}/config",
JsonConvert.SerializeObject(zone.ToConfig()));
PublishAsync($"{Global.mqtt_discovery_prefix}/sensor/{Global.mqtt_prefix}/zone{i}/config",
JsonConvert.SerializeObject(zone.ToConfigSensor()));
PublishAsync($"{Global.mqtt_discovery_prefix}/switch/{Global.mqtt_prefix}/zone{i}/config",
JsonConvert.SerializeObject(zone.ToConfigSwitch()));
if (zone.IsTemperatureZone())
PublishAsync($"{Global.mqtt_discovery_prefix}/sensor/{Global.mqtt_prefix}/zone{i}temp/config",
JsonConvert.SerializeObject(zone.ToConfigTemp(OmniLink.Controller.TempFormat)));
else if (zone.IsHumidityZone())
PublishAsync($"{Global.mqtt_discovery_prefix}/sensor/{Global.mqtt_prefix}/zone{i}humidity/config",
JsonConvert.SerializeObject(zone.ToConfigHumidity()));
}
}
private void PublishUnits()
{
log.Debug("Publishing {type}", "units");
for (ushort i = 1; i <= OmniLink.Controller.Units.Count; i++)
{
clsUnit unit = OmniLink.Controller.Units[i];
UnitType unitType = unit.ToUnitType();
if (unit.DefaultProperties == true)
{
PublishAsync(unit.ToTopic(Topic.name), null);
}
else
{
PublishUnitState(unit);
PublishAsync(unit.ToTopic(Topic.name), unit.Name);
}
if (unit.DefaultProperties == true || Global.mqtt_discovery_ignore_units.Contains(unit.Number))
{
foreach(UnitType entry in Enum.GetValues(typeof(UnitType)))
PublishAsync($"{Global.mqtt_discovery_prefix}/{entry}/{Global.mqtt_prefix}/unit{i}/config", null);
continue;
}
foreach (UnitType entry in Enum.GetValues(typeof(UnitType)).Cast<UnitType>().Where(x => x != unitType))
PublishAsync($"{Global.mqtt_discovery_prefix}/{entry}/{Global.mqtt_prefix}/unit{i}/config", null);
log.Verbose("Publishing {type} {id} {name} as {unitType}", "units", i, unit.Name, unitType);
if (unitType == UnitType.@switch)
PublishAsync($"{Global.mqtt_discovery_prefix}/{unitType}/{Global.mqtt_prefix}/unit{i}/config",
JsonConvert.SerializeObject(unit.ToConfigSwitch()));
else if (unitType == UnitType.light)
PublishAsync($"{Global.mqtt_discovery_prefix}/{unitType}/{Global.mqtt_prefix}/unit{i}/config",
JsonConvert.SerializeObject(unit.ToConfig()));
else if (unitType == UnitType.number)
PublishAsync($"{Global.mqtt_discovery_prefix}/{unitType}/{Global.mqtt_prefix}/unit{i}/config",
JsonConvert.SerializeObject(unit.ToConfigNumber()));
}
}
private void PublishThermostats()
{
log.Debug("Publishing {type}", "thermostats");
for (ushort i = 1; i <= OmniLink.Controller.Thermostats.Count; i++)
{
clsThermostat thermostat = OmniLink.Controller.Thermostats[i];
if (thermostat.DefaultProperties == true)
{
PublishAsync(thermostat.ToTopic(Topic.name), null);
PublishAsync($"{Global.mqtt_discovery_prefix}/climate/{Global.mqtt_prefix}/thermostat{i}/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/number/{Global.mqtt_prefix}/thermostat{i}humidify/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/number/{Global.mqtt_prefix}/thermostat{i}dehumidify/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/sensor/{Global.mqtt_prefix}/thermostat{i}temp/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/sensor/{Global.mqtt_prefix}/thermostat{i}humidity/config", null);
continue;
}
PublishThermostatState(thermostat);
PublishAsync(thermostat.ToTopic(Topic.name), thermostat.Name);
PublishAsync(thermostat.ToTopic(Topic.status), ONLINE);
PublishAsync($"{Global.mqtt_discovery_prefix}/climate/{Global.mqtt_prefix}/thermostat{i}/config",
JsonConvert.SerializeObject(thermostat.ToConfig(OmniLink.Controller.TempFormat)));
PublishAsync($"{Global.mqtt_discovery_prefix}/number/{Global.mqtt_prefix}/thermostat{i}humidify/config",
JsonConvert.SerializeObject(thermostat.ToConfigHumidify()));
PublishAsync($"{Global.mqtt_discovery_prefix}/number/{Global.mqtt_prefix}/thermostat{i}dehumidify/config",
JsonConvert.SerializeObject(thermostat.ToConfigDehumidify()));
PublishAsync($"{Global.mqtt_discovery_prefix}/sensor/{Global.mqtt_prefix}/thermostat{i}temp/config",
JsonConvert.SerializeObject(thermostat.ToConfigTemp(OmniLink.Controller.TempFormat)));
PublishAsync($"{Global.mqtt_discovery_prefix}/sensor/{Global.mqtt_prefix}/thermostat{i}humidity/config",
JsonConvert.SerializeObject(thermostat.ToConfigHumidity()));
}
}
private void PublishButtons()
{
log.Debug("Publishing {type}", "buttons");
if (Global.mqtt_discovery_button_type == typeof(Switch))
log.Information("See {setting} for new option when publishing {type}", "mqtt_discovery_button_type", "buttons");
for (ushort i = 1; i <= OmniLink.Controller.Buttons.Count; i++)
{
clsButton button = OmniLink.Controller.Buttons[i];
if (button.DefaultProperties == true)
{
PublishAsync(button.ToTopic(Topic.name), null);
PublishAsync($"{Global.mqtt_discovery_prefix}/switch/{Global.mqtt_prefix}/button{i}/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/button/{Global.mqtt_prefix}/button{i}/config", null);
continue;
}
// Buttons are off unless momentarily pressed
PublishAsync(button.ToTopic(Topic.state), "OFF");
PublishAsync(button.ToTopic(Topic.name), button.Name);
if (Global.mqtt_discovery_button_type == typeof(Switch))
{
PublishAsync($"{Global.mqtt_discovery_prefix}/button/{Global.mqtt_prefix}/button{i}/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/switch/{Global.mqtt_prefix}/button{i}/config",
JsonConvert.SerializeObject(button.ToConfigSwitch()));
}
else if (Global.mqtt_discovery_button_type == typeof(Button))
{
PublishAsync($"{Global.mqtt_discovery_prefix}/switch/{Global.mqtt_prefix}/button{i}/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/button/{Global.mqtt_prefix}/button{i}/config",
JsonConvert.SerializeObject(button.ToConfigButton()));
}
}
}
private void PublishMessages()
{
log.Debug("Publishing {type}", "messages");
for (ushort i = 1; i <= OmniLink.Controller.Messages.Count; i++)
{
clsMessage message = OmniLink.Controller.Messages[i];
if (message.DefaultProperties == true)
{
PublishAsync(message.ToTopic(Topic.name), null);
continue;
}
PublishMessageStateAsync(message);
PublishAsync(message.ToTopic(Topic.name), message.Name);
}
}
private void PublishLocks()
{
log.Debug("Publishing {type}", "locks");
for (ushort i = 1; i <= OmniLink.Controller.AccessControlReaders.Count; i++)
{
clsAccessControlReader reader = OmniLink.Controller.AccessControlReaders[i];
if (reader.DefaultProperties == true)
{
PublishAsync(reader.ToTopic(Topic.name), null);
PublishAsync($"{Global.mqtt_discovery_prefix}/lock/{Global.mqtt_prefix}/lock{i}/config", null);
continue;
}
PublishLockStateAsync(reader);
PublishAsync(reader.ToTopic(Topic.name), reader.Name);
PublishAsync($"{Global.mqtt_discovery_prefix}/lock/{Global.mqtt_prefix}/lock{i}/config",
JsonConvert.SerializeObject(reader.ToConfig()));
}
}
private void PublishAudioSources()
{
log.Debug("Publishing {type}", "audio sources");
for (ushort i = 1; i <= OmniLink.Controller.AudioSources.Count; i++)
{
clsAudioSource audioSource = OmniLink.Controller.AudioSources[i];
if (audioSource.DefaultProperties == true)
{
PublishAsync(audioSource.ToTopic(Topic.name), null);
continue;
}
PublishAsync(audioSource.ToTopic(Topic.name), audioSource.rawName);
if (AudioSources.ContainsKey(audioSource.rawName))
{
log.Warning("Duplicate audio source name {name}", audioSource.rawName);
continue;
}
AudioSources.Add(audioSource.rawName, i);
}
}
private void PublishAudioZones()
{
log.Debug("Publishing {type}", "audio zones");
for (ushort i = 1; i <= OmniLink.Controller.AudioZones.Count; i++)
{
clsAudioZone audioZone = OmniLink.Controller.AudioZones[i];
if (audioZone.DefaultProperties == true)
{
PublishAsync(audioZone.ToTopic(Topic.name), null);
PublishAsync($"{Global.mqtt_discovery_prefix}/switch/{Global.mqtt_prefix}/audio{i}/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/switch/{Global.mqtt_prefix}/audio{i}mute/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/select/{Global.mqtt_prefix}/audio{i}source/config", null);
PublishAsync($"{Global.mqtt_discovery_prefix}/number/{Global.mqtt_prefix}/audio{i}volume/config", null);
continue;
}
PublishAudioZoneStateAsync(audioZone);
PublishAsync(audioZone.ToTopic(Topic.name), audioZone.rawName);
PublishAsync($"{Global.mqtt_discovery_prefix}/switch/{Global.mqtt_prefix}/audio{i}/config",
JsonConvert.SerializeObject(audioZone.ToConfig()));
PublishAsync($"{Global.mqtt_discovery_prefix}/switch/{Global.mqtt_prefix}/audio{i}mute/config",
JsonConvert.SerializeObject(audioZone.ToConfigMute()));
PublishAsync($"{Global.mqtt_discovery_prefix}/select/{Global.mqtt_prefix}/audio{i}source/config",
JsonConvert.SerializeObject(audioZone.ToConfigSource(new List<string>(AudioSources.Keys))));
PublishAsync($"{Global.mqtt_discovery_prefix}/number/{Global.mqtt_prefix}/audio{i}volume/config",
JsonConvert.SerializeObject(audioZone.ToConfigVolume()));
}
PublishAsync($"{Global.mqtt_discovery_prefix}/button/{Global.mqtt_prefix}/audio0/config",
JsonConvert.SerializeObject(new Button(MqttDeviceRegistry)
{
unique_id = $"{Global.mqtt_prefix}audio0",
name = Global.mqtt_discovery_name_prefix + "Audio All Off",
icon = "mdi:speaker",
command_topic = $"{Global.mqtt_prefix}/audio0/{Topic.command}",
payload_press = "OFF"
}));
}
private void Omnilink_OnAreaStatus(object sender, AreaStatusEventArgs e)
{
if (!MqttClient.IsConnected)
return;
PublishAreaState(e.Area);
// Since the controller doesn't fire zone status change on area status change
// request update so armed, tripped, and secure statuses are correct
for (ushort i = 1; i <= OmniLink.Controller.Zones.Count; i++)
{
clsZone zone = OmniLink.Controller.Zones[i];
if (zone.DefaultProperties == false && zone.Area == e.Area.Number)
OmniLink.Controller.Connection.Send(new clsOL2MsgRequestExtendedStatus(
OmniLink.Controller.Connection, enuObjectType.Zone, i, i), HandleRequestZoneStatus);
}
}
private void HandleRequestZoneStatus(clsOmniLinkMessageQueueItem M, byte[] B, bool Timeout)
{
if (Timeout)
return;
clsOL2MsgExtendedStatus MSG = new clsOL2MsgExtendedStatus(OmniLink.Controller.Connection, B);
for (byte i = 0; i < MSG.ZoneStatusCount(); i++)
{
clsZone zone = OmniLink.Controller.Zones[MSG.ObjectNumber(i)];
zone.CopyExtendedStatus(MSG, i);
PublishAsync(zone.ToTopic(Topic.state), zone.ToState());
}
}
private void Omnilink_OnZoneStatus(object sender, ZoneStatusEventArgs e)
{
if (!MqttClient.IsConnected)
return;
PublishZoneState(e.Zone);
}
private void Omnilink_OnUnitStatus(object sender, UnitStatusEventArgs e)
{
if (!MqttClient.IsConnected)
return;
PublishUnitState(e.Unit);
}
private void Omnilink_OnThermostatStatus(object sender, ThermostatStatusEventArgs e)
{
if (!MqttClient.IsConnected)
return;
// Ignore events fired by thermostat polling
if (e.EventTimer)
return;
if (e.Offline)
{
PublishAsync(e.Thermostat.ToTopic(Topic.status), OFFLINE);
return;
}
PublishAsync(e.Thermostat.ToTopic(Topic.status), ONLINE);
PublishThermostatState(e.Thermostat);
}
private async void OmniLink_OnButtonStatus(object sender, ButtonStatusEventArgs e)
{
if (!MqttClient.IsConnected)
return;
await PublishButtonStateAsync(e.Button);
}
private void OmniLink_OnMessageStatus(object sender, MessageStatusEventArgs e)
{
if (!MqttClient.IsConnected)
return;
PublishMessageStateAsync(e.Message);
}
private void OmniLink_OnLockStatus(object sender, LockStatusEventArgs e)
{
if (!MqttClient.IsConnected)
return;
PublishLockStateAsync(e.Reader);
}
private void OmniLink_OnAudioZoneStatus(object sender, AudioZoneStatusEventArgs e)
{
if (!MqttClient.IsConnected)
return;
PublishAudioZoneStateAsync(e.AudioZone);
}
private void OmniLink_OnSystemStatus(object sender, SystemStatusEventArgs e)
{
if (!MqttClient.IsConnected)
return;
if(e.Type == SystemEventType.Phone)
PublishAsync(SystemTroubleTopic("phone"), e.Trouble ? TROUBLE : SECURE);
else if (e.Type == SystemEventType.AC)
PublishAsync(SystemTroubleTopic("ac"), e.Trouble ? TROUBLE : SECURE);
else if (e.Type == SystemEventType.Button)
PublishAsync(SystemTroubleTopic("battery"), e.Trouble ? TROUBLE : SECURE);
else if (e.Type == SystemEventType.DCM)
PublishAsync(SystemTroubleTopic("dcm"), e.Trouble ? TROUBLE : SECURE);
}
private void PublishAreaState(clsArea area)
{
PublishAsync(area.ToTopic(Topic.state), area.ToState());
PublishAsync(area.ToTopic(Topic.basic_state), area.ToBasicState());
PublishAsync(area.ToTopic(Topic.json_state), area.ToJsonState());
}
private void PublishZoneState(clsZone zone)
{
PublishAsync(zone.ToTopic(Topic.state), zone.ToState());
PublishAsync(zone.ToTopic(Topic.basic_state), zone.ToBasicState());
if(zone.IsTemperatureZone())
PublishAsync(zone.ToTopic(Topic.current_temperature), zone.TempText());
else if (zone.IsHumidityZone())
PublishAsync(zone.ToTopic(Topic.current_humidity), zone.TempText());
}
private void PublishUnitState(clsUnit unit)
{
PublishAsync(unit.ToTopic(Topic.state), unit.ToState());
if (unit.Type == enuOL2UnitType.Flag)
{
PublishAsync(unit.ToTopic(Topic.flag_state), ((ushort)unit.Status).ToString());
}
else if(unit.Type != enuOL2UnitType.Output)
{
PublishAsync(unit.ToTopic(Topic.brightness_state), unit.ToBrightnessState().ToString());
PublishAsync(unit.ToTopic(Topic.scene_state), unit.ToSceneState());
}
}
private void PublishThermostatState(clsThermostat thermostat)
{
PublishAsync(thermostat.ToTopic(Topic.current_operation), thermostat.ToOperationState());
PublishAsync(thermostat.ToTopic(Topic.current_temperature), thermostat.TempText());
PublishAsync(thermostat.ToTopic(Topic.current_humidity), thermostat.HumidityText());
PublishAsync(thermostat.ToTopic(Topic.temperature_heat_state), thermostat.HeatSetpointText());
PublishAsync(thermostat.ToTopic(Topic.temperature_cool_state), thermostat.CoolSetpointText());
PublishAsync(thermostat.ToTopic(Topic.humidify_state), thermostat.HumidifySetpointText());
PublishAsync(thermostat.ToTopic(Topic.dehumidify_state), thermostat.DehumidifySetpointText());
PublishAsync(thermostat.ToTopic(Topic.mode_state), thermostat.ToModeState());
PublishAsync(thermostat.ToTopic(Topic.mode_basic_state), thermostat.ToModeBasicState());
PublishAsync(thermostat.ToTopic(Topic.fan_mode_state), thermostat.FanModeText().ToLower());
PublishAsync(thermostat.ToTopic(Topic.hold_state), thermostat.HoldStatusText().ToLower());
}
private async Task PublishButtonStateAsync(clsButton button)
{
// Simulate a momentary press
await PublishAsync(button.ToTopic(Topic.state), "ON");
await Task.Delay(1000);
await PublishAsync(button.ToTopic(Topic.state), "OFF");
}
private Task PublishMessageStateAsync(clsMessage message)
{
return PublishAsync(message.ToTopic(Topic.state), message.ToState());
}
private Task PublishLockStateAsync(clsAccessControlReader reader)
{
return PublishAsync(reader.ToTopic(Topic.state), reader.ToState());
}
private void PublishAudioZoneStateAsync(clsAudioZone audioZone)
{
PublishAsync(audioZone.ToTopic(Topic.state), audioZone.ToState());
PublishAsync(audioZone.ToTopic(Topic.mute_state), audioZone.ToMuteState());
PublishAsync(audioZone.ToTopic(Topic.source_state),
OmniLink.Controller.AudioSources[audioZone.ToSourceState()].rawName);
PublishAsync(audioZone.ToTopic(Topic.volume_state), audioZone.ToVolumeState().ToString());
}
private Task PublishAsync(string topic, string payload)
{
return MqttClient.PublishAsync(topic, payload, MqttQualityOfServiceLevel.AtMostOnce, true);
}
}
}

View file

@ -1,837 +0,0 @@
using HAI_Shared;
using OmniLinkBridge.OmniLink;
using Serilog;
using Serilog.Context;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace OmniLinkBridge.Modules
{
public class OmniLinkII : IModule, IOmniLinkII
{
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
private bool running = true;
// OmniLink Controller
public clsHAC Controller { get; private set; }
private DateTime retry = DateTime.MinValue;
public bool TroublePhone { get; set; }
public bool TroubleAC { get; set; }
public bool TroubleBattery { get; set; }
public bool TroubleDCM { get; set; }
// Thermostats
private readonly Dictionary<ushort, DateTime> tstats = new Dictionary<ushort, DateTime>();
private readonly System.Timers.Timer tstat_timer = new System.Timers.Timer();
private readonly object tstat_lock = new object();
// Events
public event EventHandler<EventArgs> OnConnect;
public event EventHandler<EventArgs> OnDisconnect;
public event EventHandler<AreaStatusEventArgs> OnAreaStatus;
public event EventHandler<ZoneStatusEventArgs> OnZoneStatus;
public event EventHandler<ThermostatStatusEventArgs> OnThermostatStatus;
public event EventHandler<UnitStatusEventArgs> OnUnitStatus;
public event EventHandler<ButtonStatusEventArgs> OnButtonStatus;
public event EventHandler<MessageStatusEventArgs> OnMessageStatus;
public event EventHandler<LockStatusEventArgs> OnLockStatus;
public event EventHandler<AudioZoneStatusEventArgs> OnAudioZoneStatus;
public event EventHandler<SystemStatusEventArgs> OnSystemStatus;
private readonly AutoResetEvent trigger = new AutoResetEvent(false);
private readonly AutoResetEvent nameWait = new AutoResetEvent(false);
public OmniLinkII(string address, int port, string key1, string key2)
{
Controller = new clsHAC();
Controller.Connection.NetworkAddress = address;
Controller.Connection.NetworkPort = (ushort)port;
Controller.Connection.ControllerKey = clsUtil.HexString2ByteArray(string.Concat(key1, key2));
Controller.PreferredNetworkProtocol = clsHAC.enuPreferredNetworkProtocol.TCP;
Controller.Connection.ConnectionType = enuOmniLinkConnectionType.Network_TCP;
tstat_timer.Elapsed += tstat_timer_Elapsed;
tstat_timer.AutoReset = false;
}
public void Startup()
{
while(running)
{
// Make sure controller connection is active
if (Controller.Connection.ConnectionState == enuOmniLinkConnectionState.Offline &&
retry < DateTime.Now)
{
Connect();
}
trigger.WaitOne(new TimeSpan(0, 0, 5));
}
Disconnect();
}
public void Shutdown()
{
running = false;
trigger.Set();
}
public bool SendCommand(enuUnitCommand Cmd, byte Par, ushort Pr2)
{
log.Verbose("Sending: {command}, Par1: {par1}, Par2: {par2}", Cmd, Par, Pr2);
return Controller.SendCommand(Cmd, Par, Pr2);
}
#region Connection
private void Connect()
{
if (Controller.Connection.ConnectionState == enuOmniLinkConnectionState.Offline)
{
retry = DateTime.Now.AddMinutes(1);
log.Debug("Controller: {connectionStatus}", "Connect");
Controller.Connection.Connect(HandleConnectStatus, HandleUnsolicitedPackets);
}
}
private void Disconnect()
{
if (Controller.Connection.ConnectionState != enuOmniLinkConnectionState.Offline)
{
log.Debug("Controller: {connectionStatus}", "Disconnect");
Controller.Connection.Disconnect();
}
}
private void HandleConnectStatus(enuOmniLinkCommStatus CS)
{
var status = CS.ToString().ToSpaceTitleCase();
switch (CS)
{
case enuOmniLinkCommStatus.Connecting:
log.Debug("Controller Status: {connectionStatus}", status);
break;
case enuOmniLinkCommStatus.Connected:
IdentifyController();
break;
case enuOmniLinkCommStatus.Disconnected:
log.Information("Controller Status: {connectionStatus}", status);
OnDisconnect?.Invoke(this, new EventArgs());
break;
case enuOmniLinkCommStatus.InterruptedFunctionCall:
if (running)
log.Error("Controller Status: {connectionStatus}", status);
break;
case enuOmniLinkCommStatus.Retrying:
case enuOmniLinkCommStatus.OperationNowInProgress:
case enuOmniLinkCommStatus.OperationAlreadyInProgress:
case enuOmniLinkCommStatus.AlreadyConnected:
log.Warning("Controller Status: {connectionStatus}", status);
break;
default:
log.Error("Controller Status: {connectionStatus}", status);
break;
}
}
private void IdentifyController()
{
if (Controller.Connection.ConnectionState == enuOmniLinkConnectionState.Online ||
Controller.Connection.ConnectionState == enuOmniLinkConnectionState.OnlineSecure)
{
Controller.Connection.Send(new clsOL2MsgRequestSystemInformation(Controller.Connection), HandleIdentifyController);
}
}
private async void HandleIdentifyController(clsOmniLinkMessageQueueItem M, byte[] B, bool Timeout)
{
if (Timeout)
return;
if ((B.Length > 3) && (B[2] == (byte)enuOmniLink2MessageType.SystemInformation))
{
clsOL2MsgSystemInformation MSG = new clsOL2MsgSystemInformation(Controller.Connection, B);
foreach (enuModel enu in Enum.GetValues(typeof(enuModel)))
{
if (enu == MSG.ModelNumber)
{
Controller.Model = enu;
break;
}
}
if (Controller.Model == MSG.ModelNumber)
{
Controller.CopySystemInformation(MSG);
using (LogContext.PushProperty("Telemetry", "Controller"))
log.Information("Controller is {ControllerModel} firmware {ControllerVersion}",
Controller.GetModelText(), Controller.GetVersionText());
await ConnectedAsync();
return;
}
log.Error("Model does not match file");
Controller.Connection.Disconnect();
}
}
private async Task ConnectedAsync()
{
retry = DateTime.MinValue;
await GetNamedProperties();
UnsolicitedNotifications(true);
tstat_timer.Interval = ThermostatTimerInterval();
tstat_timer.Start();
OnConnect?.Invoke(this, new EventArgs());
Program.ShowSendLogsWarning();
}
#endregion
#region Names
private async Task GetNamedProperties()
{
log.Debug("Retrieving named units");
await GetSystemFormats();
await GetSystemTroubles();
await GetNamed(enuObjectType.Area);
await GetNamed(enuObjectType.Zone);
await GetNamed(enuObjectType.Thermostat);
await GetNamed(enuObjectType.Unit);
await GetNamed(enuObjectType.Message);
await GetNamed(enuObjectType.Button);
await GetNamed(enuObjectType.AccessControlReader);
await GetNamed(enuObjectType.AudioSource);
await GetNamed(enuObjectType.AudioZone);
}
private async Task GetSystemFormats()
{
log.Debug("Waiting for system formats");
var MSG = new clsOL2MsgRequestSystemFormats(Controller.Connection);
Controller.Connection.Send(MSG, HandleNamedPropertiesResponse);
await Task.Run(() =>
{
if(!nameWait.WaitOne(new TimeSpan(0, 0, 10)))
log.Error("Timeout occurred waiting system formats");
});
}
private async Task GetSystemTroubles()
{
log.Debug("Waiting for system troubles");
var MSG = new clsOL2MsgRequestSystemTroubles(Controller.Connection);
Controller.Connection.Send(MSG, HandleNamedPropertiesResponse);
await Task.Run(() =>
{
if(!nameWait.WaitOne(new TimeSpan(0, 0, 10)))
log.Error("Timeout occurred waiting for system troubles");
});
}
private async Task GetNamed(enuObjectType type)
{
log.Debug("Waiting for named units {unitType}", type.ToString());
GetNextNamed(type, 0);
await Task.Run(() =>
{
if (!nameWait.WaitOne(new TimeSpan(0, 0, 30)))
log.Error("Timeout occurred waiting for named units {unitType}", type.ToString());
});
}
private void GetNextNamed(enuObjectType type, int ix)
{
var MSG = new clsOL2MsgRequestProperties(Controller.Connection)
{
ObjectType = type,
IndexNumber = (UInt16)ix,
RelativeDirection = 1, // next object after IndexNumber
Filter1 = 1, // (0=Named or Unnamed, 1=Named, 2=Unnamed).
Filter2 = 0, // Any Area
Filter3 = 0 // Any Room
};
Controller.Connection.Send(MSG, HandleNamedPropertiesResponse);
}
private void HandleNamedPropertiesResponse(clsOmniLinkMessageQueueItem M, byte[] B, bool Timeout)
{
if (Timeout)
return;
// does it look like a valid response
if ((B.Length > 3) && (B[0] == 0x21))
{
switch ((enuOmniLink2MessageType)B[2])
{
case enuOmniLink2MessageType.EOD:
nameWait.Set();
break;
case enuOmniLink2MessageType.SystemFormats:
var systemFormats = new clsOL2MsgSystemFormats(Controller.Connection, B);
Controller.DateFormat = systemFormats.Date;
Controller.TimeFormat = systemFormats.Time;
Controller.TempFormat = systemFormats.Temp;
using (LogContext.PushProperty("Telemetry", "TemperatureFormat"))
log.Debug("Temperature format is {TemperatureFormat}",
(Controller.TempFormat == enuTempFormat.Fahrenheit ? "Fahrenheit" : "Celsius"));
nameWait.Set();
break;
case enuOmniLink2MessageType.SystemTroubles:
var systemTroubles = new clsOL2MsgSystemTroubles(Controller.Connection, B);
TroublePhone = systemTroubles.Contains(enuTroubles.PhoneLine);
TroubleAC = systemTroubles.Contains(enuTroubles.AC);
TroubleBattery = systemTroubles.Contains(enuTroubles.BatteryLow);
TroubleDCM = systemTroubles.Contains(enuTroubles.DCM);
nameWait.Set();
break;
case enuOmniLink2MessageType.Properties:
clsOL2MsgProperties MSG = new clsOL2MsgProperties(Controller.Connection, B);
switch (MSG.ObjectType)
{
case enuObjectType.Area:
Controller.Areas.CopyProperties(MSG);
break;
case enuObjectType.Zone:
Controller.Zones.CopyProperties(MSG);
if (Controller.Zones[MSG.ObjectNumber].IsTemperatureZone() || Controller.Zones[MSG.ObjectNumber].IsHumidityZone())
Controller.Connection.Send(new clsOL2MsgRequestExtendedStatus(Controller.Connection,
enuObjectType.Auxillary, MSG.ObjectNumber, MSG.ObjectNumber), HandleRequestAuxillaryStatus);
break;
case enuObjectType.Thermostat:
Controller.Thermostats.CopyProperties(MSG);
if (!tstats.ContainsKey(MSG.ObjectNumber))
tstats.Add(MSG.ObjectNumber, DateTime.MinValue);
else
tstats[MSG.ObjectNumber] = DateTime.MinValue;
Controller.Connection.Send(new clsOL2MsgRequestExtendedStatus(Controller.Connection,
enuObjectType.Thermostat, MSG.ObjectNumber, MSG.ObjectNumber), HandleRequestThermostatStatus);
log.Debug("Added thermostat to watch list {thermostatName}",
Controller.Thermostats[MSG.ObjectNumber].Name);
break;
case enuObjectType.Unit:
Controller.Units.CopyProperties(MSG);
break;
case enuObjectType.Message:
Controller.Messages.CopyProperties(MSG);
break;
case enuObjectType.Button:
Controller.Buttons.CopyProperties(MSG);
break;
case enuObjectType.AccessControlReader:
Controller.AccessControlReaders.CopyProperties(MSG);
break;
case enuObjectType.AudioSource:
Controller.AudioSources.CopyProperties(MSG);
Controller.AudioSources[MSG.ObjectNumber].rawName = MSG.ObjectName;
break;
case enuObjectType.AudioZone:
Controller.AudioZones.CopyProperties(MSG);
Controller.AudioZones[MSG.ObjectNumber].rawName = MSG.ObjectName;
break;
default:
break;
}
GetNextNamed(MSG.ObjectType, MSG.ObjectNumber);
break;
default:
break;
}
}
}
#endregion
#region Notifications
private void UnsolicitedNotifications(bool enable)
{
log.Debug("Unsolicited notifications {status}", (enable ? "enabled" : "disabled"));
Controller.Connection.Send(new clsOL2EnableNotifications(Controller.Connection, enable), null);
}
private bool HandleUnsolicitedPackets(byte[] B)
{
if ((B.Length > 3) && (B[0] == 0x21))
{
bool handled = false;
switch ((enuOmniLink2MessageType)B[2])
{
case enuOmniLink2MessageType.ClearNames:
break;
case enuOmniLink2MessageType.DownloadNames:
break;
case enuOmniLink2MessageType.UploadNames:
break;
case enuOmniLink2MessageType.NameData:
break;
case enuOmniLink2MessageType.ClearVoices:
break;
case enuOmniLink2MessageType.DownloadVoices:
break;
case enuOmniLink2MessageType.UploadVoices:
break;
case enuOmniLink2MessageType.VoiceData:
break;
case enuOmniLink2MessageType.Command:
break;
case enuOmniLink2MessageType.EnableNotifications:
break;
case enuOmniLink2MessageType.SystemInformation:
break;
case enuOmniLink2MessageType.SystemStatus:
break;
case enuOmniLink2MessageType.SystemTroubles:
break;
case enuOmniLink2MessageType.SystemFeatures:
break;
case enuOmniLink2MessageType.Capacities:
break;
case enuOmniLink2MessageType.Properties:
break;
case enuOmniLink2MessageType.Status:
break;
case enuOmniLink2MessageType.EventLogItem:
break;
case enuOmniLink2MessageType.ValidateCode:
break;
case enuOmniLink2MessageType.SystemFormats:
break;
case enuOmniLink2MessageType.Login:
break;
case enuOmniLink2MessageType.Logout:
break;
case enuOmniLink2MessageType.ActivateKeypadEmg:
break;
case enuOmniLink2MessageType.ExtSecurityStatus:
break;
case enuOmniLink2MessageType.CmdExtSecurity:
break;
case enuOmniLink2MessageType.AudioSourceStatus:
// Ignore audio source metadata status updates
handled = true;
break;
case enuOmniLink2MessageType.SystemEvents:
HandleUnsolicitedSystemEvent(B);
handled = true;
break;
case enuOmniLink2MessageType.ZoneReadyStatus:
break;
case enuOmniLink2MessageType.ExtendedStatus:
HandleUnsolicitedExtendedStatus(B);
handled = true;
break;
default:
break;
}
if (Global.verbose_unhandled && !handled)
log.Debug("Unhandled notification: " + ((enuOmniLink2MessageType)B[2]).ToString());
}
return true;
}
private void HandleUnsolicitedSystemEvent(byte[] B)
{
clsOL2SystemEvent MSG = new clsOL2SystemEvent(Controller.Connection, B);
SystemStatusEventArgs eventargs = new SystemStatusEventArgs();
if (MSG.SystemEvent >= 1 && MSG.SystemEvent <= 255)
{
eventargs.Type = SystemEventType.Button;
eventargs.Value = ((int)MSG.SystemEvent).ToString() + " " + Controller.Buttons[MSG.SystemEvent].Name;
OnSystemStatus?.Invoke(this, eventargs);
OnButtonStatus?.Invoke(this, new ButtonStatusEventArgs()
{
ID = MSG.SystemEvent,
Button = Controller.Buttons[MSG.SystemEvent]
});
}
else if (MSG.SystemEvent >= (ushort)enuEventType.PHONE_LINE_DEAD &&
MSG.SystemEvent <= (ushort)enuEventType.PHONE_LINE_ON_HOOK)
{
eventargs.Type = SystemEventType.Phone;
if (MSG.SystemEvent == (ushort)enuEventType.PHONE_)
{
eventargs.Value = "DEAD";
eventargs.Trouble = true;
eventargs.SendNotification = true;
}
else if (MSG.SystemEvent == (ushort)enuEventType.PHONE_LINE_RING)
eventargs.Value = "RING";
else if (MSG.SystemEvent == (ushort)enuEventType.PHONE_LINE_OFF_HOOK)
eventargs.Value = "OFF HOOK";
else if (MSG.SystemEvent == (ushort)enuEventType.PHONE_LINE_ON_HOOK)
eventargs.Value = "ON HOOK";
OnSystemStatus?.Invoke(this, eventargs);
}
else if (MSG.SystemEvent >= (ushort)enuEventType.AC_POWER_OFF &&
MSG.SystemEvent <= (ushort)enuEventType.AC_POWER_RESTORED)
{
eventargs.Type = SystemEventType.AC;
eventargs.SendNotification = true;
if (MSG.SystemEvent == (ushort)enuEventType.AC_POWER_OFF)
{
eventargs.Value = "OFF";
eventargs.Trouble = true;
}
else if (MSG.SystemEvent == (ushort)enuEventType.AC_POWER_RESTORED)
eventargs.Value = "RESTORED";
OnSystemStatus?.Invoke(this, eventargs);
}
else if (MSG.SystemEvent >= (ushort)enuEventType.BATTERY_LOW &&
MSG.SystemEvent <= (ushort)enuEventType.BATTERY_OK)
{
eventargs.Type = SystemEventType.Battery;
eventargs.SendNotification = true;
if (MSG.SystemEvent == (ushort)enuEventType.BATTERY_LOW)
{
eventargs.Value = "LOW";
eventargs.Trouble = true;
}
else if (MSG.SystemEvent == (ushort)enuEventType.BATTERY_OK)
eventargs.Value = "OK";
OnSystemStatus?.Invoke(this, eventargs);
}
else if (MSG.SystemEvent >= (ushort)enuEventType.DCM_TROUBLE &&
MSG.SystemEvent <= (ushort)enuEventType.DCM_OK)
{
eventargs.Type = SystemEventType.DCM;
eventargs.SendNotification = true;
if (MSG.SystemEvent == (ushort)enuEventType.DCM_TROUBLE)
{
eventargs.Value = "TROUBLE";
eventargs.Trouble = true;
}
else if (MSG.SystemEvent == (ushort)enuEventType.DCM_OK)
eventargs.Value = "OK";
OnSystemStatus?.Invoke(this, eventargs);
}
else if (MSG.SystemEvent >= (ushort)enuEventType.ENERGY_COST_LOW &&
MSG.SystemEvent <= (ushort)enuEventType.ENERGY_COST_CRITICAL)
{
eventargs.Type = SystemEventType.EnergyCost;
if (MSG.SystemEvent == (ushort)enuEventType.ENERGY_COST_LOW)
eventargs.Value = "LOW";
else if (MSG.SystemEvent == (ushort)enuEventType.ENERGY_COST_MID)
eventargs.Value = "MID";
else if (MSG.SystemEvent == (ushort)enuEventType.ENERGY_COST_HIGH)
eventargs.Value = "HIGH";
else if (MSG.SystemEvent == (ushort)enuEventType.ENERGY_COST_CRITICAL)
eventargs.Value = "CRITICAL";
OnSystemStatus?.Invoke(this, eventargs);
}
else if (MSG.SystemEvent >= 782 && MSG.SystemEvent <= 787)
{
eventargs.Type = SystemEventType.Camera;
eventargs.Value = (MSG.SystemEvent - 781).ToString();
OnSystemStatus?.Invoke(this, eventargs);
}
else if (MSG.SystemEvent >= 61440 && MSG.SystemEvent <= 64511)
{
eventargs.Type = SystemEventType.SwitchPress;
int state = MSG.Data[1] - 240;
int id = MSG.Data[2];
eventargs.Value = "Unit: " + id + ", State: " + state;
OnSystemStatus?.Invoke(this, eventargs);
}
else if (MSG.SystemEvent >= 64512 && MSG.SystemEvent <= 65535)
{
eventargs.Type = SystemEventType.UPBLink;
int state = MSG.Data[1] - 252;
int id = MSG.Data[2];
eventargs.Value = "Link: " + id + ", State: " + state;
OnSystemStatus?.Invoke(this, eventargs);
}
else if (Global.verbose_unhandled)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < MSG.MessageLength; i++)
sb.Append(MSG.Data[i].ToString() + " ");
log.Debug("Unhandled SystemEvent Raw: {raw}, Num: {num}", sb.ToString(), MSG.SystemEvent);
int num = (MSG.MessageLength - 1) / 2;
for (int i = 0; i < num; i++)
{
log.Debug("Unhandled SystemEvent: " +
(int)MSG.Data[(i * 2) + 1] + " " + (int)MSG.Data[(i * 2) + 2] + ": " +
Convert.ToString(MSG.Data[(i * 2) + 1], 2).PadLeft(8, '0') + " " + Convert.ToString(MSG.Data[(i * 2) + 2], 2).PadLeft(8, '0'));
}
}
}
private void HandleUnsolicitedExtendedStatus(byte[] B)
{
clsOL2MsgExtendedStatus MSG = new clsOL2MsgExtendedStatus(Controller.Connection, B);
switch (MSG.ObjectType)
{
case enuObjectType.Area:
for (byte i = 0; i < MSG.AreaCount(); i++)
{
Controller.Areas[MSG.ObjectNumber(i)].CopyExtendedStatus(MSG, i);
OnAreaStatus?.Invoke(this, new AreaStatusEventArgs()
{
ID = MSG.ObjectNumber(i),
Area = Controller.Areas[MSG.ObjectNumber(i)]
});
}
break;
case enuObjectType.Auxillary:
for (byte i = 0; i < MSG.AuxStatusCount(); i++)
{
Controller.Zones[MSG.ObjectNumber(i)].CopyAuxExtendedStatus(MSG, i);
OnZoneStatus?.Invoke(this, new ZoneStatusEventArgs()
{
ID = MSG.ObjectNumber(i),
Zone = Controller.Zones[MSG.ObjectNumber(i)]
});
}
break;
case enuObjectType.Zone:
for (byte i = 0; i < MSG.ZoneStatusCount(); i++)
{
Controller.Zones[MSG.ObjectNumber(i)].CopyExtendedStatus(MSG, i);
OnZoneStatus?.Invoke(this, new ZoneStatusEventArgs()
{
ID = MSG.ObjectNumber(i),
Zone = Controller.Zones[MSG.ObjectNumber(i)]
});
}
break;
case enuObjectType.Thermostat:
for (byte i = 0; i < MSG.ThermostatStatusCount(); i++)
{
lock (tstat_lock)
{
Controller.Thermostats[MSG.ObjectNumber(i)].CopyExtendedStatus(MSG, i);
OnThermostatStatus?.Invoke(this, new ThermostatStatusEventArgs()
{
ID = MSG.ObjectNumber(i),
Thermostat = Controller.Thermostats[MSG.ObjectNumber(i)],
Offline = Controller.Thermostats[MSG.ObjectNumber(i)].Temp == 0,
EventTimer = false
});
if (!tstats.ContainsKey(MSG.ObjectNumber(i)))
tstats.Add(MSG.ObjectNumber(i), DateTime.Now);
else
tstats[MSG.ObjectNumber(i)] = DateTime.Now;
if (Global.verbose_thermostat_timer)
log.Debug("Unsolicited status received for Thermostat {thermostatName}",
Controller.Thermostats[MSG.ObjectNumber(i)].Name);
}
}
break;
case enuObjectType.Unit:
for (byte i = 0; i < MSG.UnitStatusCount(); i++)
{
Controller.Units[MSG.ObjectNumber(i)].CopyExtendedStatus(MSG, i);
OnUnitStatus?.Invoke(this, new UnitStatusEventArgs()
{
ID = MSG.ObjectNumber(i),
Unit = Controller.Units[MSG.ObjectNumber(i)]
});
}
break;
case enuObjectType.Message:
for (byte i = 0; i < MSG.MessageCount(); i++)
{
Controller.Messages[MSG.ObjectNumber(i)].CopyExtendedStatus(MSG, i);
OnMessageStatus?.Invoke(this, new MessageStatusEventArgs()
{
ID = MSG.ObjectNumber(i),
Message = Controller.Messages[MSG.ObjectNumber(i)]
});
}
break;
case enuObjectType.AccessControlLock:
for (byte i = 0; i < MSG.AccessControlLockCount(); i++)
{
Controller.AccessControlReaders[MSG.ObjectNumber(i)].CopyExtendedStatus(MSG, i);
OnLockStatus?.Invoke(this, new LockStatusEventArgs()
{
ID = MSG.ObjectNumber(i),
Reader = Controller.AccessControlReaders[MSG.ObjectNumber(i)]
});
}
break;
case enuObjectType.AudioZone:
for (byte i = 0; i < MSG.AudioZoneStatusCount(); i++)
{
Controller.AudioZones[MSG.ObjectNumber(i)].CopyExtendedStatus(MSG, i);
OnAudioZoneStatus?.Invoke(this, new AudioZoneStatusEventArgs()
{
ID = MSG.ObjectNumber(i),
AudioZone = Controller.AudioZones[MSG.ObjectNumber(i)]
});
}
break;
default:
if (Global.verbose_unhandled)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in MSG.ToByteArray())
sb.Append(b.ToString() + " ");
log.Debug("Unhandled ExtendedStatus" + MSG.ObjectType.ToString() + " " + sb.ToString());
}
break;
}
}
#endregion
#region Thermostats
static double ThermostatTimerInterval()
{
DateTime now = DateTime.Now;
return ((60 - now.Second) * 1000 - now.Millisecond) + new TimeSpan(0, 0, 30).TotalMilliseconds;
}
private static DateTime RoundToMinute(DateTime dt)
{
return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0);
}
private void tstat_timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
lock (tstat_lock)
{
foreach (KeyValuePair<ushort, DateTime> tstat in tstats)
{
// Poll every 4 minutes if no prior update
if (RoundToMinute(tstat.Value).AddMinutes(4) <= RoundToMinute(DateTime.Now) &&
(Controller.Connection.ConnectionState == enuOmniLinkConnectionState.Online ||
Controller.Connection.ConnectionState == enuOmniLinkConnectionState.OnlineSecure))
{
Controller.Connection.Send(new clsOL2MsgRequestExtendedStatus(Controller.Connection,
enuObjectType.Thermostat, tstat.Key, tstat.Key), HandleRequestThermostatStatus);
if (Global.verbose_thermostat_timer)
log.Debug("Polling status for Thermostat {thermostatName}",
Controller.Thermostats[tstat.Key].Name);
}
// Log every minute if update within 5 minutes and connected
if (RoundToMinute(tstat.Value).AddMinutes(5) > RoundToMinute(DateTime.Now) &&
(Controller.Connection.ConnectionState == enuOmniLinkConnectionState.Online ||
Controller.Connection.ConnectionState == enuOmniLinkConnectionState.OnlineSecure))
{
OnThermostatStatus?.Invoke(this, new ThermostatStatusEventArgs()
{
ID = tstat.Key,
Thermostat = Controller.Thermostats[tstat.Key],
Offline = Controller.Thermostats[tstat.Key].Temp == 0,
EventTimer = true
});
}
else if (Global.verbose_thermostat_timer)
log.Warning("Not logging out of date status for Thermostat {thermostatName}",
Controller.Thermostats[tstat.Key].Name);
}
}
tstat_timer.Interval = ThermostatTimerInterval();
tstat_timer.Start();
}
private void HandleRequestThermostatStatus(clsOmniLinkMessageQueueItem M, byte[] B, bool Timeout)
{
if (Timeout)
return;
clsOL2MsgExtendedStatus MSG = new clsOL2MsgExtendedStatus(Controller.Connection, B);
for (byte i = 0; i < MSG.ThermostatStatusCount(); i++)
{
lock (tstat_lock)
{
Controller.Thermostats[MSG.ObjectNumber(i)].CopyExtendedStatus(MSG, i);
if (!tstats.ContainsKey(MSG.ObjectNumber(i)))
tstats.Add(MSG.ObjectNumber(i), DateTime.Now);
else
tstats[MSG.ObjectNumber(i)] = DateTime.Now;
if (Global.verbose_thermostat_timer)
log.Debug("Polling status received for Thermostat {thermostatName}",
Controller.Thermostats[MSG.ObjectNumber(i)].Name);
}
}
}
#endregion
#region Auxiliary
private void HandleRequestAuxillaryStatus(clsOmniLinkMessageQueueItem M, byte[] B, bool Timeout)
{
if (Timeout)
return;
clsOL2MsgExtendedStatus MSG = new clsOL2MsgExtendedStatus(Controller.Connection, B);
for (byte i = 0; i < MSG.AuxStatusCount(); i++)
{
Controller.Zones[MSG.ObjectNumber(i)].CopyAuxExtendedStatus(MSG, i);
}
}
#endregion
}
}

View file

@ -1,113 +0,0 @@
using HAI_Shared;
using Serilog;
using System;
using System.Reflection;
using System.Threading;
namespace OmniLinkBridge.Modules
{
public class TimeSyncModule : IModule
{
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
private OmniLinkII OmniLink { get; set; }
private readonly System.Timers.Timer tsync_timer = new System.Timers.Timer();
private DateTime tsync_check = DateTime.MinValue;
private readonly AutoResetEvent trigger = new AutoResetEvent(false);
public TimeSyncModule(OmniLinkII omni)
{
OmniLink = omni;
}
public void Startup()
{
tsync_timer.Elapsed += tsync_timer_Elapsed;
tsync_timer.AutoReset = false;
tsync_check = DateTime.MinValue;
tsync_timer.Interval = TimeTimerInterval();
tsync_timer.Start();
// Wait until shutdown
trigger.WaitOne();
tsync_timer.Stop();
}
public void Shutdown()
{
trigger.Set();
}
static double TimeTimerInterval()
{
DateTime now = DateTime.Now;
return ((60 - now.Second) * 1000 - now.Millisecond);
}
private void tsync_timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (tsync_check.AddMinutes(Global.time_interval) < DateTime.Now)
OmniLink.Controller.Connection.Send(new clsOL2MsgRequestSystemStatus(OmniLink.Controller.Connection), HandleRequestSystemStatus);
tsync_timer.Interval = TimeTimerInterval();
tsync_timer.Start();
}
private void HandleRequestSystemStatus(clsOmniLinkMessageQueueItem M, byte[] B, bool Timeout)
{
if (Timeout)
return;
tsync_check = DateTime.Now;
clsOL2MsgSystemStatus MSG = new clsOL2MsgSystemStatus(OmniLink.Controller.Connection, B);
DateTime time;
try
{
// The controller uses 2 digit years and C# uses 4 digit years
// Extract the 2 digit prefix to use when parsing the time
int year = DateTime.Now.Year / 100;
time = new DateTime(MSG.Year + (year * 100), MSG.Month, MSG.Day, MSG.Hour, MSG.Minute, MSG.Second);
}
catch
{
log.Warning("Controller time could not be parsed");
DateTime now = DateTime.Now;
OmniLink.Controller.Connection.Send(new clsOL2MsgSetTime(OmniLink.Controller.Connection,
(byte)(now.Year % 100), (byte)now.Month, (byte)now.Day, (byte)now.DayOfWeek,
(byte)now.Hour, (byte)now.Minute, (byte)(now.IsDaylightSavingTime() ? 1 : 0)), HandleSetTime);
return;
}
double adj = (DateTime.Now - time).Duration().TotalSeconds;
if (adj > Global.time_drift)
{
log.Warning("Controller time {controllerTime} out of sync by {driftSeconds} seconds",
time.ToString("MM/dd/yyyy HH:mm:ss"), adj);
DateTime now = DateTime.Now;
OmniLink.Controller.Connection.Send(new clsOL2MsgSetTime(OmniLink.Controller.Connection,
(byte)(now.Year % 100), (byte)now.Month, (byte)now.Day, (byte)now.DayOfWeek,
(byte)now.Hour, (byte)now.Minute, (byte)(now.IsDaylightSavingTime() ? 1 : 0)), HandleSetTime);
}
}
private void HandleSetTime(clsOmniLinkMessageQueueItem M, byte[] B, bool Timeout)
{
if (Timeout)
return;
log.Debug("Controller time has been successfully set");
}
}
}

View file

@ -1,99 +0,0 @@
using Newtonsoft.Json;
using OmniLinkBridge.Modules;
using OmniLinkBridge.OmniLink;
using OmniLinkBridge.WebAPI;
using Serilog;
using System;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Threading;
namespace OmniLinkBridge
{
public class WebServiceModule : IModule
{
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
public static OmniLinkII OmniLink { get; private set; }
private WebServiceHost host;
private readonly AutoResetEvent trigger = new AutoResetEvent(false);
public WebServiceModule(OmniLinkII omni)
{
OmniLink = omni;
OmniLink.OnAreaStatus += Omnilink_OnAreaStatus;
OmniLink.OnZoneStatus += Omnilink_OnZoneStatus;
OmniLink.OnUnitStatus += Omnilink_OnUnitStatus;
OmniLink.OnThermostatStatus += Omnilink_OnThermostatStatus;
}
public void Startup()
{
log.Warning("WebAPI is deprecated");
WebNotification.RestoreSubscriptions();
Uri uri = new Uri("http://0.0.0.0:" + Global.webapi_port + "/");
host = new WebServiceHost(typeof(OmniLinkService), uri);
try
{
ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IOmniLinkService), new WebHttpBinding(), "");
host.Open();
log.Information("Listening on {url}", uri);
}
catch (CommunicationException ex)
{
log.Error(ex, "An exception occurred starting web service");
host.Abort();
}
// Wait until shutdown
trigger.WaitOne();
if (host != null)
host.Close();
WebNotification.SaveSubscriptions();
}
public void Shutdown()
{
trigger.Set();
}
private void Omnilink_OnAreaStatus(object sender, AreaStatusEventArgs e)
{
WebNotification.Send("area", JsonConvert.SerializeObject(e.Area.ToContract()));
}
private void Omnilink_OnZoneStatus(object sender, ZoneStatusEventArgs e)
{
if (e.Zone.IsTemperatureZone())
{
WebNotification.Send("temp", JsonConvert.SerializeObject(e.Zone.ToContract()));
return;
}
WebNotification.Send(Enum.GetName(typeof(DeviceType), e.Zone.ToDeviceType()), JsonConvert.SerializeObject(e.Zone.ToContract()));
}
private void Omnilink_OnUnitStatus(object sender, UnitStatusEventArgs e)
{
WebNotification.Send("unit", JsonConvert.SerializeObject(e.Unit.ToContract()));
}
private void Omnilink_OnThermostatStatus(object sender, ThermostatStatusEventArgs e)
{
// Ignore events fired by thermostat polling and when temperature is invalid
// An invalid temperature can occur when a Zigbee thermostat is unreachable
if (!e.EventTimer && e.Thermostat.Temp > 0)
WebNotification.Send("thermostat", JsonConvert.SerializeObject(e.Thermostat.ToContract()));
}
}
}

View file

@ -1,48 +0,0 @@
using OmniLinkBridge.Modules;
using Serilog;
using System;
using System.Net;
using System.Net.Mail;
using System.Reflection;
namespace OmniLinkBridge.Notifications
{
public class EmailNotification : INotification
{
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
public void Notify(string source, string description, NotificationPriority priority)
{
if (string.IsNullOrEmpty(Global.mail_server))
return;
foreach (MailAddress address in Global.mail_to)
{
MailMessage mail = new MailMessage
{
From = Global.mail_from,
Subject = $"{Global.controller_name} - {source}",
Body = $"{source}: {description}"
};
mail.To.Add(address);
using SmtpClient smtp = new SmtpClient(Global.mail_server, Global.mail_port);
smtp.EnableSsl = Global.mail_tls;
if (!string.IsNullOrEmpty(Global.mail_username))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(Global.mail_username, Global.mail_password);
}
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
log.Error(ex, "An error occurred sending email notification");
}
}
}
}
}

View file

@ -1,7 +0,0 @@
namespace OmniLinkBridge.Notifications
{
public interface INotification
{
void Notify(string source, string description, NotificationPriority priority);
}
}

View file

@ -1,35 +0,0 @@
using Serilog;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
namespace OmniLinkBridge.Notifications
{
public static class Notification
{
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly List<INotification> providers = new List<INotification>()
{
new EmailNotification(),
new ProwlNotification(),
new PushoverNotification()
};
public static void Notify(string source, string description, NotificationPriority priority = NotificationPriority.Normal)
{
Parallel.ForEach(providers, (provider) =>
{
try
{
provider.Notify(source, description, priority);
}
catch (Exception ex)
{
log.Error(ex, "Failed to send notification");
}
});
}
}
}

View file

@ -1,30 +0,0 @@
namespace OmniLinkBridge.Notifications
{
public enum NotificationPriority
{
/// <summary>
/// Generate no notification/alert
/// </summary>
VeryLow = -2,
/// <summary>
/// Always send as a quiet notification
/// </summary>
Moderate = -1,
/// <summary>
/// Trigger sound, vibration, and display an alert according to the user's device settings
/// </summary>
Normal = 0,
/// <summary>
/// Display as high-priority and bypass the user's quiet hours
/// </summary>
High = 1,
/// <summary>
/// Require confirmation from the user
/// </summary>
Emergency = 2,
};
}

View file

@ -1,41 +0,0 @@
using Serilog;
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
namespace OmniLinkBridge.Notifications
{
public class ProwlNotification : INotification
{
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly Uri URI = new Uri("https://api.prowlapp.com/publicapi/add");
public void Notify(string source, string description, NotificationPriority priority)
{
foreach (string key in Global.prowl_key)
{
List<string> parameters = new List<string>
{
"apikey=" + key,
"priority= " + (int)priority,
"application=" + Global.controller_name,
"event=" + source,
"description=" + description
};
using WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
client.UploadStringAsync(URI, string.Join("&", parameters.ToArray()));
client.UploadStringCompleted += Client_UploadStringCompleted;
}
}
private void Client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error != null)
log.Error(e.Error, "An error occurred sending prowl notification");
}
}
}

View file

@ -1,39 +0,0 @@
using Serilog;
using System;
using System.Collections.Specialized;
using System.Net;
using System.Reflection;
namespace OmniLinkBridge.Notifications
{
public class PushoverNotification : INotification
{
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly Uri URI = new Uri("https://api.pushover.net/1/messages.json");
public void Notify(string source, string description, NotificationPriority priority)
{
foreach (string key in Global.pushover_user)
{
var parameters = new NameValueCollection {
{ "token", Global.pushover_token },
{ "user", key },
{ "priority", ((int)priority).ToString() },
{ "title", $"{Global.controller_name} - {source}" },
{ "message", description }
};
using WebClient client = new WebClient();
client.UploadValues(URI, parameters);
client.UploadStringCompleted += Client_UploadStringCompleted;
}
}
private void Client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error != null)
log.Error(e.Error, "An error occurred sending pushover notification");
}
}
}

View file

@ -1,11 +0,0 @@
using HAI_Shared;
using System;
namespace OmniLinkBridge.OmniLink
{
public class AreaStatusEventArgs : EventArgs
{
public ushort ID { get; set; }
public clsArea Area { get; set; }
}
}

View file

@ -1,11 +0,0 @@
using HAI_Shared;
using System;
namespace OmniLinkBridge.OmniLink
{
public class AudioZoneStatusEventArgs : EventArgs
{
public ushort ID { get; set; }
public clsAudioZone AudioZone { get; set; }
}
}

View file

@ -1,11 +0,0 @@
using HAI_Shared;
using System;
namespace OmniLinkBridge.OmniLink
{
public class ButtonStatusEventArgs : EventArgs
{
public ushort ID { get; set; }
public clsButton Button { get; set; }
}
}

View file

@ -1,11 +0,0 @@
using HAI_Shared;
namespace OmniLinkBridge.OmniLink
{
public interface IOmniLinkII
{
clsHAC Controller { get; }
bool SendCommand(enuUnitCommand Cmd, byte Par, ushort Pr2);
}
}

View file

@ -1,11 +0,0 @@
using HAI_Shared;
using System;
namespace OmniLinkBridge.OmniLink
{
public class LockStatusEventArgs : EventArgs
{
public ushort ID { get; set; }
public clsAccessControlReader Reader { get; set; }
}
}

View file

@ -1,11 +0,0 @@
using HAI_Shared;
using System;
namespace OmniLinkBridge.OmniLink
{
public class MessageStatusEventArgs : EventArgs
{
public ushort ID { get; set; }
public clsMessage Message { get; set; }
}
}

View file

@ -1,15 +0,0 @@
namespace OmniLinkBridge.OmniLink
{
public enum SystemEventType
{
Button,
Phone,
AC,
Battery,
DCM,
EnergyCost,
Camera,
SwitchPress,
UPBLink,
}
}

View file

@ -1,12 +0,0 @@
using System;
namespace OmniLinkBridge.OmniLink
{
public class SystemStatusEventArgs : EventArgs
{
public SystemEventType Type { get; set; }
public string Value { get; set; }
public bool Trouble { get; set; }
public bool SendNotification { get; set; }
}
}

View file

@ -1,21 +0,0 @@
using HAI_Shared;
using System;
namespace OmniLinkBridge.OmniLink
{
public class ThermostatStatusEventArgs : EventArgs
{
public ushort ID { get; set; }
public clsThermostat Thermostat { get; set; }
/// <summary>
/// Set to true when thermostat is offline, indicated by a temperature of 0
/// </summary>
public bool Offline { get; set; }
/// <summary>
/// Set to true when fired by thermostat polling
/// </summary>
public bool EventTimer { get; set; }
}
}

View file

@ -1,11 +0,0 @@
using HAI_Shared;
using System;
namespace OmniLinkBridge.OmniLink
{
public class UnitStatusEventArgs : EventArgs
{
public ushort ID { get; set; }
public clsUnit Unit { get; set; }
}
}

View file

@ -1,11 +0,0 @@
using HAI_Shared;
using System;
namespace OmniLinkBridge.OmniLink
{
public class ZoneStatusEventArgs : EventArgs
{
public ushort ID { get; set; }
public clsZone Zone { get; set; }
}
}

View file

@ -1,225 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{0A636707-98BA-45AB-9843-AED430933CEE}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>OmniLinkBridge</RootNamespace>
<AssemblyName>OmniLinkBridge</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<NoWarn>IDE1006</NoWarn>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<NoWarn>IDE1006</NoWarn>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<PropertyGroup>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup>
<StartupObject>OmniLinkBridge.Program</StartupObject>
</PropertyGroup>
<ItemGroup>
<Reference Include="HAI.Controller">
<HintPath>.\HAI.Controller.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Data" />
<Reference Include="System.Management" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.ServiceModel.Web" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ControllerEnricher.cs" />
<Compile Include="CoreServer.cs" />
<Compile Include="Modules\TimeSyncModule.cs" />
<Compile Include="MQTT\HomeAssistant\Button.cs" />
<Compile Include="MQTT\HomeAssistant\Alarm.cs" />
<Compile Include="MQTT\HomeAssistant\Lock.cs" />
<Compile Include="MQTT\HomeAssistant\Select.cs" />
<Compile Include="MQTT\OverrideArea.cs" />
<Compile Include="MQTT\OverrideUnit.cs" />
<Compile Include="MQTT\Parser\AlarmCommands.cs" />
<Compile Include="MQTT\AreaCommandCode.cs" />
<Compile Include="MQTT\Parser\AreaCommands.cs" />
<Compile Include="MQTT\AreaState.cs" />
<Compile Include="MQTT\Availability.cs" />
<Compile Include="MQTT\HomeAssistant\BinarySensor.cs" />
<Compile Include="MQTT\Parser\CommandTypes.cs" />
<Compile Include="MQTT\HomeAssistant\Device.cs" />
<Compile Include="MQTT\HomeAssistant\Climate.cs" />
<Compile Include="MQTT\HomeAssistant\DeviceRegistry.cs" />
<Compile Include="MQTT\Extensions.cs" />
<Compile Include="MQTT\Parser\LockCommands.cs" />
<Compile Include="MQTT\Parser\MessageCommands.cs" />
<Compile Include="MQTT\MessageProcessor.cs" />
<Compile Include="MQTT\HomeAssistant\Number.cs" />
<Compile Include="MQTT\OverrideZone.cs" />
<Compile Include="MQTT\HomeAssistant\Switch.cs" />
<Compile Include="MQTT\HomeAssistant\Light.cs" />
<Compile Include="MQTT\MappingExtensions.cs" />
<Compile Include="MQTT\HomeAssistant\Sensor.cs" />
<Compile Include="MQTT\Parser\Topic.cs" />
<Compile Include="MQTT\Parser\UnitCommands.cs" />
<Compile Include="MQTT\Parser\ZoneCommands.cs" />
<Compile Include="MQTT\UnitType.cs" />
<Compile Include="Notifications\EmailNotification.cs" />
<Compile Include="Notifications\INotification.cs" />
<Compile Include="Notifications\Notification.cs" />
<Compile Include="Notifications\NotificationPriority.cs" />
<Compile Include="Notifications\PushoverNotification.cs" />
<Compile Include="OmniLink\ButtonStatusEventArgs.cs" />
<Compile Include="OmniLink\IOmniLinkII.cs" />
<Compile Include="OmniLink\AudioZoneStatusEventArgs.cs" />
<Compile Include="OmniLink\SystemEventType.cs" />
<Compile Include="OmniLink\LockStatusEventArgs.cs" />
<Compile Include="OmniLink\UnitStatusEventArgs.cs" />
<Compile Include="OmniLink\ThermostatStatusEventArgs.cs" />
<Compile Include="OmniLink\MessageStatusEventArgs.cs" />
<Compile Include="OmniLink\SystemStatusEventArgs.cs" />
<Compile Include="OmniLink\ZoneStatusEventArgs.cs" />
<Compile Include="OmniLink\AreaStatusEventArgs.cs" />
<Compile Include="Global.cs" />
<Compile Include="Modules\IModule.cs" />
<Compile Include="Modules\LoggerModule.cs" />
<Compile Include="Modules\MQTTModule.cs" />
<Compile Include="Modules\OmniLinkII.cs" />
<Compile Include="WebService\OmniLinkService.cs" />
<Compile Include="Extensions.cs" />
<Compile Include="WebService\CommandContract.cs" />
<Compile Include="WebService\IOmniLinkService.cs" />
<Compile Include="Program.cs" />
<Compile Include="ProjectInstaller.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="ProjectInstaller.Designer.cs">
<DependentUpon>ProjectInstaller.cs</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Notifications\ProwlNotification.cs" />
<Compile Include="Service.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Service.Designer.cs">
<DependentUpon>Service.cs</DependentUpon>
</Compile>
<Compile Include="Settings.cs" />
<Compile Include="WebService\MappingExtensions.cs" />
<Compile Include="WebService\OverrideZone.cs" />
<Compile Include="WebService\SubscribeContract.cs" />
<Compile Include="WebService\ThermostatContract.cs" />
<Compile Include="WebService\NameContract.cs" />
<Compile Include="WebService\AreaContract.cs" />
<Compile Include="WebService\ZoneContract.cs" />
<Compile Include="WebService\UnitContract.cs" />
<Compile Include="WebService\WebNotification.cs" />
<Compile Include="Modules\WebServiceModule.cs" />
<Compile Include="WebService\DeviceType.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config">
<SubType>Designer</SubType>
</None>
<None Include="OmniLinkBridge.ini">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="ProjectInstaller.resx">
<DependentUpon>ProjectInstaller.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Service.resx">
<DependentUpon>Service.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Mono.Posix-4.5">
<Version>4.5.0</Version>
</PackageReference>
<PackageReference Include="MQTTnet.Extensions.ManagedClient">
<Version>3.1.2</Version>
</PackageReference>
<PackageReference Include="Newtonsoft.Json">
<Version>13.0.3</Version>
</PackageReference>
<PackageReference Include="Serilog">
<Version>3.1.1</Version>
</PackageReference>
<PackageReference Include="Serilog.Formatting.Compact">
<Version>2.0.0</Version>
</PackageReference>
<PackageReference Include="Serilog.Sinks.Async">
<Version>1.5.0</Version>
</PackageReference>
<PackageReference Include="Serilog.Sinks.Console">
<Version>5.0.1</Version>
</PackageReference>
<PackageReference Include="Serilog.Sinks.File">
<Version>5.0.0</Version>
</PackageReference>
<PackageReference Include="Serilog.Sinks.Http">
<Version>7.2.0</Version>
</PackageReference>
<PackageReference Include="System.ValueTuple">
<Version>4.5.0</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- 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.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View file

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<StartArguments>
</StartArguments>
</PropertyGroup>
<PropertyGroup>
<ProjectView>ProjectFiles</ProjectView>
</PropertyGroup>
</Project>

View file

@ -1,119 +0,0 @@
# HAI / Leviton Omni Controller
controller_address =
controller_port = 4369
controller_key1 = 00-00-00-00-00-00-00-00
controller_key2 = 00-00-00-00-00-00-00-00
# Used in notifications
controller_name = OmniLinkBridge
# Controller Time Sync (yes/no)
# time_interval is interval in minutes to check controller time
# time_drift is the drift in seconds to allow before an adjustment is made
time_sync = no
time_interval = 60
time_drift = 10
# Verbose Console (yes/no)
verbose_unhandled = yes
verbose_event = yes
verbose_area = yes
verbose_zone = yes
verbose_thermostat_timer = yes
verbose_thermostat = yes
verbose_unit = yes
verbose_message = yes
verbose_lock = yes
verbose_audio = yes
# mySQL Logging (yes/no)
mysql_logging = no
mysql_connection = DRIVER={MySQL};SERVER=localhost;DATABASE=OmniLinkBridge;USER=root;PASSWORD=myPassword;OPTION=3;
# Web Service (yes/no)
# Can be used for integration with Samsung SmartThings
webapi_enabled = no
webapi_port = 8000
# device_type must be contact, motion, water, smoke, or co
#webapi_override_zone = id=20;device_type=motion
# MQTT
# Can be used for integration with Home Assistant
mqtt_enabled = no
mqtt_server =
mqtt_port = 1883
mqtt_username =
mqtt_password =
# If you have multiple Omni Controllers you will want to change the
# mqtt_prefix and mqtt_discovery_name_prefix to prevent collisions.
# Prefix for MQTT state / command topics
mqtt_prefix = omnilink
# Prefix for Home Assistant discovery
mqtt_discovery_prefix = homeassistant
# Prefix for Home Assistant entity names
mqtt_discovery_name_prefix =
# Skip publishing Home Assistant discovery topics for zones/units
# Specify a range of numbers 1,2,3,5-10
mqtt_discovery_ignore_zones =
mqtt_discovery_ignore_units =
# Override the area Home Assistant alarm control panel
# Prompt for user code
# code_arm: true or false, defaults to false
# code_disarm: true or false, defaults to false
# Show these modes
# arm_home: true or false, defaults to true
# arm_away: true or false, defaults to true
# arm_night: true or false, defaults to true
# arm_vacation: true or false, defaults to true
#mqtt_discovery_override_area = id=1;code_disarm=true;arm_vacation=false
# Override the zone Home Assistant binary sensor device_class
# device_class: must be battery, cold, door, garage_door, gas,
# heat, moisture, motion, problem, safety, smoke, or window
#mqtt_discovery_override_zone = id=5;device_class=garage_door
#mqtt_discovery_override_zone = id=6;device_class=garage_door
# Override the unit Home Assistant device type
# type:
# Units (LTe 1-32, IIe 1-64, Pro 1-256) light or switch, defaults to light
# Flags (LTe 41-88, IIe 73-128, Pro 393-511) switch or number, defaults to switch
#mqtt_discovery_override_unit = id=1;type=switch
#mqtt_discovery_override_unit = id=395;type=number
# Publish buttons as this Home Assistant device type
# must be button (recommended) or switch (default, previous behavior)
mqtt_discovery_button_type = switch
# Handle mute locally by setting volume to 0 and restoring to previous value
mqtt_audio_local_mute = no
# Change audio volume scaling for Home Assistant media player
# yes 0.00-1.00, no 0-100 (default, previous behavior)
mqtt_audio_volume_media_player = no
# Notifications (yes/no)
# Always sent for area alarms and critical system events
# Optionally enable for area status changes and console messages
notify_area = no
notify_message = no
# Email Notifications
# mail_username and mail_password optional for authenticated mail
mail_server =
mail_tls = no
# When TLS is enabled the port is usually 587
mail_port = 25
mail_username =
mail_password =
mail_from = OmniLinkBridge@localhost
#mail_to =
#mail_to =
# Prowl Notifications
# Register for API key at http://www.prowlapp.com
#prowl_key =
#prowl_key =
# Pushover Notifications
# Register for API token at http://www.pushover.net
#pushover_token =
#pushover_user =
#pushover_user =

View file

@ -1,239 +0,0 @@
using Mono.Unix;
using Serilog;
using Serilog.Events;
using Serilog.Filters;
using Serilog.Formatting.Compact;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.ServiceProcess;
using System.Threading.Tasks;
namespace OmniLinkBridge
{
internal class Program
{
private static CoreServer server;
private static int Main(string[] args)
{
bool interactive = false;
string config_file = "OmniLinkBridge.ini";
string log_file = "log.txt";
bool log_clef = false;
LogEventLevel log_level = LogEventLevel.Information;
for (int i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "/?":
case "-h":
case "-help":
ShowHelp();
return 0;
case "-c":
config_file = args[++i];
break;
case "-e":
Global.UseEnvironment = true;
break;
case "-d":
Global.DebugSettings = true;
break;
case "-lf":
log_file = args[++i];
if (string.Compare(log_file, "disable", true) == 0)
log_file = null;
break;
case "-lj":
log_clef = true;
break;
case "-ll":
Enum.TryParse(args[++i], out log_level);
break;
case "-ld":
Global.DebugSettings = true;
Global.SendLogs = true;
break;
case "-s":
Global.webapi_subscriptions_file = args[++i];
break;
case "-i":
interactive = true;
break;
}
}
if (string.Compare(Environment.GetEnvironmentVariable("SEND_LOGS"), "1") == 0)
{
Global.DebugSettings = true;
Global.SendLogs = true;
}
config_file = GetFullPath(config_file);
Global.webapi_subscriptions_file = GetFullPath(Global.webapi_subscriptions_file ?? "WebSubscriptions.json");
// Use TLS 1.2 as default connection
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
string log_format = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{SourceContext} {Level:u3}] {Message:lj}{NewLine}{Exception}";
var log_config = new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.WithProperty("Application", "OmniLinkBridge")
.Enrich.WithProperty("Session", Global.SessionID)
.Enrich.With<ControllerEnricher>()
.Enrich.FromLogContext();
if (log_file != null)
{
log_file = GetFullPath(log_file);
if (log_clef)
log_config = log_config.WriteTo.Async(a => a.File(new CompactJsonFormatter(), log_file, log_level,
rollingInterval: RollingInterval.Day, retainedFileCountLimit: 15));
else
log_config = log_config.WriteTo.Async(a => a.File(log_file, log_level, log_format,
rollingInterval: RollingInterval.Day, retainedFileCountLimit: 15));
}
if (Global.SendLogs)
log_config = log_config.WriteTo.Logger(lc => lc
.WriteTo.Http("https://telemetry.excalibur-partners.com"));
else if (UseTelemetry())
log_config = log_config.WriteTo.Logger(lc => lc
.Filter.ByIncludingOnly(Matching.WithProperty("Telemetry"))
.WriteTo.Http("https://telemetry.excalibur-partners.com"));
if (Environment.UserInteractive || interactive)
log_config = log_config.WriteTo.Console(outputTemplate: log_format);
Log.Logger = log_config.CreateLogger();
try
{
Settings.LoadSettings(config_file);
}
catch
{
// Errors are logged in LoadSettings();
Log.CloseAndFlush();
return -1;
}
if (Environment.UserInteractive || interactive)
{
if (IsRunningOnMono())
{
UnixSignal[] signals = new UnixSignal[]{
new UnixSignal(Mono.Unix.Native.Signum.SIGTERM),
new UnixSignal(Mono.Unix.Native.Signum.SIGINT),
new UnixSignal(Mono.Unix.Native.Signum.SIGUSR1)
};
Task.Factory.StartNew(() =>
{
// Blocking call to wait for any kill signal
int index = UnixSignal.WaitAny(signals, -1);
server.Shutdown();
});
}
Console.TreatControlCAsInput = false;
Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler);
server = new CoreServer();
}
else
{
ServiceBase[] ServicesToRun;
// More than one user Service may run within the same process. To add
// another service to this process, change the following line to
// create a second service object. For example,
//
// ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
//
ServicesToRun = new ServiceBase[] { new Service() };
ServiceBase.Run(ServicesToRun);
}
return 0;
}
private static string GetFullPath(string file)
{
if (Path.IsPathRooted(file))
return file;
return Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), file);
}
protected static void myHandler(object sender, ConsoleCancelEventArgs args)
{
server.Shutdown();
args.Cancel = true;
}
private static bool IsRunningOnMono()
{
return Type.GetType("Mono.Runtime") != null;
}
public static string GetEnvironment()
{
if (Environment.GetEnvironmentVariable("HASSIO_TOKEN") != null)
return "Home Assistant";
else if (IsRunningOnMono())
return Process.GetProcesses().Any(w => w.Id == 2) ? "Mono" : "Docker";
else
return "Native";
}
private static bool UseTelemetry()
{
return string.Compare(Environment.GetEnvironmentVariable("TELEMETRY_OPTOUT"), "1") != 0;
}
public static void ShowSendLogsWarning()
{
if (Global.SendLogs)
Log.Warning("SENDING LOGS TO DEVELOPER Controller: {ControllerID}, Session: {Session}",
Global.controller_id, Global.SessionID);
}
private static void ShowHelp()
{
Console.WriteLine(
AppDomain.CurrentDomain.FriendlyName + " [-c config_file] [-e] [-d] [-j] [-s subscriptions_file]\n" +
"\t[-lf log_file|disable] [-lj [-ll verbose|debug|information|warning|error] [-ld] [-i]\n" +
"\t-c Specifies the configuration file. Default is OmniLinkBridge.ini\n" +
"\t-e Check environment variables for configuration settings\n" +
"\t-d Show debug ouput for configuration loading\n" +
"\t-s Specifies the web api subscriptions file. Default is WebSubscriptions.json\n" +
"\t-lf Specifies the rolling log file. Retention is 15 days. Default is log.txt.\n" +
"\t-lj Write logs as CLEF (compact log event format) JSON.\n" +
"\t-ll Minimum level at which events will be logged. Default is information.\n" +
"\t-ld Send logs to developer. ONLY USE WHEN ASKED.\n" +
"\t Also enabled by setting a SEND_LOGS environment variable to 1.\n" +
"\t-i Run in interactive mode");
Console.WriteLine(
"\nVersion: " + Assembly.GetExecutingAssembly().GetName().Version +
"\nEnvironment: " + GetEnvironment());
Console.WriteLine(
"\nOmniLink Bridge collects anonymous telemetry data to help improve the software.\n" +
"You can opt of telemetry by setting a TELEMETRY_OPTOUT environment variable to 1.");
}
}
}

View file

@ -1,517 +0,0 @@
using OmniLinkBridge.MQTT.HomeAssistant;
using Serilog;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Reflection;
using ha = OmniLinkBridge.MQTT.HomeAssistant;
namespace OmniLinkBridge
{
public static class Settings
{
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
public static void LoadSettings(string file)
{
LoadSettings(LoadCollection(file));
}
public static void LoadSettings(string[] lines)
{
LoadSettings(LoadCollection(lines));
}
public static void LoadSettings(NameValueCollection settings)
{
// HAI / Leviton Omni Controller
Global.controller_address = settings.ValidateHasValue("controller_address");
Global.controller_port = settings.ValidatePort("controller_port");
Global.controller_key1 = settings.ValidateEncryptionKey("controller_key1");
Global.controller_key2 = settings.ValidateEncryptionKey("controller_key2");
Global.controller_name = settings.CheckEnv("controller_name") ?? "OmniLinkBridge";
Global.controller_id = (Global.controller_address + Global.controller_key1 + Global.controller_key2).ComputeGuid();
// Controller Time Sync
Global.time_sync = settings.ValidateBool("time_sync");
if (Global.time_sync)
{
Global.time_interval = settings.ValidateInt("time_interval");
Global.time_drift = settings.ValidateInt("time_drift");
}
// Verbose Console
Global.verbose_unhandled = settings.ValidateBool("verbose_unhandled");
Global.verbose_event = settings.ValidateBool("verbose_event");
Global.verbose_area = settings.ValidateBool("verbose_area");
Global.verbose_zone = settings.ValidateBool("verbose_zone");
Global.verbose_thermostat_timer = settings.ValidateBool("verbose_thermostat_timer");
Global.verbose_thermostat = settings.ValidateBool("verbose_thermostat");
Global.verbose_unit = settings.ValidateBool("verbose_unit");
Global.verbose_message = settings.ValidateBool("verbose_message");
Global.verbose_lock = settings.ValidateBool("verbose_lock");
Global.verbose_audio = settings.ValidateBool("verbose_audio");
// mySQL Logging
Global.mysql_logging = settings.ValidateBool("mysql_logging");
Global.mysql_connection = settings.CheckEnv("mysql_connection", true);
// Web Service
Global.webapi_enabled = settings.ValidateBool("webapi_enabled");
if (Global.webapi_enabled)
{
Global.webapi_port = settings.ValidatePort("webapi_port");
Global.webapi_override_zone = settings.LoadOverrideZone<WebAPI.OverrideZone>("webapi_override_zone");
}
// MQTT
Global.mqtt_enabled = settings.ValidateBool("mqtt_enabled");
if (Global.mqtt_enabled)
{
Global.mqtt_server = settings.CheckEnv("mqtt_server");
Global.mqtt_port = settings.ValidatePort("mqtt_port");
Global.mqtt_username = settings.CheckEnv("mqtt_username", true);
Global.mqtt_password = settings.CheckEnv("mqtt_password", true);
Global.mqtt_prefix = settings.CheckEnv("mqtt_prefix") ?? "omnilink";
Global.mqtt_discovery_prefix = settings.CheckEnv("mqtt_discovery_prefix") ?? "homeassistant";
Global.mqtt_discovery_name_prefix = settings.CheckEnv("mqtt_discovery_name_prefix") ?? string.Empty;
if (!string.IsNullOrEmpty(Global.mqtt_discovery_name_prefix))
Global.mqtt_discovery_name_prefix += " ";
Global.mqtt_discovery_ignore_zones = settings.ValidateRange("mqtt_discovery_ignore_zones");
Global.mqtt_discovery_ignore_units = settings.ValidateRange("mqtt_discovery_ignore_units");
Global.mqtt_discovery_override_area = settings.LoadOverrideArea<MQTT.OverrideArea>("mqtt_discovery_override_area");
Global.mqtt_discovery_override_zone = settings.LoadOverrideZone<MQTT.OverrideZone>("mqtt_discovery_override_zone");
Global.mqtt_discovery_override_unit = settings.LoadOverrideUnit<MQTT.OverrideUnit>("mqtt_discovery_override_unit");
Global.mqtt_discovery_button_type = settings.ValidateType("mqtt_discovery_button_type", typeof(Switch), typeof(Button));
Global.mqtt_audio_local_mute = settings.ValidateBool("mqtt_audio_local_mute");
Global.mqtt_audio_volume_media_player = settings.ValidateBool("mqtt_audio_volume_media_player");
}
// Notifications
Global.notify_area = settings.ValidateBool("notify_area");
Global.notify_message = settings.ValidateBool("notify_message");
// Email Notifications
Global.mail_server = settings.CheckEnv("mail_server");
if (!string.IsNullOrEmpty(Global.mail_server))
{
Global.mail_tls = settings.ValidateBool("mail_tls");
Global.mail_port = settings.ValidatePort("mail_port");
Global.mail_username = settings.CheckEnv("mail_username", true);
Global.mail_password = settings.CheckEnv("mail_password", true);
Global.mail_from = settings.ValidateMailFrom("mail_from");
Global.mail_to = settings.ValidateMailTo("mail_to");
}
// Prowl Notifications
Global.prowl_key = settings.ValidateMultipleStrings("prowl_key", true);
// Pushover Notifications
Global.pushover_token = settings.CheckEnv("pushover_token", true);
Global.pushover_user = settings.ValidateMultipleStrings("pushover_user", true);
}
private static string CheckEnv(this NameValueCollection settings, string name, bool sensitive = false)
{
string env = Global.UseEnvironment ? Environment.GetEnvironmentVariable(name.ToUpper()) : null;
string value = !string.IsNullOrEmpty(env) ? env : settings[name];
if (Global.DebugSettings)
log.Debug("{ConfigType} {ConfigName}: {ConfigValue}",
(!string.IsNullOrEmpty(env) ? "ENV" : "CONF").PadRight(4), name,
sensitive && value != null ? value.Truncate(3) + "***MASKED***" : value);
return value;
}
private static ConcurrentDictionary<int, T> LoadOverrideArea<T>(this NameValueCollection settings, string section) where T : new()
{
try
{
ConcurrentDictionary<int, T> ret = new ConcurrentDictionary<int, T>();
string value = settings.CheckEnv(section);
if (string.IsNullOrEmpty(value))
return ret;
string[] ids = value.Split(',');
for (int i = 0; i < ids.Length; i++)
{
Dictionary<string, string> attributes = ids[i].TrimEnd(new char[] { ';' }).Split(';')
.Select(s => s.Split('='))
.ToDictionary(a => a[0].Trim(), a => a[1].Trim(), StringComparer.InvariantCultureIgnoreCase);
if (!attributes.ContainsKey("id") || !int.TryParse(attributes["id"], out int attrib_id))
throw new Exception("Missing or invalid id attribute");
T override_area = new T();
if (override_area is MQTT.OverrideArea mqtt_area)
{
foreach (string attribute in attributes.Keys)
{
switch(attribute)
{
case "id":
continue;
case "code_arm":
if (!bool.TryParse(attributes["code_arm"], out bool code_arm))
throw new Exception("Invalid code_arm attribute");
mqtt_area.code_arm = code_arm;
break;
case "code_disarm":
if (!bool.TryParse(attributes["code_disarm"], out bool code_disarm))
throw new Exception("Invalid code_disarm attribute");
mqtt_area.code_disarm = code_disarm;
break;
case "arm_home":
if (!bool.TryParse(attributes["arm_home"], out bool arm_home))
throw new Exception("Invalid arm_home attribute");
mqtt_area.arm_home = arm_home;
break;
case "arm_away":
if (!bool.TryParse(attributes["arm_away"], out bool arm_away))
throw new Exception("Invalid arm_away attribute");
mqtt_area.arm_away = arm_away;
break;
case "arm_night":
if (!bool.TryParse(attributes["arm_night"], out bool arm_night))
throw new Exception("Invalid arm_night attribute");
mqtt_area.arm_night = arm_night;
break;
case "arm_vacation":
if (!bool.TryParse(attributes["arm_vacation"], out bool arm_vacation))
throw new Exception("Invalid arm_vacation attribute");
mqtt_area.arm_vacation = arm_vacation;
break;
default:
throw new Exception($"Unknown attribute {attribute}" );
}
}
}
ret.TryAdd(attrib_id, override_area);
}
return ret;
}
catch (Exception ex)
{
log.Error(ex, "Invalid override area specified for {section}", section);
throw;
}
}
private static ConcurrentDictionary<int, T> LoadOverrideZone<T>(this NameValueCollection settings, string section) where T : new()
{
try
{
ConcurrentDictionary<int, T> ret = new ConcurrentDictionary<int, T>();
string value = settings.CheckEnv(section);
if (string.IsNullOrEmpty(value))
return ret;
string[] ids = value.Split(',');
for (int i = 0; i < ids.Length; i++)
{
Dictionary<string, string> attributes = ids[i].TrimEnd(new char[] { ';' }).Split(';')
.Select(s => s.Split('='))
.ToDictionary(a => a[0].Trim(), a => a[1].Trim(), StringComparer.InvariantCultureIgnoreCase);
if (!attributes.ContainsKey("id") || !int.TryParse(attributes["id"], out int attrib_id))
throw new Exception("Missing or invalid id attribute");
T override_zone = new T();
if (override_zone is WebAPI.OverrideZone webapi_zone)
{
if (!attributes.ContainsKey("device_type") || !Enum.TryParse(attributes["device_type"], out WebAPI.DeviceType attrib_device_type))
throw new Exception("Missing or invalid device_type attribute");
webapi_zone.device_type = attrib_device_type;
}
else if (override_zone is MQTT.OverrideZone mqtt_zone)
{
if (!attributes.ContainsKey("device_class") || !Enum.TryParse(attributes["device_class"], out ha.BinarySensor.DeviceClass attrib_device_class))
throw new Exception("Missing or invalid device_class attribute");
mqtt_zone.device_class = attrib_device_class;
}
ret.TryAdd(attrib_id, override_zone);
}
return ret;
}
catch (Exception ex)
{
log.Error(ex, "Invalid override zone specified for {section}", section);
throw;
}
}
private static ConcurrentDictionary<int, T> LoadOverrideUnit<T>(this NameValueCollection settings, string section) where T : new()
{
try
{
ConcurrentDictionary<int, T> ret = new ConcurrentDictionary<int, T>();
string value = settings.CheckEnv(section);
if (string.IsNullOrEmpty(value))
return ret;
string[] ids = value.Split(',');
for (int i = 0; i < ids.Length; i++)
{
Dictionary<string, string> attributes = ids[i].TrimEnd(new char[] { ';' }).Split(';')
.Select(s => s.Split('='))
.ToDictionary(a => a[0].Trim(), a => a[1].Trim(), StringComparer.InvariantCultureIgnoreCase);
if (!attributes.ContainsKey("id") || !int.TryParse(attributes["id"], out int attrib_id))
throw new Exception("Missing or invalid id attribute");
T override_unit = new T();
if (override_unit is MQTT.OverrideUnit mqtt_unit)
{
if (!attributes.ContainsKey("type") || !Enum.TryParse(attributes["type"], out MQTT.UnitType attrib_type))
throw new Exception("Missing or invalid type attribute");
mqtt_unit.type = attrib_type;
}
ret.TryAdd(attrib_id, override_unit);
}
return ret;
}
catch (Exception ex)
{
log.Error(ex, "Invalid override unit specified for {section}", section);
throw;
}
}
private static string ValidateHasValue(this NameValueCollection settings, string section)
{
string value = settings.CheckEnv(section);
if(string.IsNullOrEmpty(value))
{
log.Error("Empty string specified for {section}", section);
throw new Exception();
}
return value;
}
private static string ValidateEncryptionKey(this NameValueCollection settings, string section)
{
string value = settings.CheckEnv(section, true).Replace("-","");
if (string.IsNullOrEmpty(value) || value.Length != 16)
{
log.Error("Invalid encryption key specified for {section}", section);
throw new Exception();
}
return value;
}
private static int ValidateInt(this NameValueCollection settings, string section)
{
try
{
return int.Parse(settings.CheckEnv(section));
}
catch
{
log.Error("Invalid integer specified for {section}", section);
throw;
}
}
private static HashSet<int> ValidateRange(this NameValueCollection settings, string section)
{
try
{
string value = settings.CheckEnv(section);
if (string.IsNullOrEmpty(value))
return new HashSet<int>();
return new HashSet<int>(settings.CheckEnv(section).ParseRanges());
}
catch
{
log.Error("Invalid range specified for {section}", section);
throw;
}
}
private static int ValidatePort(this NameValueCollection settings, string section)
{
try
{
int port = int.Parse(settings.CheckEnv(section));
if (port < 1 || port > 65534)
throw new Exception();
return port;
}
catch
{
log.Error("Invalid port specified for {section}", section);
throw;
}
}
private static MailAddress ValidateMailFrom(this NameValueCollection settings, string section)
{
try
{
return new MailAddress(settings.CheckEnv(section));
}
catch
{
log.Error("Invalid email specified for {section}", section);
throw;
}
}
private static MailAddress[] ValidateMailTo(this NameValueCollection settings, string section)
{
try
{
string value = settings.CheckEnv(section);
if (string.IsNullOrEmpty(value))
return new MailAddress[] {};
string[] emails = value.Split(',');
MailAddress[] addresses = new MailAddress[emails.Length];
for(int i=0; i < emails.Length; i++)
addresses[i] = new MailAddress(emails[i]);
return addresses;
}
catch
{
log.Error("Invalid email specified for {section}", section);
throw;
}
}
private static string[] ValidateMultipleStrings(this NameValueCollection settings, string section, bool sensitive = false)
{
try
{
if (settings.CheckEnv(section, true) == null)
return new string[] { };
return settings.CheckEnv(section, sensitive).Split(',');
}
catch
{
log.Error("Invalid string specified for {section}", section);
throw;
}
}
private static bool ValidateBool (this NameValueCollection settings, string section)
{
string value = settings.CheckEnv(section);
if (value == null)
return false;
if (string.Compare(value, "yes", true) == 0 || string.Compare(value, "true", true) == 0)
return true;
else if (string.Compare(value, "no", true) == 0 || string.Compare(value, "false", true) == 0)
return false;
else
{
log.Error("Invalid yes/no or true/false specified for {section}", section);
throw new Exception();
}
}
private static Type ValidateType(this NameValueCollection settings, string section, params Type[] types)
{
string value = settings.CheckEnv(section);
if (value == null)
return types[0];
foreach (Type type in types)
if (string.Compare(value, type.Name, true) == 0)
return type;
log.Error("Invalid type specified for {section}", section);
throw new Exception();
}
private static NameValueCollection LoadCollection(string[] lines)
{
NameValueCollection settings = new NameValueCollection();
foreach(string line in lines)
{
if (line.StartsWith("#"))
continue;
int pos = line.IndexOf('=', 0);
if (pos == -1)
continue;
string key = line.Substring(0, pos).Trim();
string value = line.Substring(pos + 1).Trim();
settings.Add(key, value);
}
return settings;
}
private static NameValueCollection LoadCollection(string file)
{
if (Global.DebugSettings)
log.Debug("Using settings file {file}", file);
if(!File.Exists(file))
{
log.Warning("Unable to locate settings file {file}", file);
return new NameValueCollection();
}
try
{
return LoadCollection(File.ReadAllLines(file));
}
catch (FileNotFoundException ex)
{
log.Error(ex, "Error parsing settings file {file}", file);
throw;
}
}
}
}

View file

@ -1,12 +0,0 @@
namespace OmniLinkBridge.WebAPI
{
public enum DeviceType
{
unknown,
contact,
motion,
water,
smoke,
co
}
}

Some files were not shown because too many files have changed in this diff Show more