Compare commits

...

47 Commits

Author SHA1 Message Date
Ryan Wagoner
efa16fb2c3 1.1.19 - Fix MQTT alarm control panel for Home Assistant 2024.6 2024-06-07 21:39:43 -04:00
Ryan Wagoner
f297c2fcaa 1.1.18 - Increase timeout for loading names and add send support logs 2024-05-08 20:25:31 -04:00
Ryan Wagoner
d7eef51adf 1.1.17 - Add MQTT volume scaling for Home Assistant media player 2024-05-05 15:36:00 -04:00
Ryan Wagoner
73f504ca93 1.1.16 - Add MQTT audio support 2024-05-03 21:35:46 -04:00
Ryan Wagoner
800242a87f 1.1.15 - Add notice for deprecated modules and update packages 2024-04-13 02:21:22 -04:00
Ryan Wagoner
84b52c8f30 Add MQTT lock support 2024-04-12 00:00:26 -04:00
Ryan Wagoner
495ce74149 1.1.14 - Improve MQTT unit, output and flag capabilities 2022-11-02 18:09:33 -04:00
Ryan Wagoner
a016e1cd64 Implement MQTT thermostat offline status 2022-10-20 23:44:27 -04:00
Ryan Wagoner
1ce5e3dab9 1.1.13 - Add MQTT area security code support 2022-10-20 21:43:39 -04:00
Ryan Wagoner
7c24d9046e Add support to build docker for multiple architectures 2022-07-13 18:28:21 -04:00
Ryan Wagoner
41330b9bf4 1.1.12 - MQTT area basic_state now includes arm_vacation to align with changes to Home Assistant 2022-04-04 23:11:01 -04:00
Ryan Wagoner
3b86dd6a3a Update MQTT Home Assistant discovery to use preset mode instead of deprecated hold mode 2022-04-04 23:10:41 -04:00
Ryan Wagoner
5cd6048dd5 Fix system trouble naming and discovery payloads 2021-12-16 23:33:42 -05:00
Ryan Wagoner
b5298a1e74 Update to NET Framework 4.7.2 and cleanup warnings 2021-12-15 20:04:26 -05:00
Ryan Wagoner
e7613741d3 Fix controller reconnect issue and async cleanup 2021-12-14 01:13:43 -05:00
Ryan Wagoner
2f652f7c8a 1.1.11 - Add MQTT thermostat humidify and dehumidify discovery 2021-11-04 21:49:14 -04:00
Ryan Wagoner
a8d965eb04 Add thermostat emergency heat and fix hold documentation 2021-11-04 20:34:13 -04:00
Ryan Wagoner
a248bd4f30 - Add MQTT area and zone user code support and update packages 2021-07-28 20:33:47 -04:00
Ryan Wagoner
92012fc0b7 1.1.10 - Add MQTT zone bypass switch discovery 2021-07-20 23:44:11 -04:00
Ryan Wagoner
37aed0e891 - Change MQTT thermostat current status and alarm arming status 2021-07-20 23:07:56 -04:00
Ryan Wagoner
1cf77ba179 1.1.9 - Add MQTT system trouble, thermostat type, and area alarm activation 2020-11-05 21:59:30 -05:00
Ryan Wagoner
85c549d5dd - Add MQTT unit scene, update packages, and fix compiler warnings 2020-11-02 21:14:01 -05:00
Ryan Wagoner
084fb9a473 - Add initial verbose logs and additional details 2020-11-02 20:51:53 -05:00
Ryan Wagoner
8e637db459 - Switch to structured logging and add telemetry 2020-01-05 21:34:03 -05:00
Ryan Wagoner
7d87416915 1.1.8 - Fix MQTT undefined settings and add unit tests 2019-12-27 13:57:17 -05:00
Ryan Wagoner
a5e9fae32e 1.1.7 - Improve configuration environment and file loading 2019-12-26 22:14:58 -05:00
Ryan Wagoner
9a966225b6 1.1.6 - Add support for environment variables 2019-12-24 22:32:42 -05:00
Ryan Wagoner
792355dd0a - Add license, contributing, and update readme 2019-12-23 22:00:21 -05:00
Ryan Wagoner
314ea42f64 - Update MQTT, add console messages and button presses 2019-12-23 22:00:14 -05:00
Ryan Wagoner
c3aa88621d - Add controller name and TLS support to email notifications 2019-12-23 19:37:21 -05:00
Ryan Wagoner
336e02e8e8 1.1.5 - Update readme, fix thermostat logging interval, and cleanup code 2019-12-14 22:11:23 -05:00
Ryan Wagoner
cb24322bef - Refactor MQTT parser and add unit tests 2019-12-13 23:14:20 -05:00
Ryan Wagoner
dbad9ea3ce - Fix SQL logging error for areas and units 2019-12-13 23:13:31 -05:00
Ryan Wagoner
fe66f608ec 1.1.4 - Shutdown cleanly on linux or docker 2019-11-22 21:58:28 -05:00
Ryan Wagoner
3e4a53fa13 - Add MQTT messages for controller disconnect and last will 2019-11-22 21:26:53 -05:00
Ryan Wagoner
a891363539 - Add Home Assistant MQTT device registry support 2019-11-22 20:53:21 -05:00
Ryan Wagoner
a1b15cd08b - Fix missing last area, zone, unit, thermostat, and button 2019-11-05 22:49:30 -05:00
Ryan Wagoner
23dd321f25 - Always enable first area to support Omni LTe and Omni IIe 2019-11-05 22:49:30 -05:00
Ryan Wagoner
ff02e1fd44 - Fix MQTT id validation and add notice for publishing to area 0 2019-11-05 22:49:30 -05:00
Ryan Wagoner
151384c5b6 - Utilize controller temperature format 2019-11-05 22:49:30 -05:00
Ryan Wagoner
177dda4c1a - Fix compatibility with Home Assistant 0.95.4 MQTT extra keys
- Don't publish invalid thermostat temperatures
2019-11-05 22:49:30 -05:00
Ryan Wagoner
a9c52b433f 1.1.3 - Fix compatibility with Home Assistant 0.87 MQTT strict config 2019-02-10 17:56:54 -05:00
Ryan Wagoner
09637316a5 - Add area json status and climate temp sensor 2018-11-09 01:01:28 -05:00
Ryan Wagoner
cda76b6930 - Add override zone type for web service 2018-11-01 23:25:13 -04:00
Ryan Wagoner
c9e5063ddd - Update readme documentation 2018-11-01 20:24:51 -04:00
Ryan Wagoner
fd701b269c - Publish config when reconnecting to MQTT 2018-10-25 21:34:01 -04:00
Ryan Wagoner
96093fbebd 1.1.2 - Add min and max climate temperatures
- Update docker run command to use local time zone
- Improve area and zone MQTT support
- Add option to change MQTT prefix to support multiple instances
- Add detailed zone sensor and thermostat humidity sensor
- Add prefix for MQTT discovery entity name
- Request zone status update on area status change
2018-10-24 00:01:58 -04:00
81 changed files with 5677 additions and 1460 deletions

3
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,3 @@
# 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,17 +1,39 @@
FROM mono:latest
FROM mono:latest AS build
COPY . /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
RUN rm -rf /build
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
CMD [ "mono", "OmniLinkBridge.exe", "-i", "-c", "/config/OmniLinkBridge.ini", "-s", "/config/WebSubscriptions.json" ]
COPY --from=build /app .
CMD [ "mono", "OmniLinkBridge.exe", "-i", "-c", "/config/OmniLinkBridge.ini", "-e", "-s", "/config/WebSubscriptions.json", "-lf", "disable" ]

674
LICENSE.md Normal file
View File

@ -0,0 +1,674 @@
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

@ -37,10 +37,23 @@ CREATE TABLE IF NOT EXISTS `log_areas` (
`duress` varchar(10) NOT NULL,
`security` varchar(20) NOT NULL,
PRIMARY KEY (`log_area_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=287 ;
) 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`
--
@ -52,7 +65,7 @@ CREATE TABLE IF NOT EXISTS `log_messages` (
`name` varchar(12) NOT NULL,
`status` varchar(10) NOT NULL,
PRIMARY KEY (`log_message_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=139 ;
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
@ -72,11 +85,11 @@ CREATE TABLE IF NOT EXISTS `log_thermostats` (
`humidity` smallint(6) NOT NULL,
`humidify` smallint(6) NOT NULL,
`dehumidify` smallint(6) NOT NULL,
`mode` varchar(5) NOT NULL,
`mode` varchar(14) NOT NULL,
`fan` varchar(5) NOT NULL,
`hold` varchar(5) NOT NULL,
`hold` varchar(8) NOT NULL,
PRIMARY KEY (`log_tstat_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=67544 ;
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
@ -93,7 +106,7 @@ CREATE TABLE IF NOT EXISTS `log_units` (
`statusvalue` smallint(6) NOT NULL,
`statustime` smallint(6) NOT NULL,
PRIMARY KEY (`log_unit_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1245 ;
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
@ -108,7 +121,7 @@ CREATE TABLE IF NOT EXISTS `log_zones` (
`name` varchar(16) NOT NULL,
`status` varchar(10) NOT NULL,
PRIMARY KEY (`log_zone_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=10298 ;
) 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 */;

View File

@ -1,37 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
</startup>
<log4net>
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date %-5level: %message%newline"/>
</layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt"/>
<appendToFile value="true"/>
<rollingStyle value="Composite"/>
<datePattern value="yyyyMMdd"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="5MB"/>
<immediateFlush value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="WARN"/>
<levelMax value="FATAL"/>
</filter>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="TraceAppender"/>
<appender-ref ref="RollingFileAppender"/>
</root>
</log4net>
</configuration>

View File

@ -0,0 +1,16 @@
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,6 +1,7 @@
using OmniLinkBridge.Modules;
using OmniLinkBridge.OmniLink;
using log4net;
using Serilog;
using Serilog.Context;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
@ -10,11 +11,13 @@ namespace OmniLinkBridge
{
public class CoreServer
{
private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
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()
{
@ -24,11 +27,6 @@ namespace OmniLinkBridge
private void Server()
{
Global.running = true;
log.Debug("Starting up server " +
Assembly.GetExecutingAssembly().GetName().Version.ToString());
// Controller connection
modules.Add(omnilink = new OmniLinkII(Global.controller_address, Global.controller_port, Global.controller_key1, Global.controller_key2));
@ -44,6 +42,14 @@ namespace OmniLinkBridge
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)
{
@ -53,14 +59,11 @@ namespace OmniLinkBridge
}));
}
// Wait for all threads to stop
Task.WaitAll(tasks.ToArray());
quitEvent.WaitOne();
}
public void Shutdown()
{
Global.running = false;
// Shutdown modules
foreach (IModule module in modules)
module.Shutdown();
@ -69,7 +72,12 @@ namespace OmniLinkBridge
if (tasks != null)
Task.WaitAll(tasks.ToArray());
log.Debug("Shutdown completed");
using (LogContext.PushProperty("Telemetry", "Shutdown"))
log.Information("Shutdown completed with uptime {Uptime}", (DateTime.Now - startTime).ToString());
Log.CloseAndFlush();
quitEvent.Set();
}
}
}

View File

@ -1,14 +1,19 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
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
@ -25,6 +30,10 @@ namespace OmniLinkBridge
{
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)
{
@ -41,5 +50,14 @@ namespace OmniLinkBridge
.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,22 +1,25 @@
using OmniLinkBridge.MQTT;
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 running;
// Config File
public static string config_file;
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;
@ -32,6 +35,8 @@ namespace OmniLinkBridge
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;
@ -40,6 +45,7 @@ namespace OmniLinkBridge
// 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
@ -48,10 +54,17 @@ namespace OmniLinkBridge
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, OverrideZone> mqtt_discovery_override_zone;
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;
@ -59,6 +72,7 @@ namespace OmniLinkBridge
// 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;
@ -71,5 +85,10 @@ namespace OmniLinkBridge
// 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,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OmniLinkBridge.MQTT
{
public class Alarm : Device
{
public string command_topic { get; set; }
//public string code { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,10 @@
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

@ -0,0 +1,16 @@
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

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

View File

@ -1,30 +0,0 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OmniLinkBridge.MQTT
{
public class BinarySensor : Device
{
[JsonConverter(typeof(StringEnumConverter))]
public enum DeviceClass
{
battery,
door,
garage_door,
gas,
moisture,
motion,
problem,
smoke,
window
}
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public DeviceClass? device_class { get; set; }
}
}

View File

@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OmniLinkBridge.MQTT
{
public class Device
{
public string name { get; set; }
public string state_topic { get; set; }
public string availability_topic { get; set; } = "omnilink/status";
}
}

View File

@ -0,0 +1,66 @@
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

@ -0,0 +1,30 @@
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

@ -0,0 +1,42 @@
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

@ -0,0 +1,17 @@
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,13 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace OmniLinkBridge.MQTT
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; }
@ -16,6 +20,9 @@ namespace OmniLinkBridge.MQTT
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" });
@ -24,7 +31,8 @@ namespace OmniLinkBridge.MQTT
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 hold_state_topic { get; set; }
public string hold_command_topic { get; set; }
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

@ -0,0 +1,44 @@
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

@ -0,0 +1,11 @@
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,13 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OmniLinkBridge.MQTT
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; }

View File

@ -0,0 +1,26 @@
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

@ -0,0 +1,23 @@
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

@ -0,0 +1,16 @@
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,15 +1,15 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OmniLinkBridge.MQTT
namespace OmniLinkBridge.MQTT.HomeAssistant
{
public class Sensor : Device
{
public Sensor(DeviceRegistry deviceRegistry) : base(deviceRegistry)
{
}
[JsonConverter(typeof(StringEnumConverter))]
public enum DeviceClass
{
@ -22,5 +22,8 @@ namespace OmniLinkBridge.MQTT
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string unit_of_measurement { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string value_template { get; set; }
}
}

View File

@ -0,0 +1,23 @@
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,9 +1,9 @@
using System;
using HAI_Shared;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HAI_Shared;
using OmniLinkBridge.MQTT.HomeAssistant;
using OmniLinkBridge.MQTT.Parser;
using OmniLinkBridge.Modules;
namespace OmniLinkBridge.MQTT
{
@ -11,24 +11,75 @@ namespace OmniLinkBridge.MQTT
{
public static string ToTopic(this clsArea area, Topic topic)
{
return $"omnilink/area{area.Number.ToString()}/{topic.ToString()}";
return $"{Global.mqtt_prefix}/area{area.Number}/{topic}";
}
public static Alarm ToConfig(this clsArea area)
{
Alarm ret = new Alarm();
ret.name = area.Name;
ret.state_topic = area.ToTopic(Topic.state);
ret.command_topic = area.ToTopic(Topic.command);
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.AreaBurglaryAlarmText != "OK")
if (area.AreaAlarms.IsBitSet(0) || // Burgulary
area.AreaAlarms.IsBitSet(3) || // Auxiliary
area.AreaAlarms.IsBitSet(6)) // Duress
return "triggered";
else if (area.ExitTimer > 0)
return "pending";
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)
{
@ -39,43 +90,241 @@ namespace OmniLinkBridge.MQTT
case enuSecurityMode.DayInst:
return "armed_home";
case enuSecurityMode.Away:
case enuSecurityMode.Vacation:
return "armed_away";
case enuSecurityMode.Vacation:
return "armed_vacation";
case enuSecurityMode.Off:
default:
return "disarmed";
}
}
public static string ToTopic(this clsZone zone, Topic topic)
public static BinarySensor ToConfigBurglary(this clsArea area)
{
return $"omnilink/zone{zone.Number.ToString()}/{topic.ToString()}";
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 Sensor ToConfigTemp(this clsZone zone)
public static BinarySensor ToConfigFire(this clsArea area)
{
Sensor ret = new Sensor();
ret.name = zone.Name;
ret.device_class = Sensor.DeviceClass.temperature;
ret.state_topic = zone.ToTopic(Topic.state);
ret.unit_of_measurement = "°F";
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();
ret.name = zone.Name;
ret.device_class = Sensor.DeviceClass.humidity;
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);
ret.unit_of_measurement = "%";
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();
ret.name = zone.Name;
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);
@ -114,46 +363,79 @@ namespace OmniLinkBridge.MQTT
}
}
ret.state_topic = zone.ToTopic(Topic.state);
ret.state_topic = zone.ToTopic(Topic.basic_state);
return ret;
}
public static string ToState(this clsZone zone)
{
if (zone.IsTemperatureZone() || zone.IsHumidityZone())
return zone.TempText();
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 zone.Status.IsBitSet(0) ? "ON" : "OFF";
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 $"omnilink/unit{unit.Number.ToString()}/{topic.ToString()}";
return $"{Global.mqtt_prefix}/unit{unit.Number}/{topic}";
}
public static Light ToConfig(this clsUnit unit)
{
Light ret = new Light();
ret.name = unit.Name;
ret.state_topic = unit.ToTopic(Topic.state);
ret.command_topic = unit.ToTopic(Topic.command);
ret.brightness_state_topic = unit.ToTopic(Topic.brightness_state);
ret.brightness_command_topic = unit.ToTopic(Topic.brightness_command);
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();
ret.name = unit.Name;
ret.state_topic = unit.ToTopic(Topic.state);
ret.command_topic = unit.ToTopic(Topic.command);
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 ? "OFF" : "ON";
return unit.Status == 0 || unit.Status == 100 ? UnitCommands.OFF.ToString() : UnitCommands.ON.ToString();
}
public static int ToBrightnessState(this clsUnit unit)
@ -166,58 +448,322 @@ namespace OmniLinkBridge.MQTT
return 0;
}
public static string ToTopic(this clsThermostat thermostat, Topic topic)
public static string ToSceneState(this clsUnit unit)
{
return $"omnilink/thermostat{thermostat.Number.ToString()}/{topic.ToString()}";
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 Climate ToConfig(this clsThermostat thermostat)
public static string ToTopic(this clsThermostat thermostat, Topic topic)
{
Climate ret = new Climate();
ret.name = thermostat.Name;
ret.current_temperature_topic = thermostat.ToTopic(Topic.current_temperature);
return $"{Global.mqtt_prefix}/thermostat{thermostat.Number}/{topic}";
}
ret.temperature_low_state_topic = thermostat.ToTopic(Topic.temperature_heat_state);
ret.temperature_low_command_topic = thermostat.ToTopic(Topic.temperature_heat_command);
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;
}
ret.temperature_high_state_topic = thermostat.ToTopic(Topic.temperature_cool_state);
ret.temperature_high_command_topic = thermostat.ToTopic(Topic.temperature_cool_command);
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;
}
ret.mode_state_topic = thermostat.ToTopic(Topic.mode_state);
ret.mode_command_topic = thermostat.ToTopic(Topic.mode_command);
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;
}
ret.fan_mode_state_topic = thermostat.ToTopic(Topic.fan_mode_state);
ret.fan_mode_command_topic = thermostat.ToTopic(Topic.fan_mode_command);
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";
}
ret.hold_state_topic = thermostat.ToTopic(Topic.hold_state);
ret.hold_command_topic = thermostat.ToTopic(Topic.hold_command);
return ret;
}
public static string ToOperationState(this clsThermostat thermostat)
{
string status = thermostat.HorC_StatusText();
if (status.Contains("COOLING"))
return "cool";
else if (status.Contains("HEATING"))
return "heat";
if (thermostat.HorC_Status.IsBitSet(0))
return "heating";
else if (thermostat.HorC_Status.IsBitSet(1))
return "cooling";
else
return "idle";
}
public static string ToTopic(this clsButton button, Topic topic)
public static string ToModeState(this clsThermostat thermostat)
{
return $"omnilink/button{button.Number.ToString()}/{topic.ToString()}";
if (thermostat.Mode == enuThermostatMode.E_Heat)
return "e_heat";
else
return thermostat.ModeText().ToLower();
}
public static Switch ToConfig(this clsButton button)
public static string ToModeBasicState(this clsThermostat thermostat)
{
Switch ret = new Switch();
ret.name = button.Name;
ret.state_topic = button.ToTopic(Topic.state);
ret.command_topic = button.ToTopic(Topic.command);
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

@ -0,0 +1,416 @@
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

@ -0,0 +1,19 @@
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

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

View File

@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OmniLinkBridge.MQTT.HomeAssistant;
namespace OmniLinkBridge.MQTT
{

View File

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

View File

@ -0,0 +1,14 @@
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

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

View File

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

View File

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

View File

@ -0,0 +1,43 @@
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

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

View File

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

View File

@ -1,13 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OmniLinkBridge.MQTT
{
public class Switch : Device
{
public string command_topic { get; set; }
}
}

View File

@ -1,56 +0,0 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OmniLinkBridge.MQTT
{
public class Topic
{
public string Value { get; private set; }
private Topic(string value)
{
Value = value;
}
public override string ToString()
{
return Value;
}
public static Topic state { get { return new Topic("state"); } }
public static Topic command { get { return new Topic("command"); } }
public static Topic brightness_state { get { return new Topic("brightness_state"); } }
public static Topic brightness_command { get { return new Topic("brightness_command"); } }
public static Topic current_operation { get { return new Topic("current_operation"); } }
public static Topic current_temperature { get { return new Topic("current_temperature"); } }
public static Topic current_humidity { get { return new Topic("current_humidity"); } }
public static Topic temperature_heat_state { get { return new Topic("temperature_heat_state"); } }
public static Topic temperature_heat_command { get { return new Topic("temperature_heat_command"); } }
public static Topic temperature_cool_state { get { return new Topic("temperature_cool_state"); } }
public static Topic temperature_cool_command { get { return new Topic("temperature_cool_command"); } }
public static Topic humidify_state { get { return new Topic("humidify_state"); } }
public static Topic humidify_command { get { return new Topic("humidify_command"); } }
public static Topic dehumidify_state { get { return new Topic("dehumidify_state"); } }
public static Topic dehumidify_command { get { return new Topic("dehumidify_command"); } }
public static Topic mode_state { get { return new Topic("mode_state"); } }
public static Topic mode_command { get { return new Topic("mode_command"); } }
public static Topic fan_mode_state { get { return new Topic("fan_mode_state"); } }
public static Topic fan_mode_command { get { return new Topic("fan_mode_command"); } }
public static Topic hold_state { get { return new Topic("hold_state"); } }
public static Topic hold_command { get { return new Topic("hold_command"); } }
}
}

View File

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

View File

@ -1,6 +1,8 @@
using OmniLinkBridge.Notifications;
using HAI_Shared;
using OmniLinkBridge.Notifications;
using OmniLinkBridge.OmniLink;
using log4net;
using Serilog;
using Serilog.Context;
using System;
using System.Collections.Generic;
using System.Data;
@ -12,28 +14,33 @@ namespace OmniLinkBridge.Modules
{
public class LoggerModule : IModule
{
private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
private OmniLinkII omnilink;
private List<string> alarms = new List<string>();
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 Queue<string> mysql_queue = new Queue<string>();
private object mysql_lock = new object();
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;
}
@ -41,26 +48,23 @@ namespace OmniLinkBridge.Modules
{
if (Global.mysql_logging)
{
log.Info("Connecting to database");
log.Warning("MySQL logging is deprecated");
log.Information("Connecting to database");
mysql_conn = new OdbcConnection(Global.mysql_connection);
// Must make an initial connection
if (!DBOpen())
Environment.Exit(1);
}
while (true)
{
// End gracefully when not logging or database queue empty
if (!Global.running && (!Global.mysql_logging || DBQueueCount() == 0))
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 (!Global.running)
if (!running)
break;
if (mysql_retry < DateTime.Now)
@ -100,11 +104,11 @@ namespace OmniLinkBridge.Modules
{
if (mysql_conn.State != ConnectionState.Open)
{
log.Warn("Lost connection to database");
log.Warning("Lost connection to database");
}
else
{
log.Error("Error executing query\r\n" + query, ex);
log.Error(ex, "Error executing {query}", query);
// Prevent an endless loop from failed query
lock (mysql_lock)
@ -119,67 +123,143 @@ namespace OmniLinkBridge.Modules
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)
{
// Alarm notifcation
if (e.Area.AreaFireAlarmText != "OK")
{
Notification.Notify("ALARM", "FIRE " + e.Area.Name + " " + e.Area.AreaFireAlarmText, NotificationPriority.Emergency);
if (!alarms.Contains("FIRE" + e.ID))
alarms.Add("FIRE" + e.ID);
}
else if (alarms.Contains("FIRE" + e.ID))
{
Notification.Notify("ALARM CLEARED", "FIRE " + e.Area.Name + " " + e.Area.AreaFireAlarmText, NotificationPriority.High);
alarms.Remove("FIRE" + e.ID);
}
if (e.Area.AreaBurglaryAlarmText != "OK")
{
Notification.Notify("ALARM", "BURGLARY " + e.Area.Name + " " + e.Area.AreaBurglaryAlarmText, NotificationPriority.Emergency);
if (!alarms.Contains("BURGLARY" + e.ID))
alarms.Add("BURGLARY" + e.ID);
}
else if (alarms.Contains("BURGLARY" + e.ID))
{
Notification.Notify("ALARM CLEARED", "BURGLARY " + e.Area.Name + " " + e.Area.AreaBurglaryAlarmText, NotificationPriority.High);
alarms.Remove("BURGLARY" + e.ID);
}
if (e.Area.AreaAuxAlarmText != "OK")
{
Notification.Notify("ALARM", "AUX " + e.Area.Name + " " + e.Area.AreaAuxAlarmText, NotificationPriority.Emergency);
if (!alarms.Contains("AUX" + e.ID))
alarms.Add("AUX" + e.ID);
}
else if (alarms.Contains("AUX" + e.ID))
{
Notification.Notify("ALARM CLEARED", "AUX " + e.Area.Name + " " + e.Area.AreaAuxAlarmText, NotificationPriority.High);
alarms.Remove("AUX" + e.ID);
}
if (e.Area.AreaDuressAlarmText != "OK")
{
Notification.Notify("ALARM", "DURESS " + e.Area.Name + " " + e.Area.AreaDuressAlarmText, NotificationPriority.Emergency);
if (!alarms.Contains("DURESS" + e.ID))
alarms.Add("DURESS" + e.ID);
}
else if (alarms.Contains("DURESS" + e.ID))
{
Notification.Notify("ALARM CLEARED", "DURESS " + e.Area.Name + " " + e.Area.AreaDuressAlarmText, NotificationPriority.High);
alarms.Remove("DURESS" + e.ID);
}
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();
@ -190,7 +270,7 @@ namespace OmniLinkBridge.Modules
status = "TRIPPED " + status;
DBQueue(@"
INSERT INTO log_areas (timestamp, e.AreaID, name,
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 + "','" +
@ -198,12 +278,29 @@ namespace OmniLinkBridge.Modules
e.Area.AreaDuressAlarmText + "','" + status + "')");
if (Global.verbose_area)
log.Debug("AreaStatus " + e.ID + " " + e.Area.Name + ", Status: " + status);
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(@"
@ -213,26 +310,22 @@ namespace OmniLinkBridge.Modules
if (Global.verbose_zone)
{
if (e.Zone.IsTemperatureZone())
log.Debug("ZoneStatus " + e.ID + " " + e.Zone.Name + ", Temp: " + e.Zone.TempText());
log.Verbose("ZoneStatus {id} {name}, Temp: {temp}", e.ID, e.Zone.Name, e.Zone.TempText());
else
log.Debug("ZoneStatus" + e.ID + " " + e.Zone.Name + ", Status: " + e.Zone.StatusText());
log.Verbose("ZoneStatus {id} {name}, Status: {status}", e.ID, e.Zone.Name, e.Zone.StatusText());
}
}
private void Omnilink_OnThermostatStatus(object sender, ThermostatStatusEventArgs e)
{
if (e.EventTimer)
return;
int temp, heat, cool, humidity, humidify, dehumidify;
Int32.TryParse(e.Thermostat.TempText(), out temp);
Int32.TryParse(e.Thermostat.HeatSetpointText(), out heat);
Int32.TryParse(e.Thermostat.CoolSetpointText(), out cool);
Int32.TryParse(e.Thermostat.HumidityText(), out humidity);
Int32.TryParse(e.Thermostat.HumidifySetpointText(), out humidify);
Int32.TryParse(e.Thermostat.DehumidifySetpointText(), out dehumidify);
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,
@ -243,14 +336,21 @@ namespace OmniLinkBridge.Modules
humidity + "','" + humidify + "','" + dehumidify + "','" +
e.Thermostat.ModeText() + "','" + e.Thermostat.FanModeText() + "','" + e.Thermostat.HoldStatusText() + "')");
if (Global.verbose_thermostat)
log.Debug("ThermostatStatus " + e.ID + " " + e.Thermostat.Name +
", Status: " + e.Thermostat.TempText() + " " + e.Thermostat.HorC_StatusText() +
", Heat: " + e.Thermostat.HeatSetpointText() +
", Cool: " + e.Thermostat.CoolSetpointText() +
", Mode: " + e.Thermostat.ModeText() +
", Fan: " + e.Thermostat.FanModeText() +
", Hold: " + 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)
@ -263,13 +363,13 @@ namespace OmniLinkBridge.Modules
status = "ON";
DBQueue(@"
INSERT INTO log_e.Units (timestamp, id, name,
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.Debug("UnitStatus " + e.ID + " " + e.Unit.Name + ", Status: " + status);
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)
@ -279,12 +379,25 @@ namespace OmniLinkBridge.Modules
VALUES ('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + e.ID + "','" + e.Message.Name + "','" + e.Message.StatusText() + "')");
if (Global.verbose_message)
log.Debug("MessageStatus " + e.Message.Name + ", " + e.Message.StatusText());
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(@"
@ -292,7 +405,7 @@ namespace OmniLinkBridge.Modules
VALUES ('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + e.Type.ToString() + "','" + e.Value + "')");
if (Global.verbose_event)
log.Debug("SystemEvent " + e.Type.ToString() + " " + e.Value);
log.Verbose("SystemEvent {name}, Status: {status}", e.Type.ToString(), e.Value);
if (e.SendNotification)
Notification.Notify("SystemEvent", e.Type.ToString() + " " + e.Value);
@ -309,7 +422,7 @@ namespace OmniLinkBridge.Modules
}
catch (Exception ex)
{
log.Error("Failed to connect to database", ex);
log.Error(ex, "Failed to connect to database");
mysql_retry = DateTime.Now.AddMinutes(1);
return false;
}

View File

@ -1,46 +1,80 @@
using HAI_Shared;
using OmniLinkBridge.OmniLink;
using log4net;
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.Threading;
using Newtonsoft.Json;
using MQTTnet.Extensions.ManagedClient;
using OmniLinkBridge.MQTT;
using MQTTnet.Protocol;
using System.Text.RegularExpressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace OmniLinkBridge.Modules
{
public class MQTTModule : IModule
{
private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
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 Regex regexTopic = new Regex("omnilink/([A-Za-z]+)([0-9]+)/(.*)", RegexOptions.Compiled);
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);
.WithTcpServer(Global.mqtt_server)
.WithWillMessage(lastwill);
if (!string.IsNullOrEmpty(Global.mqtt_username))
options = options
@ -52,175 +86,61 @@ namespace OmniLinkBridge.Modules
.Build();
MqttClient = new MqttFactory().CreateManagedMqttClient();
MqttClient.Connected += (sender, e) => { log.Debug("Connected"); };
MqttClient.ConnectingFailed += (sender, e) => { log.Debug("Error " + e.Exception.Message); };
MqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate((e) =>
{
log.Debug("Connected");
MqttClient.StartAsync(manoptions);
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"
};
MqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
// 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.SubscribeAsync(new TopicFilterBuilder().WithTopic("omnilink/+/" + Topic.command).Build());
MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("omnilink/+/" + Topic.brightness_command).Build());
MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("omnilink/+/" + Topic.temperature_heat_command).Build());
MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("omnilink/+/" + Topic.temperature_cool_command).Build());
MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("omnilink/+/" + Topic.humidify_command).Build());
MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("omnilink/+/" + Topic.dehumidify_command).Build());
MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("omnilink/+/" + Topic.mode_command).Build());
MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("omnilink/+/" + Topic.fan_mode_command).Build());
MqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("omnilink/+/" + Topic.hold_command).Build());
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();
MqttClient.PublishAsync("omnilink/status", "offline", MqttQualityOfServiceLevel.AtMostOnce, true);
}
PublishControllerStatus(OFFLINE);
private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
{
Match match = regexTopic.Match(e.ApplicationMessage.Topic);
if (!match.Success)
return;
string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
log.Debug($"Received: Type: {match.Groups[1].Value}, Id: {match.Groups[2].Value}, Command: {match.Groups[3].Value}, Value: {payload}");
if (match.Groups[1].Value == "area" && ushort.TryParse(match.Groups[2].Value, out ushort areaId) && areaId < OmniLink.Controller.Areas.Count)
{
ProcessAreaReceived(OmniLink.Controller.Areas[areaId], match.Groups[3].Value, payload);
}
else if (match.Groups[1].Value == "unit" && ushort.TryParse(match.Groups[2].Value, out ushort unitId) && unitId < OmniLink.Controller.Units.Count)
{
ProcessUnitReceived(OmniLink.Controller.Units[unitId], match.Groups[3].Value, payload);
}
else if (match.Groups[1].Value == "thermostat" && ushort.TryParse(match.Groups[2].Value, out ushort thermostatId) && thermostatId < OmniLink.Controller.Thermostats.Count)
{
ProcessThermostatReceived(OmniLink.Controller.Thermostats[thermostatId], match.Groups[3].Value, payload);
}
else if (match.Groups[1].Value == "button" && ushort.TryParse(match.Groups[2].Value, out ushort buttonId) && buttonId < OmniLink.Controller.Buttons.Count)
{
ProcessButtonReceived(OmniLink.Controller.Buttons[buttonId], match.Groups[3].Value, payload);
}
}
private void ProcessAreaReceived(clsArea area, string command, string payload)
{
if (string.Compare(command, Topic.command.ToString()) == 0)
{
switch(payload)
{
case "ARM_HOME":
log.Debug("SetArea: " + area.Number + " to home");
OmniLink.Controller.SendCommand(enuUnitCommand.SecurityDay, 0, (ushort)area.Number);
break;
case "ARM_AWAY":
log.Debug("SetArea: " + area.Number + " to away");
OmniLink.Controller.SendCommand(enuUnitCommand.SecurityAway, 0, (ushort)area.Number);
break;
case "ARM_NIGHT":
log.Debug("SetArea: " + area.Number + " to night");
OmniLink.Controller.SendCommand(enuUnitCommand.SecurityNight, 0, (ushort)area.Number);
break;
case "DISARM":
log.Debug("SetArea: " + area.Number + " to disarm");
OmniLink.Controller.SendCommand(enuUnitCommand.SecurityOff, 0, (ushort)area.Number);
break;
// The below aren't supported by Home Assistant
case "ARM_HOME_INSTANT":
log.Debug("SetArea: " + area.Number + " to home instant");
OmniLink.Controller.SendCommand(enuUnitCommand.SecurityDyi, 0, (ushort)area.Number);
break;
case "ARM_NIGHT_DELAY":
log.Debug("SetArea: " + area.Number + " to night delay");
OmniLink.Controller.SendCommand(enuUnitCommand.SecurityNtd, 0, (ushort)area.Number);
break;
case "ARM_VACATION":
log.Debug("SetArea: " + area.Number + " to vacation");
OmniLink.Controller.SendCommand(enuUnitCommand.SecurityVac, 0, (ushort)area.Number);
break;
}
}
}
private void ProcessUnitReceived(clsUnit unit, string command, string payload)
{
if (string.Compare(command, Topic.command.ToString()) == 0 && (payload == "ON" || payload == "OFF"))
{
if (unit.ToState() != payload)
{
log.Debug("SetUnit: " + unit.Number + " to " + payload);
if (payload == "ON")
OmniLink.Controller.SendCommand(enuUnitCommand.On, 0, (ushort)unit.Number);
else
OmniLink.Controller.SendCommand(enuUnitCommand.Off, 0, (ushort)unit.Number);
}
}
else if (string.Compare(command, Topic.brightness_command.ToString()) == 0 && Int32.TryParse(payload, out int unitValue))
{
log.Debug("SetUnit: " + unit.Number + " to " + payload + "%");
OmniLink.Controller.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);
}
}
private void ProcessThermostatReceived(clsThermostat thermostat, string command, string payload)
{
if (string.Compare(command, Topic.temperature_heat_command.ToString()) == 0 && double.TryParse(payload, out double tempLow))
{
int temp = tempLow.ToCelsius().ToOmniTemp();
log.Debug("SetThermostatHeatSetpoint: " + thermostat.Number + " to " + payload + "F (" + temp + ")");
OmniLink.Controller.SendCommand(enuUnitCommand.SetLowSetPt, BitConverter.GetBytes(temp)[0], (ushort)thermostat.Number);
}
else if (string.Compare(command, Topic.temperature_cool_command.ToString()) == 0 && double.TryParse(payload, out double tempHigh))
{
int temp = tempHigh.ToCelsius().ToOmniTemp();
log.Debug("SetThermostatCoolSetpoint: " + thermostat.Number + " to " + payload + "F (" + temp + ")");
OmniLink.Controller.SendCommand(enuUnitCommand.SetHighSetPt, BitConverter.GetBytes(temp)[0], (ushort)thermostat.Number);
}
else if (string.Compare(command, Topic.humidify_command.ToString()) == 0 && double.TryParse(payload, out double humidify))
{
int level = humidify.ToCelsius().ToOmniTemp();
log.Debug("SetThermostatHumidifySetpoint: " + thermostat.Number + " to " + payload + "% (" + level + ")");
OmniLink.Controller.SendCommand(enuUnitCommand.SetHumidifySetPt, BitConverter.GetBytes(level)[0], (ushort)thermostat.Number);
}
else if (string.Compare(command, Topic.dehumidify_command.ToString()) == 0 && double.TryParse(payload, out double dehumidify))
{
int level = dehumidify.ToCelsius().ToOmniTemp();
log.Debug("SetThermostatDehumidifySetpoint: " + thermostat.Number + " to " + payload + "% (" + level + ")");
OmniLink.Controller.SendCommand(enuUnitCommand.SetDeHumidifySetPt, BitConverter.GetBytes(level)[0], (ushort)thermostat.Number);
}
else if (string.Compare(command, Topic.mode_command.ToString()) == 0 && Enum.TryParse(payload, true, out enuThermostatMode mode))
{
log.Debug("SetThermostatMode: " + thermostat.Number + " to " + payload);
OmniLink.Controller.SendCommand(enuUnitCommand.Mode, BitConverter.GetBytes((int)mode)[0], (ushort)thermostat.Number);
}
else if (string.Compare(command, Topic.fan_mode_command.ToString()) == 0 && Enum.TryParse(payload, true, out enuThermostatFanMode fanMode))
{
log.Debug("SetThermostatFanMode: " + thermostat.Number + " to " + payload);
OmniLink.Controller.SendCommand(enuUnitCommand.Fan, BitConverter.GetBytes((int)fanMode)[0], (ushort)thermostat.Number);
}
else if (string.Compare(command, Topic.hold_command.ToString()) == 0 && Enum.TryParse(payload, true, out enuThermostatHoldMode holdMode))
{
log.Debug("SetThermostatHold: " + thermostat.Number + " to " + payload);
OmniLink.Controller.SendCommand(enuUnitCommand.Hold, BitConverter.GetBytes((int)holdMode)[0], (ushort)thermostat.Number);
}
}
private void ProcessButtonReceived(clsButton button, string command, string payload)
{
if (string.Compare(command, Topic.command.ToString()) == 0 && payload == "ON")
{
log.Debug("PushButton: " + button.Number);
OmniLink.Controller.SendCommand(enuUnitCommand.Button, 0, (ushort)button.Number);
}
MqttClient.StopAsync().Wait();
}
public void Shutdown()
@ -230,193 +150,598 @@ namespace OmniLinkBridge.Modules
private void OmniLink_OnConnect(object sender, EventArgs e)
{
PublishConfig();
if(MqttClient.IsConnected)
PublishConfig();
MqttClient.PublishAsync("omnilink/status", "online", MqttQualityOfServiceLevel.AtMostOnce, true);
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 areas");
log.Debug("Publishing {type}", "areas");
for (ushort i = 1; i < OmniLink.Controller.Areas.Count; i++)
for (ushort i = 1; i <= OmniLink.Controller.Areas.Count; i++)
{
clsArea area = OmniLink.Controller.Areas[i];
if (area.DefaultProperties == true)
// 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)
{
MqttClient.PublishAsync($"{Global.mqtt_discovery_prefix}/alarm_control_panel/omnilink/area{i.ToString()}/config", null, MqttQualityOfServiceLevel.AtMostOnce, 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);
MqttClient.PublishAsync($"{Global.mqtt_discovery_prefix}/alarm_control_panel/omnilink/area{i.ToString()}/config",
JsonConvert.SerializeObject(area.ToConfig()), MqttQualityOfServiceLevel.AtMostOnce, true);
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 zones");
log.Debug("Publishing {type}", "zones");
for (ushort i = 1; i < OmniLink.Controller.Zones.Count; i++)
for (ushort i = 1; i <= OmniLink.Controller.Zones.Count; i++)
{
clsZone zone = OmniLink.Controller.Zones[i];
if (zone.DefaultProperties == true || Global.mqtt_discovery_ignore_zones.Contains(zone.Number))
if (zone.DefaultProperties == true)
{
MqttClient.PublishAsync($"{Global.mqtt_discovery_prefix}/sensor/omnilink/zone{i.ToString()}/config", null, MqttQualityOfServiceLevel.AtMostOnce, true);
MqttClient.PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/omnilink/zone{i.ToString()}/config", null, MqttQualityOfServiceLevel.AtMostOnce, true);
continue;
}
PublishZoneState(zone);
if (zone.IsTemperatureZone())
{
MqttClient.PublishAsync($"{Global.mqtt_discovery_prefix}/sensor/omnilink/zone{i.ToString()}/config",
JsonConvert.SerializeObject(zone.ToConfigTemp()), MqttQualityOfServiceLevel.AtMostOnce, true);
}
else if (zone.IsHumidityZone())
{
MqttClient.PublishAsync($"{Global.mqtt_discovery_prefix}/sensor/omnilink/zone{i.ToString()}/config",
JsonConvert.SerializeObject(zone.ToConfigHumidity()), MqttQualityOfServiceLevel.AtMostOnce, true);
PublishAsync(zone.ToTopic(Topic.name), null);
}
else
{
MqttClient.PublishAsync($"{Global.mqtt_discovery_prefix}/binary_sensor/omnilink/zone{i.ToString()}/config",
JsonConvert.SerializeObject(zone.ToConfig()), MqttQualityOfServiceLevel.AtMostOnce, true);
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 units");
log.Debug("Publishing {type}", "units");
for (ushort i = 1; i < OmniLink.Controller.Units.Count; i++)
for (ushort i = 1; i <= OmniLink.Controller.Units.Count; i++)
{
string type = i < 385 ? "light" : "switch";
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))
{
MqttClient.PublishAsync($"{Global.mqtt_discovery_prefix}/{type}/omnilink/unit{i.ToString()}/config", null, MqttQualityOfServiceLevel.AtMostOnce, true);
foreach(UnitType entry in Enum.GetValues(typeof(UnitType)))
PublishAsync($"{Global.mqtt_discovery_prefix}/{entry}/{Global.mqtt_prefix}/unit{i}/config", null);
continue;
}
PublishUnitState(unit);
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);
MqttClient.PublishAsync($"{Global.mqtt_discovery_prefix}/{type}/omnilink/unit{i.ToString()}/config",
JsonConvert.SerializeObject(unit.ToConfig()), MqttQualityOfServiceLevel.AtMostOnce, true);
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 thermostats");
log.Debug("Publishing {type}", "thermostats");
for (ushort i = 1; i < OmniLink.Controller.Thermostats.Count; i++)
for (ushort i = 1; i <= OmniLink.Controller.Thermostats.Count; i++)
{
clsThermostat thermostat = OmniLink.Controller.Thermostats[i];
if (thermostat.DefaultProperties == true)
{
MqttClient.PublishAsync($"{Global.mqtt_discovery_prefix}/climate/omnilink/thermostat{i.ToString()}/config", null, MqttQualityOfServiceLevel.AtMostOnce, 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);
MqttClient.PublishAsync($"{Global.mqtt_discovery_prefix}/climate/omnilink/thermostat{i.ToString()}/config",
JsonConvert.SerializeObject(thermostat.ToConfig()), MqttQualityOfServiceLevel.AtMostOnce, true);
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 buttons");
log.Debug("Publishing {type}", "buttons");
for (ushort i = 1; i < OmniLink.Controller.Buttons.Count; i++)
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)
{
MqttClient.PublishAsync($"{Global.mqtt_discovery_prefix}/switch/omnilink/button{i.ToString()}/config", null, MqttQualityOfServiceLevel.AtMostOnce, 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 always off
MqttClient.PublishAsync(button.ToTopic(Topic.state), "OFF", MqttQualityOfServiceLevel.AtMostOnce, true);
// Buttons are off unless momentarily pressed
PublishAsync(button.ToTopic(Topic.state), "OFF");
MqttClient.PublishAsync($"{Global.mqtt_discovery_prefix}/switch/omnilink/button{i.ToString()}/config",
JsonConvert.SerializeObject(button.ToConfig()), MqttQualityOfServiceLevel.AtMostOnce, true);
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(!e.EventTimer)
PublishThermostatState(e.Thermostat);
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)
{
MqttClient.PublishAsync(area.ToTopic(Topic.state), area.ToState(), MqttQualityOfServiceLevel.AtMostOnce, true);
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)
{
MqttClient.PublishAsync(zone.ToTopic(Topic.state), zone.ToState(), MqttQualityOfServiceLevel.AtMostOnce, true);
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)
{
MqttClient.PublishAsync(unit.ToTopic(Topic.state), unit.ToState(), MqttQualityOfServiceLevel.AtMostOnce, true);
PublishAsync(unit.ToTopic(Topic.state), unit.ToState());
if(unit.Number < 385)
MqttClient.PublishAsync(unit.ToTopic(Topic.brightness_state), unit.ToBrightnessState().ToString(), MqttQualityOfServiceLevel.AtMostOnce, true);
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)
{
MqttClient.PublishAsync(thermostat.ToTopic(Topic.current_operation), thermostat.ToOperationState(), MqttQualityOfServiceLevel.AtMostOnce, true);
MqttClient.PublishAsync(thermostat.ToTopic(Topic.current_temperature), thermostat.TempText(), MqttQualityOfServiceLevel.AtMostOnce, true);
MqttClient.PublishAsync(thermostat.ToTopic(Topic.current_humidity), thermostat.HumidityText(), MqttQualityOfServiceLevel.AtMostOnce, true);
MqttClient.PublishAsync(thermostat.ToTopic(Topic.temperature_heat_state), thermostat.HeatSetpointText(), MqttQualityOfServiceLevel.AtMostOnce, true);
MqttClient.PublishAsync(thermostat.ToTopic(Topic.temperature_cool_state), thermostat.CoolSetpointText(), MqttQualityOfServiceLevel.AtMostOnce, true);
MqttClient.PublishAsync(thermostat.ToTopic(Topic.humidify_state), thermostat.HumidifySetpointText(), MqttQualityOfServiceLevel.AtMostOnce, true);
MqttClient.PublishAsync(thermostat.ToTopic(Topic.dehumidify_state), thermostat.DehumidifySetpointText(), MqttQualityOfServiceLevel.AtMostOnce, true);
MqttClient.PublishAsync(thermostat.ToTopic(Topic.mode_state), thermostat.ModeText().ToLower(), MqttQualityOfServiceLevel.AtMostOnce, true);
MqttClient.PublishAsync(thermostat.ToTopic(Topic.fan_mode_state), thermostat.FanModeText().ToLower(), MqttQualityOfServiceLevel.AtMostOnce, true);
MqttClient.PublishAsync(thermostat.ToTopic(Topic.hold_state), thermostat.HoldStatusText().ToLower(), MqttQualityOfServiceLevel.AtMostOnce, true);
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,6 +1,7 @@
using HAI_Shared;
using OmniLinkBridge.OmniLink;
using log4net;
using Serilog;
using Serilog.Context;
using System;
using System.Collections.Generic;
using System.Reflection;
@ -10,26 +11,37 @@ using System.Threading.Tasks;
namespace OmniLinkBridge.Modules
{
public class OmniLinkII : IModule
public class OmniLinkII : IModule, IOmniLinkII
{
private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
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 Dictionary<ushort, DateTime> tstats = new Dictionary<ushort, DateTime>();
private System.Timers.Timer tstat_timer = new System.Timers.Timer();
private object tstat_lock = new object();
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);
@ -38,10 +50,10 @@ namespace OmniLinkBridge.Modules
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.Connection.ControllerKey = clsUtil.HexString2ByteArray(string.Concat(key1, key2));
Controller.PreferredNetworkProtocol = clsHAC.enuPreferredNetworkProtocol.TCP;
Controller.Connection.ConnectionType = enuOmniLinkConnectionType.Network_TCP;
@ -52,8 +64,8 @@ namespace OmniLinkBridge.Modules
public void Startup()
{
while (Global.running)
{
while(running)
{
// Make sure controller connection is active
if (Controller.Connection.ConnectionState == enuOmniLinkConnectionState.Offline &&
retry < DateTime.Now)
@ -63,13 +75,22 @@ namespace OmniLinkBridge.Modules
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()
{
@ -77,6 +98,7 @@ namespace OmniLinkBridge.Modules
{
retry = DateTime.Now.AddMinutes(1);
log.Debug("Controller: {connectionStatus}", "Connect");
Controller.Connection.Connect(HandleConnectStatus, HandleUnsolicitedPackets);
}
}
@ -84,192 +106,42 @@ namespace OmniLinkBridge.Modules
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.NoReply:
log.Error("CONNECTION STATUS: No Reply");
break;
case enuOmniLinkCommStatus.UnrecognizedReply:
log.Error("CONNECTION STATUS: Unrecognized Reply");
break;
case enuOmniLinkCommStatus.UnsupportedProtocol:
log.Error("CONNECTION STATUS: Unsupported Protocol");
break;
case enuOmniLinkCommStatus.ClientSessionTerminated:
log.Error("CONNECTION STATUS: Client Session Terminated");
break;
case enuOmniLinkCommStatus.ControllerSessionTerminated:
log.Error("CONNECTION STATUS: Controller Session Terminated");
break;
case enuOmniLinkCommStatus.CannotStartNewSession:
log.Error("CONNECTION STATUS: Cannot Start New Session");
break;
case enuOmniLinkCommStatus.LoginFailed:
log.Error("CONNECTION STATUS: Login Failed");
break;
case enuOmniLinkCommStatus.UnableToOpenSocket:
log.Error("CONNECTION STATUS: Unable To Open Socket");
break;
case enuOmniLinkCommStatus.UnableToConnect:
log.Error("CONNECTION STATUS: Unable To Connect");
break;
case enuOmniLinkCommStatus.SocketClosed:
log.Error("CONNECTION STATUS: Socket Closed");
break;
case enuOmniLinkCommStatus.UnexpectedError:
log.Error("CONNECTION STATUS: Unexpected Error");
break;
case enuOmniLinkCommStatus.UnableToCreateSocket:
log.Error("CONNECTION STATUS: Unable To Create Socket");
break;
case enuOmniLinkCommStatus.Retrying:
log.Warn("CONNECTION STATUS: Retrying");
case enuOmniLinkCommStatus.Connecting:
log.Debug("Controller Status: {connectionStatus}", status);
break;
case enuOmniLinkCommStatus.Connected:
IdentifyController();
break;
case enuOmniLinkCommStatus.Connecting:
log.Info("CONNECTION STATUS: Connecting");
break;
case enuOmniLinkCommStatus.Disconnected:
log.Info("CONNECTION STATUS: Disconnected");
log.Information("Controller Status: {connectionStatus}", status);
OnDisconnect?.Invoke(this, new EventArgs());
break;
case enuOmniLinkCommStatus.InterruptedFunctionCall:
if (Global.running)
log.Error("CONNECTION STATUS: Interrupted Function Call");
break;
case enuOmniLinkCommStatus.PermissionDenied:
log.Error("CONNECTION STATUS: Permission Denied");
break;
case enuOmniLinkCommStatus.BadAddress:
log.Error("CONNECTION STATUS: Bad Address");
break;
case enuOmniLinkCommStatus.InvalidArgument:
log.Error("CONNECTION STATUS: Invalid Argument");
break;
case enuOmniLinkCommStatus.TooManyOpenFiles:
log.Error("CONNECTION STATUS: Too Many Open Files");
break;
case enuOmniLinkCommStatus.ResourceTemporarilyUnavailable:
log.Error("CONNECTION STATUS: Resource Temporarily Unavailable");
if (running)
log.Error("Controller Status: {connectionStatus}", status);
break;
case enuOmniLinkCommStatus.Retrying:
case enuOmniLinkCommStatus.OperationNowInProgress:
log.Warn("CONNECTION STATUS: Operation Now In Progress");
break;
case enuOmniLinkCommStatus.OperationAlreadyInProgress:
log.Warn("CONNECTION STATUS: Operation Already In Progress");
break;
case enuOmniLinkCommStatus.SocketOperationOnNonSocket:
log.Error("CONNECTION STATUS: Socket Operation On Non Socket");
break;
case enuOmniLinkCommStatus.DestinationAddressRequired:
log.Error("CONNECTION STATUS: Destination Address Required");
break;
case enuOmniLinkCommStatus.MessgeTooLong:
log.Error("CONNECTION STATUS: Message Too Long");
break;
case enuOmniLinkCommStatus.WrongProtocolType:
log.Error("CONNECTION STATUS: Wrong Protocol Type");
break;
case enuOmniLinkCommStatus.BadProtocolOption:
log.Error("CONNECTION STATUS: Bad Protocol Option");
break;
case enuOmniLinkCommStatus.ProtocolNotSupported:
log.Error("CONNECTION STATUS: Protocol Not Supported");
break;
case enuOmniLinkCommStatus.SocketTypeNotSupported:
log.Error("CONNECTION STATUS: Socket Type Not Supported");
break;
case enuOmniLinkCommStatus.OperationNotSupported:
log.Error("CONNECTION STATUS: Operation Not Supported");
break;
case enuOmniLinkCommStatus.ProtocolFamilyNotSupported:
log.Error("CONNECTION STATUS: Protocol Family Not Supported");
break;
case enuOmniLinkCommStatus.AddressFamilyNotSupported:
log.Error("CONNECTION STATUS: Address Family Not Supported");
break;
case enuOmniLinkCommStatus.AddressInUse:
log.Error("CONNECTION STATUS: Address In Use");
break;
case enuOmniLinkCommStatus.AddressNotAvailable:
log.Error("CONNECTION STATUS: Address Not Available");
break;
case enuOmniLinkCommStatus.NetworkIsDown:
log.Error("CONNECTION STATUS: Network Is Down");
break;
case enuOmniLinkCommStatus.NetworkIsUnreachable:
log.Error("CONNECTION STATUS: Network Is Unreachable");
break;
case enuOmniLinkCommStatus.NetworkReset:
log.Error("CONNECTION STATUS: Network Reset");
break;
case enuOmniLinkCommStatus.ConnectionAborted:
log.Error("CONNECTION STATUS: Connection Aborted");
break;
case enuOmniLinkCommStatus.ConnectionResetByPeer:
log.Error("CONNECTION STATUS: Connection Reset By Peer");
break;
case enuOmniLinkCommStatus.NoBufferSpaceAvailable:
log.Error("CONNECTION STATUS: No Buffer Space Available");
break;
case enuOmniLinkCommStatus.AlreadyConnected:
log.Warn("CONNECTION STATUS: Already Connected");
break;
case enuOmniLinkCommStatus.NotConnected:
log.Error("CONNECTION STATUS: Not Connected");
break;
case enuOmniLinkCommStatus.CannotSendAfterShutdown:
log.Error("CONNECTION STATUS: Cannot Send After Shutdown");
break;
case enuOmniLinkCommStatus.ConnectionTimedOut:
log.Error("CONNECTION STATUS: Connection Timed Out");
break;
case enuOmniLinkCommStatus.ConnectionRefused:
log.Error("CONNECTION STATUS: Connection Refused");
break;
case enuOmniLinkCommStatus.HostIsDown:
log.Error("CONNECTION STATUS: Host Is Down");
break;
case enuOmniLinkCommStatus.HostUnreachable:
log.Error("CONNECTION STATUS: Host Unreachable");
break;
case enuOmniLinkCommStatus.TooManyProcesses:
log.Error("CONNECTION STATUS: Too Many Processes");
break;
case enuOmniLinkCommStatus.NetworkSubsystemIsUnavailable:
log.Error("CONNECTION STATUS: Network Subsystem Is Unavailable");
break;
case enuOmniLinkCommStatus.UnsupportedVersion:
log.Error("CONNECTION STATUS: Unsupported Version");
break;
case enuOmniLinkCommStatus.NotInitialized:
log.Error("CONNECTION STATUS: Not Initialized");
break;
case enuOmniLinkCommStatus.ShutdownInProgress:
log.Error("CONNECTION STATUS: Shutdown In Progress");
break;
case enuOmniLinkCommStatus.ClassTypeNotFound:
log.Error("CONNECTION STATUS: Class Type Not Found");
break;
case enuOmniLinkCommStatus.HostNotFound:
log.Error("CONNECTION STATUS: Host Not Found");
break;
case enuOmniLinkCommStatus.HostNotFoundTryAgain:
log.Error("CONNECTION STATUS: Host Not Found Try Again");
break;
case enuOmniLinkCommStatus.NonRecoverableError:
log.Error("CONNECTION STATUS: Non Recoverable Error");
break;
case enuOmniLinkCommStatus.NoDataOfRequestedType:
log.Error("CONNECTION STATUS: No Data Of Requested Type");
log.Warning("Controller Status: {connectionStatus}", status);
break;
default:
log.Error("Controller Status: {connectionStatus}", status);
break;
}
}
@ -283,7 +155,7 @@ namespace OmniLinkBridge.Modules
}
}
private void HandleIdentifyController(clsOmniLinkMessageQueueItem M, byte[] B, bool Timeout)
private async void HandleIdentifyController(clsOmniLinkMessageQueueItem M, byte[] B, bool Timeout)
{
if (Timeout)
return;
@ -304,10 +176,12 @@ namespace OmniLinkBridge.Modules
if (Controller.Model == MSG.ModelNumber)
{
Controller.CopySystemInformation(MSG);
log.Info("CONTROLLER IS: " + Controller.GetModelText() + " (" + Controller.GetVersionText() + ")");
_ = Connected();
using (LogContext.PushProperty("Telemetry", "Controller"))
log.Information("Controller is {ControllerModel} firmware {ControllerVersion}",
Controller.GetModelText(), Controller.GetVersionText());
await ConnectedAsync();
return;
}
@ -316,7 +190,7 @@ namespace OmniLinkBridge.Modules
}
}
private async Task Connected()
private async Task ConnectedAsync()
{
retry = DateTime.MinValue;
@ -327,6 +201,8 @@ namespace OmniLinkBridge.Modules
tstat_timer.Start();
OnConnect?.Invoke(this, new EventArgs());
Program.ShowSendLogsWarning();
}
#endregion
@ -335,34 +211,71 @@ namespace OmniLinkBridge.Modules
{
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(() =>
{
log.Debug("Waiting for named units " + type.ToString());
nameWait.WaitOne(new TimeSpan(0, 0, 10));
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)
{
clsOL2MsgRequestProperties MSG = new clsOL2MsgRequestProperties(Controller.Connection);
MSG.ObjectType = type;
MSG.IndexNumber = (UInt16)ix;
MSG.RelativeDirection = 1; // next object after IndexNumber
MSG.Filter1 = 1; // (0=Named or Unnamed, 1=Named, 2=Unnamed).
MSG.Filter2 = 0; // Any Area
MSG.Filter3 = 0; // Any Room
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);
}
@ -379,8 +292,30 @@ namespace OmniLinkBridge.Modules
case enuOmniLink2MessageType.EOD:
nameWait.Set();
break;
case enuOmniLink2MessageType.Properties:
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)
@ -391,8 +326,9 @@ namespace OmniLinkBridge.Modules
case enuObjectType.Zone:
Controller.Zones.CopyProperties(MSG);
if (Controller.Zones[MSG.ObjectNumber].IsTemperatureZone())
Controller.Connection.Send(new clsOL2MsgRequestExtendedStatus(Controller.Connection, enuObjectType.Auxillary, MSG.ObjectNumber, MSG.ObjectNumber), HandleRequestAuxillaryStatus);
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:
@ -403,8 +339,10 @@ namespace OmniLinkBridge.Modules
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 " + Controller.Thermostats[MSG.ObjectNumber].Name);
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);
@ -415,6 +353,17 @@ namespace OmniLinkBridge.Modules
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;
}
@ -432,7 +381,7 @@ namespace OmniLinkBridge.Modules
#region Notifications
private void UnsolicitedNotifications(bool enable)
{
log.Info("Unsolicited notifications " + (enable ? "enabled" : "disabled"));
log.Debug("Unsolicited notifications {status}", (enable ? "enabled" : "disabled"));
Controller.Connection.Send(new clsOL2EnableNotifications(Controller.Connection, enable), null);
}
@ -495,6 +444,8 @@ namespace OmniLinkBridge.Modules
case enuOmniLink2MessageType.CmdExtSecurity:
break;
case enuOmniLink2MessageType.AudioSourceStatus:
// Ignore audio source metadata status updates
handled = true;
break;
case enuOmniLink2MessageType.SystemEvents:
HandleUnsolicitedSystemEvent(B);
@ -525,92 +476,114 @@ namespace OmniLinkBridge.Modules
if (MSG.SystemEvent >= 1 && MSG.SystemEvent <= 255)
{
eventargs.Type = enuEventType.USER_MACRO_BUTTON;
eventargs.Type = SystemEventType.Button;
eventargs.Value = ((int)MSG.SystemEvent).ToString() + " " + Controller.Buttons[MSG.SystemEvent].Name;
OnSystemStatus?.Invoke(this, eventargs);
}
else if (MSG.SystemEvent >= 768 && MSG.SystemEvent <= 771)
{
eventargs.Type = enuEventType.PHONE_;
if (MSG.SystemEvent == 768)
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 == 769)
else if (MSG.SystemEvent == (ushort)enuEventType.PHONE_LINE_RING)
eventargs.Value = "RING";
else if (MSG.SystemEvent == 770)
else if (MSG.SystemEvent == (ushort)enuEventType.PHONE_LINE_OFF_HOOK)
eventargs.Value = "OFF HOOK";
else if (MSG.SystemEvent == 771)
else if (MSG.SystemEvent == (ushort)enuEventType.PHONE_LINE_ON_HOOK)
eventargs.Value = "ON HOOK";
OnSystemStatus?.Invoke(this, eventargs);
}
else if (MSG.SystemEvent >= 772 && MSG.SystemEvent <= 773)
else if (MSG.SystemEvent >= (ushort)enuEventType.AC_POWER_OFF &&
MSG.SystemEvent <= (ushort)enuEventType.AC_POWER_RESTORED)
{
eventargs.Type = enuEventType.AC_POWER_;
eventargs.Type = SystemEventType.AC;
eventargs.SendNotification = true;
if (MSG.SystemEvent == 772)
if (MSG.SystemEvent == (ushort)enuEventType.AC_POWER_OFF)
{
eventargs.Value = "OFF";
else if (MSG.SystemEvent == 773)
eventargs.Trouble = true;
}
else if (MSG.SystemEvent == (ushort)enuEventType.AC_POWER_RESTORED)
eventargs.Value = "RESTORED";
OnSystemStatus?.Invoke(this, eventargs);
}
else if (MSG.SystemEvent >= 774 && MSG.SystemEvent <= 775)
else if (MSG.SystemEvent >= (ushort)enuEventType.BATTERY_LOW &&
MSG.SystemEvent <= (ushort)enuEventType.BATTERY_OK)
{
eventargs.Type = enuEventType.BATTERY_;
eventargs.Type = SystemEventType.Battery;
eventargs.SendNotification = true;
if (MSG.SystemEvent == 774)
if (MSG.SystemEvent == (ushort)enuEventType.BATTERY_LOW)
{
eventargs.Value = "LOW";
else if (MSG.SystemEvent == 775)
eventargs.Trouble = true;
}
else if (MSG.SystemEvent == (ushort)enuEventType.BATTERY_OK)
eventargs.Value = "OK";
OnSystemStatus?.Invoke(this, eventargs);
}
else if (MSG.SystemEvent >= 776 && MSG.SystemEvent <= 777)
else if (MSG.SystemEvent >= (ushort)enuEventType.DCM_TROUBLE &&
MSG.SystemEvent <= (ushort)enuEventType.DCM_OK)
{
eventargs.Type = enuEventType.DCM_;
eventargs.Type = SystemEventType.DCM;
eventargs.SendNotification = true;
if (MSG.SystemEvent == 776)
if (MSG.SystemEvent == (ushort)enuEventType.DCM_TROUBLE)
{
eventargs.Value = "TROUBLE";
else if (MSG.SystemEvent == 777)
eventargs.Trouble = true;
}
else if (MSG.SystemEvent == (ushort)enuEventType.DCM_OK)
eventargs.Value = "OK";
OnSystemStatus?.Invoke(this, eventargs);
}
else if (MSG.SystemEvent >= 778 && MSG.SystemEvent <= 781)
else if (MSG.SystemEvent >= (ushort)enuEventType.ENERGY_COST_LOW &&
MSG.SystemEvent <= (ushort)enuEventType.ENERGY_COST_CRITICAL)
{
eventargs.Type = enuEventType.ENERGY_COST_;
eventargs.Type = SystemEventType.EnergyCost;
if (MSG.SystemEvent == 778)
if (MSG.SystemEvent == (ushort)enuEventType.ENERGY_COST_LOW)
eventargs.Value = "LOW";
else if (MSG.SystemEvent == 779)
else if (MSG.SystemEvent == (ushort)enuEventType.ENERGY_COST_MID)
eventargs.Value = "MID";
else if (MSG.SystemEvent == 780)
else if (MSG.SystemEvent == (ushort)enuEventType.ENERGY_COST_HIGH)
eventargs.Value = "HIGH";
else if (MSG.SystemEvent == 781)
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 = enuEventType.CAMERA;
eventargs.Type = SystemEventType.Camera;
eventargs.Value = (MSG.SystemEvent - 781).ToString();
OnSystemStatus?.Invoke(this, eventargs);
}
else if (MSG.SystemEvent >= 61440 && MSG.SystemEvent <= 64511)
{
eventargs.Type = enuEventType.SWITCH_PRESS;
int state = (int)MSG.Data[1] - 240;
int id = (int)MSG.Data[2];
eventargs.Type = SystemEventType.SwitchPress;
int state = MSG.Data[1] - 240;
int id = MSG.Data[2];
eventargs.Value = "Unit: " + id + ", State: " + state;
@ -618,9 +591,9 @@ namespace OmniLinkBridge.Modules
}
else if (MSG.SystemEvent >= 64512 && MSG.SystemEvent <= 65535)
{
eventargs.Type = enuEventType.UPB_LINK;
int state = (int)MSG.Data[1] - 252;
int id = (int)MSG.Data[2];
eventargs.Type = SystemEventType.UPBLink;
int state = MSG.Data[1] - 252;
int id = MSG.Data[2];
eventargs.Value = "Link: " + id + ", State: " + state;
@ -631,9 +604,9 @@ namespace OmniLinkBridge.Modules
StringBuilder sb = new StringBuilder();
for (int i = 0; i < MSG.MessageLength; i++)
sb.Append(MSG.Data[i].ToString() + " ");
log.Debug("Unhandled SystemEvent Raw: " + sb.ToString() + "Num: " + MSG.SystemEvent);
log.Debug("Unhandled SystemEvent Raw: {raw}, Num: {num}", sb.ToString(), MSG.SystemEvent);
int num = ((int)MSG.MessageLength - 1) / 2;
int num = (MSG.MessageLength - 1) / 2;
for (int i = 0; i < num; i++)
{
log.Debug("Unhandled SystemEvent: " +
@ -688,10 +661,12 @@ namespace OmniLinkBridge.Modules
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
});
@ -701,7 +676,8 @@ namespace OmniLinkBridge.Modules
tstats[MSG.ObjectNumber(i)] = DateTime.Now;
if (Global.verbose_thermostat_timer)
log.Debug("Unsolicited status received for Thermostat " + Controller.Thermostats[MSG.ObjectNumber(i)].Name);
log.Debug("Unsolicited status received for Thermostat {thermostatName}",
Controller.Thermostats[MSG.ObjectNumber(i)].Name);
}
}
break;
@ -727,6 +703,28 @@ namespace OmniLinkBridge.Modules
});
}
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)
{
@ -760,12 +758,16 @@ namespace OmniLinkBridge.Modules
foreach (KeyValuePair<ushort, DateTime> tstat in tstats)
{
// Poll every 4 minutes if no prior update
if (RoundToMinute(tstat.Value).AddMinutes(4) <= RoundToMinute(DateTime.Now))
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);
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 " + Controller.Thermostats[tstat.Key].Name);
log.Debug("Polling status for Thermostat {thermostatName}",
Controller.Thermostats[tstat.Key].Name);
}
// Log every minute if update within 5 minutes and connected
@ -773,20 +775,17 @@ namespace OmniLinkBridge.Modules
(Controller.Connection.ConnectionState == enuOmniLinkConnectionState.Online ||
Controller.Connection.ConnectionState == enuOmniLinkConnectionState.OnlineSecure))
{
if (Controller.Thermostats[tstat.Key].Temp > 0)
OnThermostatStatus?.Invoke(this, new ThermostatStatusEventArgs()
{
OnThermostatStatus?.Invoke(this, new ThermostatStatusEventArgs()
{
ID = tstat.Key,
Thermostat = Controller.Thermostats[tstat.Key],
EventTimer = true
});
}
else if (Global.verbose_thermostat_timer)
log.Warn("Not logging unknown temp for Thermostat " + Controller.Thermostats[tstat.Key].Name);
ID = tstat.Key,
Thermostat = Controller.Thermostats[tstat.Key],
Offline = Controller.Thermostats[tstat.Key].Temp == 0,
EventTimer = true
});
}
else if (Global.verbose_thermostat_timer)
log.Warn("Not logging out of date status for Thermostat " + Controller.Thermostats[tstat.Key].Name);
log.Warning("Not logging out of date status for Thermostat {thermostatName}",
Controller.Thermostats[tstat.Key].Name);
}
}
@ -813,7 +812,8 @@ namespace OmniLinkBridge.Modules
tstats[MSG.ObjectNumber(i)] = DateTime.Now;
if (Global.verbose_thermostat_timer)
log.Debug("Polling status received for Thermostat " + Controller.Thermostats[MSG.ObjectNumber(i)].Name);
log.Debug("Polling status received for Thermostat {thermostatName}",
Controller.Thermostats[MSG.ObjectNumber(i)].Name);
}
}
}

View File

@ -1,6 +1,5 @@
using HAI_Shared;
using OmniLinkBridge.OmniLink;
using log4net;
using Serilog;
using System;
using System.Reflection;
using System.Threading;
@ -9,11 +8,11 @@ namespace OmniLinkBridge.Modules
{
public class TimeSyncModule : IModule
{
private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
private OmniLinkII OmniLink { get; set; }
private System.Timers.Timer tsync_timer = new System.Timers.Timer();
private readonly System.Timers.Timer tsync_timer = new System.Timers.Timer();
private DateTime tsync_check = DateTime.MinValue;
private readonly AutoResetEvent trigger = new AutoResetEvent(false);
@ -75,14 +74,15 @@ namespace OmniLinkBridge.Modules
// Extract the 2 digit prefix to use when parsing the time
int year = DateTime.Now.Year / 100;
time = new DateTime((int)MSG.Year + (year * 100), (int)MSG.Month, (int)MSG.Day, (int)MSG.Hour, (int)MSG.Minute, (int)MSG.Second);
time = new DateTime(MSG.Year + (year * 100), MSG.Month, MSG.Day, MSG.Hour, MSG.Minute, MSG.Second);
}
catch
{
log.Warn("Controller time could not be parsed");
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,
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;
@ -92,10 +92,12 @@ namespace OmniLinkBridge.Modules
if (adj > Global.time_drift)
{
log.Warn("Controller time " + time.ToString("MM/dd/yyyy HH:mm:ss") + " out of sync by " + adj + " seconds");
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,
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);
}
}

View File

@ -1,9 +1,8 @@
using HAI_Shared;
using Newtonsoft.Json;
using OmniLinkBridge.Modules;
using OmniLinkBridge.OmniLink;
using OmniLinkBridge.WebAPI;
using log4net;
using Newtonsoft.Json;
using Serilog;
using System;
using System.Reflection;
using System.ServiceModel;
@ -15,7 +14,7 @@ namespace OmniLinkBridge
{
public class WebServiceModule : IModule
{
private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
public static OmniLinkII OmniLink { get; private set; }
@ -34,6 +33,8 @@ namespace OmniLinkBridge
public void Startup()
{
log.Warning("WebAPI is deprecated");
WebNotification.RestoreSubscriptions();
Uri uri = new Uri("http://0.0.0.0:" + Global.webapi_port + "/");
@ -44,11 +45,11 @@ namespace OmniLinkBridge
ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IOmniLinkService), new WebHttpBinding(), "");
host.Open();
log.Info("Listening on " + uri.ToString());
log.Information("Listening on {url}", uri);
}
catch (CommunicationException ex)
{
log.Error("An exception occurred starting web service", ex);
log.Error(ex, "An exception occurred starting web service");
host.Abort();
}
@ -79,30 +80,7 @@ namespace OmniLinkBridge
return;
}
switch (e.Zone.ZoneType)
{
case enuZoneType.EntryExit:
case enuZoneType.X2EntryDelay:
case enuZoneType.X4EntryDelay:
case enuZoneType.Perimeter:
case enuZoneType.Tamper:
case enuZoneType.Auxiliary:
WebNotification.Send("contact", JsonConvert.SerializeObject(e.Zone.ToContract()));
break;
case enuZoneType.AwayInt:
case enuZoneType.NightInt:
WebNotification.Send("motion", JsonConvert.SerializeObject(e.Zone.ToContract()));
break;
case enuZoneType.Water:
WebNotification.Send("water", JsonConvert.SerializeObject(e.Zone.ToContract()));
break;
case enuZoneType.Fire:
WebNotification.Send("smoke", JsonConvert.SerializeObject(e.Zone.ToContract()));
break;
case enuZoneType.Gas:
WebNotification.Send("co", JsonConvert.SerializeObject(e.Zone.ToContract()));
break;
}
WebNotification.Send(Enum.GetName(typeof(DeviceType), e.Zone.ToDeviceType()), JsonConvert.SerializeObject(e.Zone.ToContract()));
}
private void Omnilink_OnUnitStatus(object sender, UnitStatusEventArgs e)
@ -112,7 +90,9 @@ namespace OmniLinkBridge
private void Omnilink_OnThermostatStatus(object sender, ThermostatStatusEventArgs e)
{
if(!e.EventTimer)
// 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,4 +1,5 @@
using log4net;
using OmniLinkBridge.Modules;
using Serilog;
using System;
using System.Net;
using System.Net.Mail;
@ -8,34 +9,38 @@ namespace OmniLinkBridge.Notifications
{
public class EmailNotification : INotification
{
private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
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();
mail.From = Global.mail_from;
mail.To.Add(address);
mail.Subject = "OmniLinkBridge - " + source;
mail.Body = source + ": " + description;
using (SmtpClient smtp = new SmtpClient(Global.mail_server, Global.mail_port))
MailMessage mail = new MailMessage
{
if (!string.IsNullOrEmpty(Global.mail_username))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(Global.mail_username, Global.mail_password);
}
From = Global.mail_from,
Subject = $"{Global.controller_name} - {source}",
Body = $"{source}: {description}"
};
mail.To.Add(address);
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
log.Error("An error occurred sending notification", ex);
}
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,10 +1,15 @@
using System.Collections.Generic;
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(),
@ -16,7 +21,14 @@ namespace OmniLinkBridge.Notifications
{
Parallel.ForEach(providers, (provider) =>
{
provider.Notify(source, description, priority);
try
{
provider.Notify(source, description, priority);
}
catch (Exception ex)
{
log.Error(ex, "Failed to send notification");
}
});
}
}

View File

@ -1,4 +1,4 @@
using log4net;
using Serilog;
using System;
using System.Collections.Generic;
using System.Net;
@ -8,35 +8,34 @@ namespace OmniLinkBridge.Notifications
{
public class ProwlNotification : INotification
{
private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
private static Uri URI = new Uri("https://api.prowlapp.com/publicapi/add");
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>();
parameters.Add("apikey=" + key);
parameters.Add("priority= " + (int)priority);
parameters.Add("application=OmniLinkBridge");
parameters.Add("event=" + source);
parameters.Add("description=" + description);
using (WebClient client = new WebClient())
List<string> parameters = new List<string>
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
client.UploadStringAsync(URI, string.Join("&", parameters.ToArray()));
client.UploadStringCompleted += client_UploadStringCompleted;
}
"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)
private void Client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error != null)
log.Error("An error occurred sending notification", e.Error);
log.Error(e.Error, "An error occurred sending prowl notification");
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -7,6 +7,15 @@ namespace OmniLinkBridge.OmniLink
{
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

@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>OmniLinkBridge</RootNamespace>
<AssemblyName>OmniLinkBridge</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
@ -24,6 +24,7 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
@ -34,6 +35,7 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
@ -43,6 +45,8 @@
<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>
@ -52,6 +56,8 @@
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<NoWarn>IDE1006</NoWarn>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<PropertyGroup>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
@ -74,23 +80,49 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ControllerEnricher.cs" />
<Compile Include="CoreServer.cs" />
<Compile Include="Modules\TimeSyncModule.cs" />
<Compile Include="MQTT\Alarm.cs" />
<Compile Include="MQTT\BinarySensor.cs" />
<Compile Include="MQTT\Device.cs" />
<Compile Include="MQTT\Climate.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\Switch.cs" />
<Compile Include="MQTT\Light.cs" />
<Compile Include="MQTT\HomeAssistant\Switch.cs" />
<Compile Include="MQTT\HomeAssistant\Light.cs" />
<Compile Include="MQTT\MappingExtensions.cs" />
<Compile Include="MQTT\Sensor.cs" />
<Compile Include="MQTT\Topics.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" />
@ -123,6 +155,7 @@
</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" />
@ -131,6 +164,7 @@
<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">
@ -149,14 +183,35 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="log4net">
<Version>2.0.8</Version>
<PackageReference Include="Mono.Posix-4.5">
<Version>4.5.0</Version>
</PackageReference>
<PackageReference Include="MQTTnet.Extensions.ManagedClient">
<Version>2.8.4</Version>
<Version>3.1.2</Version>
</PackageReference>
<PackageReference Include="Newtonsoft.Json">
<Version>11.0.2</Version>
<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" />

View File

@ -0,0 +1,10 @@
<?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,33 +1,40 @@
# HAI / Leviton Omni Controller
controller_address =
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_check is interval in minutes to check controller time
# time_adj is the drift in seconds to allow before an adjustment is made
time_sync = yes
# 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 =
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 = yes
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
@ -36,14 +43,52 @@ 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
# specify a range of numbers like 1,2,3,5-10
# 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 =
# device_class must be battery, door, garage_door, gas, moisture, motion, problem, smoke, or window
# 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
@ -53,6 +98,8 @@ 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 =

View File

@ -1,19 +1,32 @@
using System;
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
{
class Program
internal class Program
{
static CoreServer server;
private static CoreServer server;
static void Main(string[] args)
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])
@ -22,9 +35,31 @@ namespace OmniLinkBridge
case "-h":
case "-help":
ShowHelp();
return;
return 0;
case "-c":
Global.config_file = args[++i];
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];
@ -35,33 +70,86 @@ namespace OmniLinkBridge
}
}
if (string.IsNullOrEmpty(Global.config_file))
Global.config_file = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) +
Path.DirectorySeparatorChar + "OmniLinkBridge.ini";
if (string.Compare(Environment.GetEnvironmentVariable("SEND_LOGS"), "1") == 0)
{
Global.DebugSettings = true;
Global.SendLogs = true;
}
if (string.IsNullOrEmpty(Global.webapi_subscriptions_file))
Global.webapi_subscriptions_file = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) +
Path.DirectorySeparatorChar + "WebSubscriptions.json";
config_file = GetFullPath(config_file);
log4net.Config.XmlConfigurator.Configure();
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();
Settings.LoadSettings(config_file);
}
catch
{
// Errors are logged in LoadSettings();
Environment.Exit(1);
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);
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
server = new CoreServer();
}
else
@ -78,6 +166,16 @@ namespace OmniLinkBridge
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)
@ -86,13 +184,56 @@ namespace OmniLinkBridge
args.Cancel = true;
}
static void ShowHelp()
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] [-s subscriptions_file] [-i]\n" +
"\t-c Specifies the configuration file. Default is OmniLinkBridge.ini\n" +
"\t-s Specifies the web api subscriptions file. Default is WebSubscriptions.json\n" +
"\t-i Run in interactive mode");
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

@ -5,12 +5,12 @@ using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OmniLinkBridge")]
[assembly: AssemblyTitle("OmniLink Bridge")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Excalibur Partners, LLC")]
[assembly: AssemblyProduct("OmniLinkBridge")]
[assembly: AssemblyCopyright("Copyright © Excalibur Partners, LLC 2018")]
[assembly: AssemblyCopyright("Copyright © Excalibur Partners, LLC 2024")]
[assembly: AssemblyTrademark("")]
[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
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.1.0")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyVersion("1.1.19.0")]
[assembly: AssemblyFileVersion("1.1.19.0")]

View File

@ -1,95 +1,151 @@
using log4net;
using OmniLinkBridge.MQTT;
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;
using System.Net.Mail;
using System.Reflection;
using ha = OmniLinkBridge.MQTT.HomeAssistant;
namespace OmniLinkBridge
{
public static class Settings
{
private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
public static void LoadSettings()
public static void LoadSettings(string file)
{
NameValueCollection settings = LoadCollection(Global.config_file);
// HAI / Leviton Omni Controller
Global.controller_address = settings["controller_address"];
Global.controller_port = ValidatePort(settings, "controller_port");
Global.controller_key1 = settings["controller_key1"];
Global.controller_key2 = settings["controller_key2"];
// Controller Time Sync
Global.time_sync = ValidateYesNo(settings, "time_sync");
Global.time_interval = ValidateInt(settings, "time_interval");
Global.time_drift = ValidateInt(settings, "time_drift");
// Verbose Console
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");
// mySQL Logging
Global.mysql_logging = ValidateYesNo(settings, "mysql_logging");
Global.mysql_connection = settings["mysql_connection"];
// Web Service
Global.webapi_enabled = ValidateYesNo(settings, "webapi_enabled");
Global.webapi_port = ValidatePort(settings, "webapi_port");
// MQTT
Global.mqtt_enabled = ValidateYesNo(settings, "mqtt_enabled");
Global.mqtt_server = settings["mqtt_server"];
Global.mqtt_port = ValidatePort(settings, "mqtt_port");
Global.mqtt_username = settings["mqtt_username"];
Global.mqtt_password = settings["mqtt_password"];
Global.mqtt_discovery_prefix = settings["mqtt_discovery_prefix"];
Global.mqtt_discovery_ignore_zones = ValidateRange(settings, "mqtt_discovery_ignore_zones");
Global.mqtt_discovery_ignore_units = ValidateRange(settings, "mqtt_discovery_ignore_units");
Global.mqtt_discovery_override_zone = LoadOverrideZone(settings, "mqtt_discovery_override_zone");
// Notifications
Global.notify_area = ValidateYesNo(settings, "notify_area");
Global.notify_message = ValidateYesNo(settings, "notify_message");
// Email Notifications
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");
// Prowl Notifications
Global.prowl_key = ValidateMultipleStrings(settings, "prowl_key");
// Pushover Notifications
Global.pushover_token = settings["pushover_token"];
Global.pushover_user = ValidateMultipleStrings(settings, "pushover_user");
LoadSettings(LoadCollection(file));
}
private static ConcurrentDictionary<int, OverrideZone> LoadOverrideZone(NameValueCollection settings, string section)
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, OverrideZone> ret = new ConcurrentDictionary<int, OverrideZone>();
ConcurrentDictionary<int, T> ret = new ConcurrentDictionary<int, T>();
if (settings[section] == null)
string value = settings.CheckEnv(section);
if (string.IsNullOrEmpty(value))
return ret;
string[] ids = settings[section].Split(',');
string[] ids = value.Split(',');
for (int i = 0; i < ids.Length; i++)
{
@ -97,58 +153,224 @@ namespace OmniLinkBridge
.Select(s => s.Split('='))
.ToDictionary(a => a[0].Trim(), a => a[1].Trim(), StringComparer.InvariantCultureIgnoreCase);
if (!attributes.ContainsKey("id") || !Int32.TryParse(attributes["id"], out int attrib_id))
if (!attributes.ContainsKey("id") || !int.TryParse(attributes["id"], out int attrib_id))
throw new Exception("Missing or invalid id attribute");
if (!attributes.ContainsKey("device_class") || !Enum.TryParse(attributes["device_class"], out BinarySensor.DeviceClass attrib_device_class))
throw new Exception("Missing or invalid device_class attribute");
T override_area = new T();
ret.TryAdd(attrib_id, new OverrideZone()
if (override_area is MQTT.OverrideArea mqtt_area)
{
device_class = attrib_device_class,
});
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("Invalid override zone specified for " + section, ex);
log.Error(ex, "Invalid override area specified for {section}", section);
throw;
}
}
private static int ValidateInt(NameValueCollection settings, string section)
private static ConcurrentDictionary<int, T> LoadOverrideZone<T>(this NameValueCollection settings, string section) where T : new()
{
try
{
return Int32.Parse(settings[section]);
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);
log.Error("Invalid integer specified for {section}", section);
throw;
}
}
private static HashSet<int> ValidateRange(NameValueCollection settings, string section)
private static HashSet<int> ValidateRange(this NameValueCollection settings, string section)
{
try
{
return new HashSet<int>(settings[section].ParseRanges());
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);
log.Error("Invalid range specified for {section}", section);
throw;
}
}
private static int ValidatePort(NameValueCollection settings, string section)
private static int ValidatePort(this NameValueCollection settings, string section)
{
try
{
int port = Int32.Parse(settings[section]);
int port = int.Parse(settings.CheckEnv(section));
if (port < 1 || port > 65534)
throw new Exception();
@ -157,80 +379,34 @@ namespace OmniLinkBridge
}
catch
{
log.Error("Invalid port specified for " + section);
log.Error("Invalid port specified for {section}", section);
throw;
}
}
private static bool ValidateBool(NameValueCollection settings, string section)
private static MailAddress ValidateMailFrom(this NameValueCollection settings, string section)
{
try
{
return Boolean.Parse(settings[section]);
return new MailAddress(settings.CheckEnv(section));
}
catch
{
log.Error("Invalid bool specified for " + section);
log.Error("Invalid email specified for {section}", 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
{
log.Error("Invalid IP specified for " + section);
throw;
}
}
private static string ValidateDirectory(NameValueCollection settings, string section)
private static MailAddress[] ValidateMailTo(this NameValueCollection settings, string section)
{
try
{
if (!Directory.Exists(settings[section]))
Directory.CreateDirectory(settings[section]);
string value = settings.CheckEnv(section);
return settings[section];
}
catch
{
log.Error("Invalid directory specified for " + section);
throw;
}
}
private static MailAddress ValidateMailFrom(NameValueCollection settings, string section)
{
try
{
return new MailAddress(settings[section]);
}
catch
{
log.Error("Invalid email specified for " + section);
throw;
}
}
private static MailAddress[] ValidateMailTo(NameValueCollection settings, string section)
{
try
{
if(settings[section] == null)
if (string.IsNullOrEmpty(value))
return new MailAddress[] {};
string[] emails = settings[section].Split(',');
string[] emails = value.Split(',');
MailAddress[] addresses = new MailAddress[emails.Length];
for(int i=0; i < emails.Length; i++)
@ -240,82 +416,102 @@ namespace OmniLinkBridge
}
catch
{
log.Error("Invalid email specified for " + section);
log.Error("Invalid email specified for {section}", section);
throw;
}
}
private static string[] ValidateMultipleStrings(NameValueCollection settings, string section)
private static string[] ValidateMultipleStrings(this NameValueCollection settings, string section, bool sensitive = false)
{
try
{
if (settings[section] == null)
if (settings.CheckEnv(section, true) == null)
return new string[] { };
return settings[section].Split(',');
return settings.CheckEnv(section, sensitive).Split(',');
}
catch
{
log.Error("Invalid string specified for " + section);
log.Error("Invalid string specified for {section}", section);
throw;
}
}
private static bool ValidateYesNo (NameValueCollection settings, string section)
private static bool ValidateBool (this NameValueCollection settings, string section)
{
if (settings[section] == null)
string value = settings.CheckEnv(section);
if (value == null)
return false;
if (string.Compare(settings[section], "yes", true) == 0)
if (string.Compare(value, "yes", true) == 0 || string.Compare(value, "true", true) == 0)
return true;
else if (string.Compare(settings[section], "no", true) == 0)
else if (string.Compare(value, "no", true) == 0 || string.Compare(value, "false", true) == 0)
return false;
else
{
log.Error("Invalid yes/no specified for " + section);
log.Error("Invalid yes/no or true/false specified for {section}", section);
throw new Exception();
}
}
private static NameValueCollection LoadCollection(string sFile)
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();
try
foreach(string line in lines)
{
FileStream fs = new FileStream(sFile, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
if (line.StartsWith("#"))
continue;
while (true)
{
string line = sr.ReadLine();
int pos = line.IndexOf('=', 0);
if (line == null)
break;
if (pos == -1)
continue;
if (line.StartsWith("#"))
continue;
string key = line.Substring(0, pos).Trim();
string value = line.Substring(pos + 1).Trim();
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 ex)
{
log.Error("Unable to parse settings file " + sFile, ex);
throw;
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

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

View File

@ -1,9 +1,4 @@
using HAI_Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OmniLinkBridge.WebAPI
{
@ -13,14 +8,15 @@ namespace OmniLinkBridge.WebAPI
public static AreaContract ToContract(this clsArea area)
{
AreaContract ret = new AreaContract();
ret.id = (ushort)area.Number;
ret.name = area.Name;
ret.burglary = area.AreaBurglaryAlarmText;
ret.co = area.AreaGasAlarmText;
ret.fire = area.AreaFireAlarmText;
ret.water = area.AreaWaterAlarmText;
AreaContract ret = new AreaContract
{
id = (ushort)area.Number,
name = area.Name,
burglary = area.AreaBurglaryAlarmText,
co = area.AreaGasAlarmText,
fire = area.AreaFireAlarmText,
water = area.AreaWaterAlarmText
};
if (area.ExitTimer > 0)
{
@ -37,23 +33,29 @@ namespace OmniLinkBridge.WebAPI
public static ZoneContract ToContract(this clsZone zone)
{
ZoneContract ret = new ZoneContract();
ZoneContract ret = new ZoneContract
{
id = (ushort)zone.Number,
zonetype = zone.ZoneType,
name = zone.Name,
status = zone.StatusText()
};
ret.id = (ushort)zone.Number;
ret.zonetype = zone.ZoneType;
ret.name = zone.Name;
ret.status = zone.StatusText();
ret.temp = zone.TempText();
if (zone.IsTemperatureZone())
ret.temp = zone.TempText();
else if(zone.IsHumidityZone())
ret.temp = zone.TempText();
return ret;
}
public static UnitContract ToContract(this clsUnit unit)
{
UnitContract ret = new UnitContract();
ret.id = (ushort)unit.Number;
ret.name = unit.Name;
UnitContract ret = new UnitContract
{
id = (ushort)unit.Number,
name = unit.Name
};
if (unit.Status > 100)
ret.level = (ushort)(unit.Status - 100);
@ -67,17 +69,16 @@ namespace OmniLinkBridge.WebAPI
public static ThermostatContract ToContract(this clsThermostat unit)
{
ThermostatContract ret = new ThermostatContract();
ThermostatContract ret = new ThermostatContract
{
id = (ushort)unit.Number,
name = unit.Name
};
ret.id = (ushort)unit.Number;
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);
ushort.TryParse(unit.TempText(), out ushort temp);
ushort.TryParse(unit.HeatSetpointText(), out ushort heat);
ushort.TryParse(unit.CoolSetpointText(), out ushort cool);
ushort.TryParse(unit.HumidityText(), out ushort humidity);
ret.temp = temp;
ret.humidity = humidity;
@ -98,5 +99,35 @@ namespace OmniLinkBridge.WebAPI
return ret;
}
public static DeviceType ToDeviceType(this clsZone zone)
{
Global.webapi_override_zone.TryGetValue(zone.Number, out OverrideZone override_zone);
if (override_zone != null)
return override_zone.device_type;
switch (zone.ZoneType)
{
case enuZoneType.EntryExit:
case enuZoneType.X2EntryDelay:
case enuZoneType.X4EntryDelay:
case enuZoneType.Perimeter:
case enuZoneType.Tamper:
case enuZoneType.Auxiliary:
return DeviceType.contact;
case enuZoneType.AwayInt:
case enuZoneType.NightInt:
return DeviceType.motion;
case enuZoneType.Water:
return DeviceType.water;
case enuZoneType.Fire:
return DeviceType.smoke;
case enuZoneType.Gas:
return DeviceType.co;
default:
return DeviceType.unknown;
}
}
}
}

View File

@ -1,5 +1,5 @@
using HAI_Shared;
using log4net;
using Serilog;
using System;
using System.Collections.Generic;
using System.Reflection;
@ -11,7 +11,7 @@ namespace OmniLinkBridge.WebAPI
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class OmniLinkService : IOmniLinkService
{
private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
public void Subscribe(SubscribeContract contract)
{
@ -24,11 +24,13 @@ namespace OmniLinkBridge.WebAPI
log.Debug("ListAreas");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebServiceModule.OmniLink.Controller.Areas.Count; i++)
for (ushort i = 1; i <= WebServiceModule.OmniLink.Controller.Areas.Count; i++)
{
clsArea area = WebServiceModule.OmniLink.Controller.Areas[i];
if (area.DefaultProperties == false)
// PC Access doesn't let you customize the area name for the Omni LTe or Omni IIe
// (configured for 1 area). To workaround ignore default properties for the first area.
if (i == 1 || area.DefaultProperties == false)
names.Add(new NameContract() { id = i, name = area.Name });
}
return names;
@ -36,7 +38,7 @@ namespace OmniLinkBridge.WebAPI
public AreaContract GetArea(ushort id)
{
log.Debug("GetArea: " + id);
log.Debug("GetArea: {id}", id);
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.Headers.Add("type", "area");
@ -49,16 +51,11 @@ namespace OmniLinkBridge.WebAPI
log.Debug("ListZonesContact");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebServiceModule.OmniLink.Controller.Zones.Count; i++)
for (ushort i = 1; i <= WebServiceModule.OmniLink.Controller.Zones.Count; i++)
{
clsZone zone = WebServiceModule.OmniLink.Controller.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)
if (zone.DefaultProperties == false && zone.ToDeviceType() == DeviceType.contact)
names.Add(new NameContract() { id = i, name = zone.Name });
}
return names;
@ -69,12 +66,11 @@ namespace OmniLinkBridge.WebAPI
log.Debug("ListZonesMotion");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebServiceModule.OmniLink.Controller.Zones.Count; i++)
for (ushort i = 1; i <= WebServiceModule.OmniLink.Controller.Zones.Count; i++)
{
clsZone zone = WebServiceModule.OmniLink.Controller.Zones[i];
if ((zone.ZoneType == enuZoneType.AwayInt ||
zone.ZoneType == enuZoneType.NightInt) && zone.DefaultProperties == false)
if (zone.DefaultProperties == false && zone.ToDeviceType() == DeviceType.motion)
names.Add(new NameContract() { id = i, name = zone.Name });
}
return names;
@ -85,11 +81,11 @@ namespace OmniLinkBridge.WebAPI
log.Debug("ListZonesWater");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebServiceModule.OmniLink.Controller.Zones.Count; i++)
for (ushort i = 1; i <= WebServiceModule.OmniLink.Controller.Zones.Count; i++)
{
clsZone zone = WebServiceModule.OmniLink.Controller.Zones[i];
if (zone.ZoneType == enuZoneType.Water && zone.DefaultProperties == false)
if (zone.DefaultProperties == false && zone.ToDeviceType() == DeviceType.water)
names.Add(new NameContract() { id = i, name = zone.Name });
}
return names;
@ -100,11 +96,11 @@ namespace OmniLinkBridge.WebAPI
log.Debug("ListZonesSmoke");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebServiceModule.OmniLink.Controller.Zones.Count; i++)
for (ushort i = 1; i <= WebServiceModule.OmniLink.Controller.Zones.Count; i++)
{
clsZone zone = WebServiceModule.OmniLink.Controller.Zones[i];
if (zone.ZoneType == enuZoneType.Fire && zone.DefaultProperties == false)
if (zone.DefaultProperties == false && zone.ToDeviceType() == DeviceType.smoke)
names.Add(new NameContract() { id = i, name = zone.Name });
}
return names;
@ -115,11 +111,11 @@ namespace OmniLinkBridge.WebAPI
log.Debug("ListZonesCO");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebServiceModule.OmniLink.Controller.Zones.Count; i++)
for (ushort i = 1; i <= WebServiceModule.OmniLink.Controller.Zones.Count; i++)
{
clsZone zone = WebServiceModule.OmniLink.Controller.Zones[i];
if (zone.ZoneType == enuZoneType.Gas && zone.DefaultProperties == false)
if (zone.DefaultProperties == false && zone.ToDeviceType() == DeviceType.co)
names.Add(new NameContract() { id = i, name = zone.Name });
}
return names;
@ -130,11 +126,11 @@ namespace OmniLinkBridge.WebAPI
log.Debug("ListZonesTemp");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebServiceModule.OmniLink.Controller.Zones.Count; i++)
for (ushort i = 1; i <= WebServiceModule.OmniLink.Controller.Zones.Count; i++)
{
clsZone zone = WebServiceModule.OmniLink.Controller.Zones[i];
if (zone.IsTemperatureZone() && zone.DefaultProperties == false)
if (zone.DefaultProperties == false && zone.IsTemperatureZone())
names.Add(new NameContract() { id = i, name = zone.Name });
}
return names;
@ -142,7 +138,7 @@ namespace OmniLinkBridge.WebAPI
public ZoneContract GetZone(ushort id)
{
log.Debug("GetZone: " + id);
log.Debug("GetZone: {id}", id);
WebOperationContext ctx = WebOperationContext.Current;
@ -152,33 +148,8 @@ namespace OmniLinkBridge.WebAPI
}
else
{
switch (WebServiceModule.OmniLink.Controller.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;
}
ctx.OutgoingResponse.Headers.Add("type", Enum.GetName(typeof(DeviceType),
WebServiceModule.OmniLink.Controller.Zones[id].ToDeviceType()));
}
return WebServiceModule.OmniLink.Controller.Zones[id].ToContract();
@ -189,7 +160,7 @@ namespace OmniLinkBridge.WebAPI
log.Debug("ListUnits");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebServiceModule.OmniLink.Controller.Units.Count; i++)
for (ushort i = 1; i <= WebServiceModule.OmniLink.Controller.Units.Count; i++)
{
clsUnit unit = WebServiceModule.OmniLink.Controller.Units[i];
@ -201,7 +172,7 @@ namespace OmniLinkBridge.WebAPI
public UnitContract GetUnit(ushort id)
{
log.Debug("GetUnit: " + id);
log.Debug("GetUnit: {id}", id);
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.Headers.Add("type", "unit");
@ -211,7 +182,7 @@ namespace OmniLinkBridge.WebAPI
public void SetUnit(CommandContract unit)
{
log.Debug("SetUnit: " + unit.id + " to " + unit.value + "%");
log.Debug("SetUnit: {id} to {value}%", unit.id, unit.value);
if (unit.value == 0)
WebServiceModule.OmniLink.Controller.SendCommand(enuUnitCommand.Off, 0, unit.id);
@ -224,7 +195,7 @@ namespace OmniLinkBridge.WebAPI
public void SetUnitKeypadPress(CommandContract unit)
{
log.Debug("SetUnitKeypadPress: " + unit.id + " to " + unit.value + " button");
log.Debug("SetUnitKeypadPress: {id} to {value}", unit.id, unit.value);
WebServiceModule.OmniLink.Controller.SendCommand(enuUnitCommand.LutronHomeWorksKeypadButtonPress, BitConverter.GetBytes(unit.value)[0], unit.id);
}
@ -233,7 +204,7 @@ namespace OmniLinkBridge.WebAPI
log.Debug("ListThermostats");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebServiceModule.OmniLink.Controller.Thermostats.Count; i++)
for (ushort i = 1; i <= WebServiceModule.OmniLink.Controller.Thermostats.Count; i++)
{
clsThermostat unit = WebServiceModule.OmniLink.Controller.Thermostats[i];
@ -245,7 +216,7 @@ namespace OmniLinkBridge.WebAPI
public ThermostatContract GetThermostat(ushort id)
{
log.Debug("GetThermostat: " + id);
log.Debug("GetThermostat: {id}", id);
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.Headers.Add("type", "thermostat");
@ -255,33 +226,49 @@ namespace OmniLinkBridge.WebAPI
public void SetThermostatCoolSetpoint(CommandContract unit)
{
int temp = ((double)unit.value).ToCelsius().ToOmniTemp();
log.Debug("SetThermostatCoolSetpoint: " + unit.id + " to " + unit.value + "F (" + temp + ")");
double tempHigh = unit.value;
string tempUnit = "C";
if (WebServiceModule.OmniLink.Controller.TempFormat == enuTempFormat.Fahrenheit)
{
tempHigh = tempHigh.ToCelsius();
tempUnit = "F";
}
int temp = tempHigh.ToOmniTemp();
log.Debug("SetThermostatCoolSetpoint: {id} to {value}{tempUnit} {temp}", unit.id, unit.value, tempUnit, temp);
WebServiceModule.OmniLink.Controller.SendCommand(enuUnitCommand.SetHighSetPt, BitConverter.GetBytes(temp)[0], unit.id);
}
public void SetThermostatHeatSetpoint(CommandContract unit)
{
int temp = ((double)unit.value).ToCelsius().ToOmniTemp();
log.Debug("SetThermostatCoolSetpoint: " + unit.id + " to " + unit.value + "F (" + temp + ")");
double tempLoad = unit.value;
string tempUnit = "C";
if (WebServiceModule.OmniLink.Controller.TempFormat == enuTempFormat.Fahrenheit)
{
tempLoad = tempLoad.ToCelsius();
tempUnit = "F";
}
int temp = tempLoad.ToOmniTemp();
log.Debug("SetThermostatHeatSetpoint: {id} to {value}{tempUnit} {temp}", unit.id, unit.value, tempUnit, temp);
WebServiceModule.OmniLink.Controller.SendCommand(enuUnitCommand.SetLowSetPt, BitConverter.GetBytes(temp)[0], unit.id);
}
public void SetThermostatMode(CommandContract unit)
{
log.Debug("SetThermostatMode: " + unit.id + " to " + unit.value);
log.Debug("SetThermostatMode: {id} to {value}", unit.id, unit.value);
WebServiceModule.OmniLink.Controller.SendCommand(enuUnitCommand.Mode, BitConverter.GetBytes(unit.value)[0], unit.id);
}
public void SetThermostatFanMode(CommandContract unit)
{
log.Debug("SetThermostatFanMode: " + unit.id + " to " + unit.value);
log.Debug("SetThermostatFanMode: {id} to {value}", unit.id, unit.value);
WebServiceModule.OmniLink.Controller.SendCommand(enuUnitCommand.Fan, BitConverter.GetBytes(unit.value)[0], unit.id);
}
public void SetThermostatHold(CommandContract unit)
{
log.Debug("SetThermostatHold: " + unit.id + " to " + unit.value);
log.Debug("SetThermostatHold: {id} to {value}", unit.id, unit.value);
WebServiceModule.OmniLink.Controller.SendCommand(enuUnitCommand.Hold, BitConverter.GetBytes(unit.value)[0], unit.id);
}
@ -290,7 +277,7 @@ namespace OmniLinkBridge.WebAPI
log.Debug("ListButtons");
List<NameContract> names = new List<NameContract>();
for (ushort i = 1; i < WebServiceModule.OmniLink.Controller.Buttons.Count; i++)
for (ushort i = 1; i <= WebServiceModule.OmniLink.Controller.Buttons.Count; i++)
{
clsButton unit = WebServiceModule.OmniLink.Controller.Buttons[i];
@ -302,7 +289,7 @@ namespace OmniLinkBridge.WebAPI
public void PushButton(CommandContract unit)
{
log.Debug("PushButton: " + unit.id);
log.Debug("PushButton: {id}", unit.id);
WebServiceModule.OmniLink.Controller.SendCommand(enuUnitCommand.Button, 0, unit.id);
}
}

View File

@ -0,0 +1,7 @@
namespace OmniLinkBridge.WebAPI
{
public class OverrideZone
{
public DeviceType device_type { get; set; }
}
}

View File

@ -1,5 +1,5 @@
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
@ -10,10 +10,10 @@ namespace OmniLinkBridge.WebAPI
{
static class WebNotification
{
private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
private static List<string> subscriptions = new List<string>();
private static object subscriptions_lock = new object();
private static readonly object subscriptions_lock = new object();
public static void AddSubscription(string callback)
{
@ -52,7 +52,7 @@ namespace OmniLinkBridge.WebAPI
}
catch (Exception ex)
{
log.Error("An error occurred sending notification to " + subscription, ex);
log.Error(ex, "An error occurred sending notification to {client}", subscription);
subscriptions.Remove(subscription);
SaveSubscriptions();
}
@ -63,7 +63,7 @@ namespace OmniLinkBridge.WebAPI
{
if (e.Error != null)
{
log.Error("An error occurred sending notification to " + e.UserState.ToString(), e.Error);
log.Error(e.Error, "An error occurred sending notification to {client}", e.UserState.ToString());
lock (subscriptions_lock)
subscriptions.Remove(e.UserState.ToString());
@ -88,7 +88,7 @@ namespace OmniLinkBridge.WebAPI
}
catch (Exception ex)
{
log.Error("An error occurred restoring subscriptions", ex);
log.Error(ex, "An error occurred restoring subscriptions");
}
}
@ -107,7 +107,7 @@ namespace OmniLinkBridge.WebAPI
}
catch (Exception ex)
{
log.Error("An error occurred saving subscriptions", ex);
log.Error(ex, "An error occurred saving subscriptions");
}
}
}

View File

@ -1,19 +0,0 @@
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OmniLinkBridge;
using System.IO;
using System.Reflection;
namespace OmniLinkBridgeTest
{
[TestClass]
public class AssemblyTestHarness
{
[AssemblyInitialize]
public static void InitializeAssembly(TestContext context)
{
Global.config_file = "OmniLinkBridge.ini";
Settings.LoadSettings();
}
}
}

View File

@ -1,22 +1,108 @@
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OmniLinkBridge;
using OmniLinkBridge.MQTT;
using System.Collections.Generic;
namespace OmniLinkBridgeTest
{
[TestClass]
public class ExtensionTest
{
[TestMethod]
public void TestToCelsius()
{
Assert.AreEqual(-40, ((double)-40).ToCelsius());
Assert.AreEqual(0, ((double)32).ToCelsius());
Assert.AreEqual(50, ((double)122).ToCelsius());
}
[TestMethod]
public void TestToOmniTemp()
{
// -40C is 0
double min = -40;
Assert.AreEqual(0, min.ToOmniTemp());
// 87.5C is 255
double max = 87.5;
Assert.AreEqual(255, max.ToOmniTemp());
}
[TestMethod]
public void TestIsBitSet()
{
Assert.AreEqual(true, ((byte)1).IsBitSet(0));
Assert.AreEqual(false, ((byte)2).IsBitSet(0));
Assert.AreEqual(true, ((byte)3).IsBitSet(0));
Assert.AreEqual(true, ((byte)3).IsBitSet(1));
}
[TestMethod]
public void TestToCommandCode()
{
string payload;
AreaCommandCode parser;
payload = "disarm";
parser = payload.ToCommandCode(supportValidate: true);
Assert.AreEqual(parser.Success, true);
Assert.AreEqual(parser.Command, "disarm");
Assert.AreEqual(parser.Validate, false);
Assert.AreEqual(parser.Code, 0);
payload = "disarm,1";
parser = payload.ToCommandCode(supportValidate: true);
Assert.AreEqual(parser.Success, true);
Assert.AreEqual(parser.Command, "disarm");
Assert.AreEqual(parser.Validate, false);
Assert.AreEqual(parser.Code, 1);
payload = "disarm,validate,1234";
parser = payload.ToCommandCode(supportValidate: true);
Assert.AreEqual(parser.Success, true);
Assert.AreEqual(parser.Command, "disarm");
Assert.AreEqual(parser.Validate, true);
Assert.AreEqual(parser.Code, 1234);
// Special case for Home Assistant when code not required
payload = "disarm,validate,None";
parser = payload.ToCommandCode(supportValidate: true);
Assert.AreEqual(parser.Success, true);
Assert.AreEqual(parser.Command, "disarm");
Assert.AreEqual(parser.Validate, false);
Assert.AreEqual(parser.Code, 0);
// Falures
payload = "disarm,1a";
parser = payload.ToCommandCode(supportValidate: true);
Assert.AreEqual(parser.Success, false);
Assert.AreEqual(parser.Command, "disarm");
Assert.AreEqual(parser.Validate, false);
Assert.AreEqual(parser.Code, 0);
payload = "disarm,validate,";
parser = payload.ToCommandCode(supportValidate: true);
Assert.AreEqual(parser.Success, false);
Assert.AreEqual(parser.Command, "disarm");
Assert.AreEqual(parser.Validate, true);
Assert.AreEqual(parser.Code, 0);
payload = "disarm,test,1234";
parser = payload.ToCommandCode(supportValidate: true);
Assert.AreEqual(parser.Success, false);
Assert.AreEqual(parser.Command, "disarm");
Assert.AreEqual(parser.Validate, false);
Assert.AreEqual(parser.Code, 0);
}
[TestMethod]
public void TestParseRange()
{
List<int> blank = "".ParseRanges();
Assert.AreEqual(0, blank.Count);
List<int> empty = "".ParseRanges();
Assert.AreEqual(0, empty.Count);
List<int> range = "1-3,5,6".ParseRanges();
CollectionAssert.AreEqual(new List<int>(new int[] { 1, 2, 3, 5, 6 }), range);
}
}
}
}

View File

@ -0,0 +1,446 @@
using HAI_Shared;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OmniLinkBridge;
using OmniLinkBridge.Modules;
using OmniLinkBridge.MQTT;
using OmniLinkBridgeTest.Mock;
using Serilog;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace OmniLinkBridgeTest
{
[TestClass]
public class MQTTTest
{
MockOmniLinkII omniLink;
MessageProcessor messageProcessor;
[TestInitialize]
public void Initialize()
{
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.FromLogContext()
.WriteTo.Console(outputTemplate: log_format);
Log.Logger = log_config.CreateLogger();
Dictionary<string, int> audioSources = new Dictionary<string, int>
{
{ "Radio", 1 },
{ "Streaming", 2 },
{ "TV", 4 }
};
omniLink = new MockOmniLinkII();
messageProcessor = new MessageProcessor(omniLink, audioSources, 8);
omniLink.Controller.Units[395].Type = enuOL2UnitType.Flag;
}
[TestMethod]
public void AreaCommandInvalid()
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
// Invalid command
messageProcessor.Process($"omnilink/area1/command", "disarmed");
Assert.IsNull(actual);
// Out of range
messageProcessor.Process($"omnilink/area9/command", "disarm");
Assert.IsNull(actual);
}
[TestMethod]
public void AreaCommand()
{
void check(ushort id, int code, string payload, enuUnitCommand command)
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
messageProcessor.Process($"omnilink/area{id}/command", payload);
SendCommandEventArgs expected = new SendCommandEventArgs()
{
Cmd = command,
Par = (byte)code,
Pr2 = id
};
Assert.AreEqual(expected, actual);
}
// Standard format
check(1, 0, "disarm", enuUnitCommand.SecurityOff);
check(1, 0, "arm_home", enuUnitCommand.SecurityDay);
check(1, 0, "arm_away", enuUnitCommand.SecurityAway);
check(1, 0, "arm_night", enuUnitCommand.SecurityNight);
check(1, 0, "arm_home_instant", enuUnitCommand.SecurityDyi);
check(1, 0, "arm_night_delay", enuUnitCommand.SecurityNtd);
check(1, 0, "arm_vacation", enuUnitCommand.SecurityVac);
// Check all areas
check(0, 0, "disarm", enuUnitCommand.SecurityOff);
// Check with optional code
check(1, 1, "disarm,1", enuUnitCommand.SecurityOff);
// Check case insensitivity
check(8, 0, "DISARM", enuUnitCommand.SecurityOff);
}
[TestMethod]
public void ZoneCommand()
{
void check(ushort id, int code, string payload, enuUnitCommand command, bool ensureNull = false)
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
messageProcessor.Process($"omnilink/zone{id}/command", payload);
SendCommandEventArgs expected = new SendCommandEventArgs()
{
Cmd = command,
Par = (byte)code,
Pr2 = id
};
if (ensureNull)
Assert.IsNull(actual);
else
Assert.AreEqual(expected, actual);
}
// Standard format
check(1, 0, "bypass", enuUnitCommand.Bypass);
check(1, 0, "restore", enuUnitCommand.Restore);
// Check all zones
check(0, 0, "restore", enuUnitCommand.Restore);
// Not allowed to bypass all zones
check(0, 0, "bypass", enuUnitCommand.Bypass, true);
// Check with optional code
check(1, 1, "bypass,1", enuUnitCommand.Bypass);
// Check case insensitivity
check(2, 0, "BYPASS", enuUnitCommand.Bypass);
}
[TestMethod]
public void UnitCommand()
{
void check(ushort id, string payload, enuUnitCommand command)
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
messageProcessor.Process($"omnilink/unit{id}/command", payload);
SendCommandEventArgs expected = new SendCommandEventArgs()
{
Cmd = command,
Par = 0,
Pr2 = id
};
Assert.AreEqual(expected, actual);
}
check(1, "ON", enuUnitCommand.On);
omniLink.Controller.Units[1].Status = 1;
check(1, "OFF", enuUnitCommand.Off);
check(2, "on", enuUnitCommand.On);
}
[TestMethod]
public void UnitFlagCommand()
{
void check(ushort id, string payload, enuUnitCommand command, int value)
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
messageProcessor.Process($"omnilink/unit{id}/flag_command", payload);
SendCommandEventArgs expected = new SendCommandEventArgs()
{
Cmd = command,
Par = (byte)value,
Pr2 = id
};
Assert.AreEqual(expected, actual);
}
check(395, "0", enuUnitCommand.Set, 0);
check(395, "1", enuUnitCommand.Set, 1);
check(395, "255", enuUnitCommand.Set, 255);
}
[TestMethod]
public void UnitLevelCommand()
{
void check(ushort id, string payload, enuUnitCommand command, int level)
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
messageProcessor.Process($"omnilink/unit{id}/brightness_command", payload);
SendCommandEventArgs expected = new SendCommandEventArgs()
{
Cmd = command,
Par = (byte)level,
Pr2 = id
};
Assert.AreEqual(expected, actual);
}
check(1, "50", enuUnitCommand.Level, 50);
}
[TestMethod]
public void ThermostatModeCommandInvalid()
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
omniLink.Controller.Thermostats[1].Type = enuThermostatType.HeatCool;
messageProcessor.Process($"omnilink/thermostat1/mode_command", "auto");
Assert.IsNull(actual);
omniLink.Controller.Thermostats[1].Type = enuThermostatType.CoolOnly;
messageProcessor.Process($"omnilink/thermostat1/mode_command", "auto");
Assert.IsNull(actual);
messageProcessor.Process($"omnilink/thermostat1/mode_command", "heat");
Assert.IsNull(actual);
omniLink.Controller.Thermostats[1].Type = enuThermostatType.HeatOnly;
messageProcessor.Process($"omnilink/thermostat1/mode_command", "auto");
Assert.IsNull(actual);
messageProcessor.Process($"omnilink/thermostat1/mode_command", "cool");
Assert.IsNull(actual);
}
[TestMethod]
public void ThermostatModeCommand()
{
void check(ushort id, string payload, enuUnitCommand command, int mode)
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
messageProcessor.Process($"omnilink/thermostat{id}/mode_command", payload);
SendCommandEventArgs expected = new SendCommandEventArgs()
{
Cmd = command,
Par = (byte)mode,
Pr2 = id
};
Assert.AreEqual(expected, actual);
}
omniLink.Controller.Thermostats[1].Type = enuThermostatType.AutoHeatCool;
check(1, "auto", enuUnitCommand.Mode, (int)enuThermostatMode.Auto);
check(1, "cool", enuUnitCommand.Mode, (int)enuThermostatMode.Cool);
check(1, "heat", enuUnitCommand.Mode, (int)enuThermostatMode.Heat);
check(1, "off", enuUnitCommand.Mode, (int)enuThermostatMode.Off);
omniLink.Controller.Thermostats[1].Type = enuThermostatType.HeatCool;
check(1, "cool", enuUnitCommand.Mode, (int)enuThermostatMode.Cool);
check(1, "heat", enuUnitCommand.Mode, (int)enuThermostatMode.Heat);
check(1, "off", enuUnitCommand.Mode, (int)enuThermostatMode.Off);
omniLink.Controller.Thermostats[1].Type = enuThermostatType.CoolOnly;
check(1, "cool", enuUnitCommand.Mode, (int)enuThermostatMode.Cool);
check(1, "off", enuUnitCommand.Mode, (int)enuThermostatMode.Off);
omniLink.Controller.Thermostats[1].Type = enuThermostatType.HeatOnly;
check(1, "heat", enuUnitCommand.Mode, (int)enuThermostatMode.Heat);
check(1, "off", enuUnitCommand.Mode, (int)enuThermostatMode.Off);
}
[TestMethod]
public void ButtonCommand()
{
void check(ushort id, string payload, enuUnitCommand command)
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
messageProcessor.Process($"omnilink/button{id}/command", payload);
SendCommandEventArgs expected = new SendCommandEventArgs()
{
Cmd = command,
Par = 0,
Pr2 = id
};
Assert.AreEqual(expected, actual);
}
check(1, "ON", enuUnitCommand.Button);
check(1, "on", enuUnitCommand.Button);
}
[TestMethod]
public void MessageCommand()
{
void check(ushort id, string payload, enuUnitCommand command, byte par)
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
messageProcessor.Process($"omnilink/message{id}/command", payload);
SendCommandEventArgs expected = new SendCommandEventArgs()
{
Cmd = command,
Par = par,
Pr2 = id
};
Assert.AreEqual(expected, actual);
}
check(1, "show", enuUnitCommand.ShowMsgWBeep, 0);
check(1, "show_no_beep", enuUnitCommand.ShowMsgNoBeep, 1);
check(1, "show_no_beep_or_led", enuUnitCommand.ShowMsgNoBeep, 2);
check(1, "clear", enuUnitCommand.ClearMsg, 0);
check(2, "SHOW", enuUnitCommand.ShowMsgWBeep, 0);
}
[TestMethod]
public void LockCommand()
{
void check(ushort id, string payload, enuUnitCommand command)
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
messageProcessor.Process($"omnilink/lock{id}/command", payload);
SendCommandEventArgs expected = new SendCommandEventArgs()
{
Cmd = command,
Par = 0,
Pr2 = id
};
Assert.AreEqual(expected, actual);
}
check(1, "lock", enuUnitCommand.Lock);
check(1, "unlock", enuUnitCommand.Unlock);
// Check all locks
check(0, "lock", enuUnitCommand.Lock);
// Check case insensitivity
check(2, "LOCK", enuUnitCommand.Lock);
}
[TestMethod]
public void AudioCommand()
{
void check(ushort id, string payload, enuUnitCommand command, int value)
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
messageProcessor.Process($"omnilink/audio{id}/command", payload);
SendCommandEventArgs expected = new SendCommandEventArgs()
{
Cmd = command,
Par = (byte)value,
Pr2 = id
};
Assert.AreEqual(expected, actual);
}
check(1, "ON", enuUnitCommand.AudioZone, 1);
check(1, "OFF", enuUnitCommand.AudioZone, 0);
check(2, "on", enuUnitCommand.AudioZone, 1);
}
[TestMethod]
public void AudioMuteCommand()
{
void check(ushort id, string payload, enuUnitCommand command, int value)
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
messageProcessor.Process($"omnilink/audio{id}/mute_command", payload);
SendCommandEventArgs expected = new SendCommandEventArgs()
{
Cmd = command,
Par = (byte)value,
Pr2 = id
};
Assert.AreEqual(expected, actual);
}
check(1, "ON", enuUnitCommand.AudioZone, 3);
check(1, "OFF", enuUnitCommand.AudioZone, 2);
Global.mqtt_audio_local_mute = true;
omniLink.Controller.AudioZones[2].Volume = 50;
check(2, "on", enuUnitCommand.AudioVolume, 0);
check(2, "off", enuUnitCommand.AudioVolume, 50);
omniLink.Controller.AudioZones[2].Volume = 0;
check(2, "on", enuUnitCommand.AudioVolume, 0);
check(2, "off", enuUnitCommand.AudioVolume, 10);
}
[TestMethod]
public void AudioSourceCommand()
{
void check(ushort id, string payload, enuUnitCommand command, int value)
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
messageProcessor.Process($"omnilink/audio{id}/source_command", payload);
SendCommandEventArgs expected = new SendCommandEventArgs()
{
Cmd = command,
Par = (byte)value,
Pr2 = id
};
Assert.AreEqual(expected, actual);
}
check(1, "Radio", enuUnitCommand.AudioSource, 1);
check(1, "Streaming", enuUnitCommand.AudioSource, 2);
check(2, "TV", enuUnitCommand.AudioSource, 4);
}
[TestMethod]
public void AudioVolumeCommand()
{
void check(ushort id, string payload, enuUnitCommand command, int value)
{
SendCommandEventArgs actual = null;
omniLink.OnSendCommand += (sender, e) => { actual = e; };
messageProcessor.Process($"omnilink/audio{id}/volume_command", payload);
SendCommandEventArgs expected = new SendCommandEventArgs()
{
Cmd = command,
Par = (byte)value,
Pr2 = id
};
Assert.AreEqual(expected, actual);
}
check(1, "100", enuUnitCommand.AudioVolume, 100);
check(1, "75", enuUnitCommand.AudioVolume, 75);
check(2, "0", enuUnitCommand.AudioVolume, 0);
Global.mqtt_audio_volume_media_player = true;
check(2, "1", enuUnitCommand.AudioVolume, 100);
check(2, "0.75", enuUnitCommand.AudioVolume, 75);
check(2, "0", enuUnitCommand.AudioVolume, 0);
}
}
}

View File

@ -0,0 +1,33 @@
using HAI_Shared;
using OmniLinkBridge.OmniLink;
using Serilog;
using System;
using System.Reflection;
namespace OmniLinkBridgeTest.Mock
{
class MockOmniLinkII : IOmniLinkII
{
private static readonly ILogger log = Log.Logger.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
public clsHAC Controller { get; private set; }
public event EventHandler<SendCommandEventArgs> OnSendCommand;
public MockOmniLinkII()
{
Controller = new clsHAC
{
Model = enuModel.OMNI_PRO_II,
TempFormat = enuTempFormat.Fahrenheit
};
}
public bool SendCommand(enuUnitCommand Cmd, byte Par, ushort Pr2)
{
log.Verbose("Sending: {command}, Par1: {par1}, Par2: {par2}", Cmd, Par, Pr2);
OnSendCommand?.Invoke(null, new SendCommandEventArgs() { Cmd = Cmd, Par = Par, Pr2 = Pr2 });
return true;
}
}
}

View File

@ -0,0 +1,39 @@
using HAI_Shared;
using System;
namespace OmniLinkBridgeTest.Mock
{
public class SendCommandEventArgs : EventArgs
{
public enuUnitCommand Cmd;
public byte Par;
public ushort Pr2;
public SendCommandEventArgs()
{
}
public SendCommandEventArgs(enuUnitCommand cmd, byte par, ushort pr2)
{
Cmd = cmd;
Par = par;
Pr2 = pr2;
}
public override bool Equals(object other)
{
if (!(other is SendCommandEventArgs toCompareWith))
return false;
return Cmd == toCompareWith.Cmd &&
Par == toCompareWith.Par &&
Pr2 == toCompareWith.Pr2;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}

View File

@ -1,8 +1,7 @@
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OmniLinkBridge;
using OmniLinkBridge.Notifications;
using System.Net.Mail;
namespace OmniLinkBridgeTest
{
@ -12,6 +11,16 @@ namespace OmniLinkBridgeTest
[TestMethod]
public void SendNotification()
{
// This is an integration test
Global.mail_server = "localhost";
Global.mail_tls = false;
Global.mail_port = 25;
Global.mail_from = new MailAddress("OmniLinkBridge@localhost");
Global.mail_to = new MailAddress[]
{
new MailAddress("mailbox@localhost")
};
Notification.Notify("Title", "Description");
}
}

View File

@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>OmniLinkBridgeTest</RootNamespace>
<AssemblyName>OmniLinkBridgeTest</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
@ -29,6 +29,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
@ -37,23 +38,31 @@
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<LangVersion>8.0</LangVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="HAI.Controller, Version=3.11.4.17, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\OmniLinkBridge\HAI.Controller.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="AssemblyTestHarness.cs" />
<Compile Include="ExtensionTest.cs" />
<Compile Include="Mock\MockOmniLinkII.cs" />
<Compile Include="Mock\SendCommandEventArgs.cs" />
<Compile Include="MQTTTest.cs" />
<Compile Include="SettingsTest.cs" />
<Compile Include="NotificationTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MSTest.TestAdapter">
<Version>1.3.2</Version>
<Version>2.2.8</Version>
</PackageReference>
<PackageReference Include="MSTest.TestFramework">
<Version>1.3.2</Version>
<Version>2.2.8</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>

View File

@ -2,12 +2,12 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("OmniLinkBridgeTest")]
[assembly: AssemblyTitle("OmniLink Bridge Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Excalibur Partners, LLC")]
[assembly: AssemblyProduct("OmniLinkBridgeTest")]
[assembly: AssemblyCopyright("Copyright © Excalibur Partners, LLC 2018")]
[assembly: AssemblyCopyright("Copyright © Excalibur Partners, LLC 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

View File

@ -0,0 +1,326 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OmniLinkBridge;
using OmniLinkBridge.MQTT.HomeAssistant;
using System;
using System.Collections.Generic;
using ha = OmniLinkBridge.MQTT.HomeAssistant;
namespace OmniLinkBridgeTest
{
[TestClass]
public class SettingsTest
{
private string[] RequiredSettings()
{
return new string[]
{
"controller_address = 1.1.1.1",
"controller_port = 4369",
"controller_key1 = 00-00-00-00-00-00-00-01",
"controller_key2 = 00-00-00-00-00-00-00-02",
};
}
[TestMethod]
public void TestControllerSettings()
{
Assert.ThrowsException<Exception>(() => Settings.LoadSettings(new string[]
{
"controller_address="
}));
List<string> lines = new List<string>(RequiredSettings());
lines.AddRange(new string[]
{
"controller_name = MyController"
});
Settings.LoadSettings(lines.ToArray());
Assert.AreEqual("1.1.1.1", Global.controller_address);
Assert.AreEqual(4369, Global.controller_port);
Assert.AreEqual("0000000000000001", Global.controller_key1);
Assert.AreEqual("0000000000000002", Global.controller_key2);
Assert.AreEqual("MyController", Global.controller_name);
}
[TestMethod]
public void TestTimeSyncSettings()
{
// Default should be false
Settings.LoadSettings(RequiredSettings());
Assert.AreEqual(false, Global.mqtt_enabled);
// Test minimal settings
List<string> lines = new List<string>(RequiredSettings());
lines.AddRange(new string[]
{
"time_sync = yes",
"time_interval = 60",
"time_drift = 10"
});
Settings.LoadSettings(lines.ToArray());
Assert.AreEqual(true, Global.time_sync);
Assert.AreEqual(60, Global.time_interval);
Assert.AreEqual(10, Global.time_drift);
}
[TestMethod]
public void TestVerboseSettings()
{
// Default should be false
Settings.LoadSettings(RequiredSettings());
Assert.AreEqual(false, Global.verbose_unhandled);
// Check each setting correctly sets
foreach (string setting in new string[] {
"verbose_unhandled",
"verbose_event",
"verbose_area",
"verbose_zone",
"verbose_thermostat_timer",
"verbose_thermostat",
"verbose_unit",
"verbose_message",
"verbose_lock"
})
{
List<string> lines = new List<string>(RequiredSettings())
{
$"{setting} = yes"
};
Settings.LoadSettings(lines.ToArray());
Assert.AreEqual(true, Global.GetValue(setting));
}
}
[TestMethod]
public void TestWebAPISettings()
{
// Default should be false
Settings.LoadSettings(RequiredSettings());
Assert.AreEqual(false, Global.mqtt_enabled);
// Test minimal settings
List<string> lines = new List<string>(RequiredSettings());
lines.AddRange(new string[]
{
"webapi_enabled = yes",
"webapi_port = 8000",
"webapi_override_zone = id=20;device_type=motion"
});
Settings.LoadSettings(lines.ToArray());
Assert.AreEqual(true, Global.webapi_enabled);
Assert.AreEqual(8000, Global.webapi_port);
Dictionary<int, OmniLinkBridge.WebAPI.OverrideZone> override_zone = new Dictionary<int, OmniLinkBridge.WebAPI.OverrideZone>()
{
{ 20, new OmniLinkBridge.WebAPI.OverrideZone { device_type = OmniLinkBridge.WebAPI.DeviceType.motion }}
};
Assert.AreEqual(override_zone.Count, Global.webapi_override_zone.Count);
foreach (KeyValuePair<int, OmniLinkBridge.WebAPI.OverrideZone> pair in override_zone)
{
Global.webapi_override_zone.TryGetValue(pair.Key, out OmniLinkBridge.WebAPI.OverrideZone value);
Assert.AreEqual(override_zone[pair.Key].device_type, value.device_type);
}
}
[TestMethod]
public void TestMQTTSettings()
{
// Default should be false
Settings.LoadSettings(RequiredSettings());
Assert.AreEqual(false, Global.mqtt_enabled);
// Test minimal settings
List<string> lines = new List<string>(RequiredSettings());
lines.AddRange(new string[]
{
"mqtt_enabled = yes",
"mqtt_server = localhost",
"mqtt_port = 1883"
});
Settings.LoadSettings(lines.ToArray());
Assert.AreEqual(true, Global.mqtt_enabled);
Assert.AreEqual("localhost", Global.mqtt_server);
Assert.AreEqual(1883, Global.mqtt_port);
Assert.AreEqual("omnilink", Global.mqtt_prefix);
Assert.AreEqual("homeassistant", Global.mqtt_discovery_prefix);
Assert.AreEqual(string.Empty, Global.mqtt_discovery_name_prefix);
// Test additional settings
lines.AddRange(new string[]
{
"mqtt_username = myuser",
"mqtt_password = mypass",
"mqtt_prefix = myprefix",
"mqtt_discovery_prefix = mydiscoveryprefix",
"mqtt_discovery_name_prefix = mynameprefix",
"mqtt_discovery_ignore_zones = 1,2-3,4",
"mqtt_discovery_ignore_units = 2-5,7",
"mqtt_discovery_override_area = id=1",
"mqtt_discovery_override_area = id=2;code_arm=true;code_disarm=true;arm_home=false;arm_away=false;arm_night=false;arm_vacation=false",
"mqtt_discovery_override_zone = id=5;device_class=garage_door",
"mqtt_discovery_override_zone = id=7;device_class=motion",
"mqtt_discovery_override_unit = id=1;type=switch",
"mqtt_discovery_override_unit = id=395;type=light",
});
Settings.LoadSettings(lines.ToArray());
Assert.AreEqual("myuser", Global.mqtt_username);
Assert.AreEqual("mypass", Global.mqtt_password);
Assert.AreEqual("myprefix", Global.mqtt_prefix);
Assert.AreEqual("mydiscoveryprefix", Global.mqtt_discovery_prefix);
Assert.AreEqual("mynameprefix ", Global.mqtt_discovery_name_prefix);
Assert.IsTrue(Global.mqtt_discovery_ignore_zones.SetEquals(new int[] { 1, 2, 3, 4 }));
Assert.IsTrue(Global.mqtt_discovery_ignore_units.SetEquals(new int[] { 2, 3, 4, 5, 7 }));
Dictionary<int, OmniLinkBridge.MQTT.OverrideArea> override_area = new Dictionary<int, OmniLinkBridge.MQTT.OverrideArea>()
{
{ 1, new OmniLinkBridge.MQTT.OverrideArea { }},
{ 2, new OmniLinkBridge.MQTT.OverrideArea { code_arm = true, code_disarm = true,
arm_home = false, arm_away = false, arm_night = false, arm_vacation = false }},
};
Assert.AreEqual(override_area.Count, Global.mqtt_discovery_override_area.Count);
foreach (KeyValuePair<int, OmniLinkBridge.MQTT.OverrideArea> pair in override_area)
{
Global.mqtt_discovery_override_area.TryGetValue(pair.Key, out OmniLinkBridge.MQTT.OverrideArea value);
Assert.AreEqual(override_area[pair.Key].code_arm, value.code_arm);
Assert.AreEqual(override_area[pair.Key].code_disarm, value.code_disarm);
Assert.AreEqual(override_area[pair.Key].arm_home, value.arm_home);
Assert.AreEqual(override_area[pair.Key].arm_away, value.arm_away);
Assert.AreEqual(override_area[pair.Key].arm_night, value.arm_night);
Assert.AreEqual(override_area[pair.Key].arm_vacation, value.arm_vacation);
}
Dictionary<int, OmniLinkBridge.MQTT.OverrideZone> override_zone = new Dictionary<int, OmniLinkBridge.MQTT.OverrideZone>()
{
{ 5, new OmniLinkBridge.MQTT.OverrideZone { device_class = ha.BinarySensor.DeviceClass.garage_door }},
{ 7, new OmniLinkBridge.MQTT.OverrideZone { device_class = ha.BinarySensor.DeviceClass.motion }}
};
Assert.AreEqual(override_zone.Count, Global.mqtt_discovery_override_zone.Count);
foreach (KeyValuePair<int, OmniLinkBridge.MQTT.OverrideZone> pair in override_zone)
{
Global.mqtt_discovery_override_zone.TryGetValue(pair.Key, out OmniLinkBridge.MQTT.OverrideZone value);
Assert.AreEqual(override_zone[pair.Key].device_class, value.device_class);
}
Dictionary<int, OmniLinkBridge.MQTT.OverrideUnit> override_unit = new Dictionary<int, OmniLinkBridge.MQTT.OverrideUnit>()
{
{ 1, new OmniLinkBridge.MQTT.OverrideUnit { type = OmniLinkBridge.MQTT.UnitType.@switch }},
{ 395, new OmniLinkBridge.MQTT.OverrideUnit { type = OmniLinkBridge.MQTT.UnitType.light }}
};
Assert.AreEqual(override_unit.Count, Global.mqtt_discovery_override_unit.Count);
foreach (KeyValuePair<int, OmniLinkBridge.MQTT.OverrideUnit> pair in override_unit)
{
Global.mqtt_discovery_override_unit.TryGetValue(pair.Key, out OmniLinkBridge.MQTT.OverrideUnit value);
Assert.AreEqual(override_unit[pair.Key].type, value.type);
}
Assert.AreEqual(Global.mqtt_discovery_button_type, typeof(Switch));
// Test additional settings
lines.AddRange(new string[]
{
"mqtt_discovery_button_type = button"
});
Settings.LoadSettings(lines.ToArray());
Assert.AreEqual(Global.mqtt_discovery_button_type, typeof(Button));
}
[TestMethod]
public void TestNotifySettings()
{
// Default should be false
Settings.LoadSettings(RequiredSettings());
Assert.AreEqual(false, Global.verbose_unhandled);
// Check each setting correctly sets
foreach (string setting in new string[] {
"notify_area",
"notify_message"
})
{
List<string> lines = new List<string>(RequiredSettings())
{
$"{setting} = yes"
};
Settings.LoadSettings(lines.ToArray());
Assert.AreEqual(true, Global.GetValue(setting));
}
}
[TestMethod]
public void TestMailSettings()
{
// Default should be null
Settings.LoadSettings(RequiredSettings());
Assert.AreEqual(null, Global.mail_server);
// Test minimal settings
List<string> lines = new List<string>(RequiredSettings());
lines.AddRange(new string[]
{
"mail_server = localhost",
"mail_port = 25",
"mail_from = from@localhost",
"mail_to = to1@localhost",
"mail_to = to2@localhost"
});
Settings.LoadSettings(lines.ToArray());
Assert.AreEqual("localhost", Global.mail_server);
Assert.AreEqual(false, Global.mail_tls);
Assert.AreEqual(25, Global.mail_port);
Assert.AreEqual("from@localhost", Global.mail_from.Address);
Assert.AreEqual(2, Global.mail_to.Length);
Assert.AreEqual("to1@localhost", Global.mail_to[0].Address);
Assert.AreEqual("to2@localhost", Global.mail_to[1].Address);
// Test additional settings
lines.AddRange(new string[]
{
"mail_tls = yes",
"mail_username = myuser",
"mail_password = mypass"
});
Settings.LoadSettings(lines.ToArray());
Assert.AreEqual(true, Global.mail_tls);
Assert.AreEqual("myuser", Global.mail_username);
Assert.AreEqual("mypass", Global.mail_password);
}
[TestMethod]
public void TestProwlSettings()
{
// Test minimal settings
List<string> lines = new List<string>(RequiredSettings());
lines.AddRange(new string[]
{
"prowl_key = mykey1",
"prowl_key = mykey2",
});
Settings.LoadSettings(lines.ToArray());
Assert.AreEqual("mykey1", Global.prowl_key[0]);
Assert.AreEqual("mykey2", Global.prowl_key[1]);
}
[TestMethod]
public void TestPushoverSettings()
{
// Test minimal settings
List<string> lines = new List<string>(RequiredSettings());
lines.AddRange(new string[]
{
"pushover_token = mytoken",
"pushover_user = myuser1",
"pushover_user = myuser2",
});
Settings.LoadSettings(lines.ToArray());
Assert.AreEqual("mytoken", Global.pushover_token);
Assert.AreEqual("myuser1", Global.pushover_user[0]);
Assert.AreEqual("myuser2", Global.pushover_user[1]);
}
}
}

467
README.md
View File

@ -1,96 +1,230 @@
# OmniLink Bridge
Provides time sync, logging, web service API, and MQTT bridge for HAI/Leviton OmniPro II controllers
Provides MQTT bridge, web service API, time sync, and logging for [HAI/Leviton OmniPro II controllers](https://www.leviton.com/en/products/brands/omni-security-automation). Provides integration with [Samsung SmartThings via web service API](https://github.com/excaliburpartners/SmartThings-OmniPro) and [Home Assistant via MQTT](https://www.home-assistant.io/components/mqtt/).
Please note that OmniLink Bridge is not in active development. The MQTT and Home Assistant integrations are in maintenance mode. The SmartThings Web API and MySQL logging are deprecated and not feature consistent with MQTT.
## Download
You can download the [binary here](http://www.excalibur-partners.com/downloads/OmniLinkBridge_1_1_1.zip) or use docker to build an image from git.
You can use docker to build an image from git or download the [binary here](https://github.com/excaliburpartners/OmniLinkBridge/releases/latest/download/OmniLinkBridge.zip). You can also install it as a [Home Assistant Add-on](https://github.com/excaliburpartners/hassio-addons).
## Requirements
- .NET Framework 4.5.2 (or Mono equivalent)
- [Docker](https://www.docker.com/)
- .NET Framework 4.7.2 (or Mono equivalent)
## Operation
- Area, Messages, Units, and Zones are logged to mySQL when status changes
- Thermostats are logged to mySQL once per minute
- If no notifications are received within 4 minutes a request is issued
- After 5 minutes of no updates a warning will be logged and mySQL will not be updated
- If the temp is 0 a warning will be logged and mySQL will not be updated
- Controller time is checked and compared to the local computer time disregarding time zones
OmniLink Bridge is divided into the following modules and configurable settings. Configuration settings can also be set as environment variables by using their name in uppercase. Refer to [OmniLinkBridge.ini](OmniLinkBridge/OmniLinkBridge.ini) for specifics.
## Notifications
- Supports email, prowl, and pushover
- Always sent for area alarms and critical system events
- Optionally enable for area status changes and console messages
- OmniLinkII: controller_
- Maintains connection to the OmniLink controller
- Thermostats
- If no status update has been received after 4 minutes a request is issued
- A status update containing a temperature of 0 marks the thermostat offline
- This can occur when a ZigBee thermostat has lost communication
- Time Sync: time_
- Controller time is checked and compared to the local computer time disregarding time zones
- MQTT: mqtt_
- Maintains connection to the MQTT broker
- Publishes discovery topics for [Home Assistant](https://www.home-assistant.io/components/mqtt/) to auto configure devices
- Publishes topics for status received from the OmniLinkII module
- Subscribes to command topics and sends commands to the OmniLinkII module
- Web API: webapi_
- Provides integration with [Samsung SmartThings](https://github.com/excaliburpartners/SmartThings-OmniPro)
- Allows an application to subscribe to receive POST notifications status updates are received from the OmniLinkII module
- On failure to POST to callback URL subscription is removed
- Recommended for application to send subscribe requests every few minutes
- Requests to GET endpoints return status from the OmniLinkII module
- Requests to POST endpoints send commands to the OmniLinkII module
- Logger
- Console output: verbose_
- Enabled by default
- Thermostats (verbose_thermostat_timer)
- After 5 minutes of no status updates a warning will be logged
- When a current temperature of 0 is received a warning will be logged
- MySQL logging: mysql_
- Thermostats are logged every minute and when an event is received
- Push notifications: notify_
- Always sent for area alarms and critical system events
- Optionally enable for area status changes and console messages
- Email: mail_
- Prowl: prowl_
- Pushover: pushover_
## Docker Hub Quickstart
Quickly get started with console logging by specifying the controller address and encryption keys.
```
docker run --name="omnilink-bridge" \
-v /etc/localtime:/etc/localtime:ro \
-e CONTROLLER_ADDRESS='' \
-e CONTROLLER_KEY1='00-00-00-00-00-00-00-00' \
-e CONTROLLER_KEY2='00-00-00-00-00-00-00-00' \
--net=host excaliburpartners/omnilink-bridge
```
Or start in the background with time sync and MQTT modules enabled.
```
docker run -d --name="omnilink-bridge" --restart always \
-v /etc/localtime:/etc/localtime:ro \
-e CONTROLLER_ADDRESS='' \
-e CONTROLLER_KEY1='00-00-00-00-00-00-00-00' \
-e CONTROLLER_KEY2='00-00-00-00-00-00-00-00' \
-e TIME_SYNC='yes' \
-e MQTT_ENABLED='yes' \
-e MQTT_SERVER='' \
-e MQTT_USERNAME='' \
-e MQTT_PASSWORD='' \
--net=host excaliburpartners/omnilink-bridge
```
## Docker Hub with Configuration File
1. Configure at a minimum the controller IP and encryptions keys.
```
mkdir /opt/omnilink-bridge
curl https://raw.githubusercontent.com/excaliburpartners/OmniLinkBridge/master/OmniLinkBridge/OmniLinkBridge.ini -o /opt/omnilink-bridge/OmniLinkBridge.ini
vim /opt/omnilink-bridge/OmniLinkBridge.ini
```
2. Start docker container
```
docker run -d --name="omnilink-bridge" -v /opt/omnilink-bridge:/config -v /etc/localtime:/etc/localtime:ro --net=host --restart always excaliburpartners/omnilink-bridge
```
3. Verify connectivity by looking at logs
```
docker logs omnilink-bridge
```
## Docker for Developers
1. Clone git repo and build docker image
```
git clone https://github.com/excaliburpartners/OmniLinkBridge.git
cd OmniLinkBridge
docker build --tag="omnilink-bridge" .
```
2. Configure at a minimum the controller IP and encryptions keys. The web service port must be 8000 unless the Dockerfile is changed.
```
mkdir /opt/omnilink-bridge
cp OmniLinkBridge/OmniLinkBridge.ini /opt/omnilink-bridge
vim /opt/omnilink-bridge/OmniLinkBridge.ini
```
3. Start docker container
```
docker run -d --name="omnilink-bridge" -v /opt/omnilink-bridge:/config -v /etc/localtime:/etc/localtime:ro --net=host --restart always omnilink-bridge
```
4. Verify connectivity by looking at logs
```
docker logs omnilink-bridge
```
## Installation Windows
1. Copy files to your desired location like C:\OmniLinkBridge
2. Edit OmniLinkBridge.ini and define at a minimum the controller IP and encryptions keys
3. Run OmniLinkBridge.exe to verify connectivity
3. Run OmniLinkBridge.exe from the command prompt to verify connectivity
4. Add Windows service
- sc create OmniLinkBridge binpath=C:\OmniLinkBridge\OmniLinkBridge.exe
```
sc create OmniLinkBridge binpath=C:\OmniLinkBridge\OmniLinkBridge.exe
```
5. Start service
- net start OmniLinkBridge
```
net start OmniLinkBridge
```
## Installation Linux
1. Copy files to your desired location like /opt/OmniLinkBridge
2. Configure at a minimum the controller IP and encryptions keys
- vim OmniLinkBridge.ini
```
vim OmniLinkBridge.ini
```
3. Run as interactive to verify connectivity
- mono OmniLinkBridge.exe -i
```
mono OmniLinkBridge.exe -i
```
4. Add systemd file and configure paths
- cp omnilinkbridge.service /etc/systemd/system/
- vim /etc/systemd/system/omnilinkbridge.service
- systemctl daemon-reload
```
cp omnilinkbridge.service /etc/systemd/system/
vim /etc/systemd/system/omnilinkbridge.service
systemctl daemon-reload
```
5. Enable at boot and start service
- systemctl enable omnilinkbridge.service
- systemctl start omnilinkbridge.service
## Docker
1. Clone git repo and build docker image
- git clone https://github.com/excaliburpartners/OmniLinkBridge.git
- cd OmniLinkBridge
- docker build --tag="omnilink-bridge" .
2. Configure at a minimum the controller IP and encryptions keys. The web service port must be 8000 unless the Dockerfile is changed.
- mkdir /opt/omnilink-bridge
- cp OmniLinkBridge/OmniLinkBridge.ini /opt/omnilink-bridge
- vim /opt/omnilink-bridge/OmniLinkBridge.ini
3. Start docker container
- docker run -d --name="omnilink-bridge" -v /opt/omnilink-bridge:/config --net=host --restart unless-stopped omnilink-bridge
4. Verify connectivity by looking at logs
- docker container logs omnilink-bridge
## MySQL Setup
You will want to install the MySQL Community Server, Workbench, and ODBC Connector. The Workbench software provides a graphical interface to administer the MySQL server. The OmniLink Bridge uses ODBC to communicate with the database. The MySQL ODBC Connector library is needed for Windows ODBC to communicate with MySQL.
http://dev.mysql.com/downloads/mysql/
http://dev.mysql.com/downloads/tools/workbench/
http://dev.mysql.com/downloads/connector/odbc/
At this point we need to open MySQL Workbench to create the database (called a schema in the Workbench GUI) for OmniLinkBridge to use.
1. After opening the program double-click on "Local instance MySQL" and enter the password you set in the wizard.
2. On the toolbar click the "Create a new schema" button, provide a name, and click apply.
3. On the left side right-click on the schema you created and click "Set as default schema".
4. In the middle section under Query1 click the open file icon and select the OmniLinkBridge.sql file.
5. Click the Execute lighting bolt to run the query, which will create the tables.
Lastly in OmniLinkBridge.ini set mysql_connection. This should get you up and running. The MySQL Workbench can also be used to view the data that OmniLink Bridge inserts into the tables.
mysql_connection = DRIVER={MySQL ODBC 8.0 Driver};SERVER=localhost;DATABASE=OmniLinkBridge;USER=root;PASSWORD=myPassword;OPTION=3;
## Web Service API
To test the API you can use your browser to view a page or PowerShell (see below) to change a value.
- http://localhost:8000/ListUnits
- http://localhost:8000/GetUnit?id=1
- Invoke-WebRequest -Uri "http://localhost:8000/SetUnit" -Method POST -ContentType "application/json" -Body (convertto-json -InputObject @{"id"=1;"value"=100}) -UseBasicParsing
```
systemctl enable omnilinkbridge.service
systemctl start omnilinkbridge.service
```
## MQTT
This module will also publish discovery topics for Home Assistant to auto configure devices.
```
SUB omnilink/status
string online, offline
SUB omnilink/areaX/state
string triggered, pending, armed_night, armed_home, armed_away, disarmed
SUB omnilink/model
string Controller model
PUB omnilink/areaX/command
string ARM_HOME, ARM_AWAY, ARM_NIGHT, DISARM, ARM_HOME_INSTANT, ARM_NIGHT_DELAY, ARM_VACATION
SUB omnilink/version
string Controller version
```
### System
```
SUB omnilink/system/phone/state
string secure, trouble
SUB omnilink/system/ac/state
string secure, trouble
SUB omnilink/system/battery/state
string secure, trouble
SUB omnilink/system/dcm/state
string secure, trouble
```
### Areas
```
SUB omnilink/areaX/name
string Area name
SUB omnilink/areaX/state
string triggered, arming, armed_night, armed_night_delay, armed_home, armed_home_instant, armed_away, armed_vacation, disarmed
SUB omnilink/areaX/basic_state
string triggered, arming, armed_night, armed_home, armed_away, armed_vacation, disarmed
SUB omnilink/areaX/json_state
string json
PUB omnilink/areaX/command
string arm_home, arm_away, arm_night, disarm, arm_home_instant, arm_night_delay, arm_vacation
note Use area 0 for all areas
note Optionally the user code number can be specified 'disarm,1'
note Optionally the security code can be be specified 'disarm,validate,1234'
PUB omnilink/areaX/alarm_command
string burglary, fire, auxiliary
```
### Zones
```
SUB omnilink/zoneX/name
string Zone name
SUB omnilink/zoneX/state
string secure, not_ready, trouble, armed, tripped, bypassed
SUB omnilink/zoneX/basic_state
string OFF, ON
SUB omnilink/zoneX/current_temperature (optional)
int Current temperature in degrees fahrenheit
SUB omnilink/zoneX/current_humidity (optional)
int Current relative humidity
PUB omnilink/zoneX/command
string bypass, restore
note Use zone 0 to restore all zones
note Optionally the user code number can be specified 'bypass,1'
```
### Units
```
SUB omnilink/unitX/name
string Unit name
SUB omnilink/unitX/state
PUB omnilink/unitX/command
@ -100,8 +234,25 @@ SUB omnilink/unitX/brightness_state
PUB omnilink/unitX/brightness_command
int Level from 0 to 100 percent
SUB omnilink/unitX/flag_state
PUB omnilink/unitX/flag_command
int Level from 0 to 255
SUB omnilink/unitX/scene_state
PUB omnilink/unitX/scene_command
string A-L
```
### Thermostats
```
SUB omnilink/thermostatX/name
string Thermostat name
SUB omnilink/thermostatX/status
string online, offline
SUB omnilink/thermostatX/current_operation
string idle, cool, heat
string idle, cooling, heating
SUB omnilink/thermostatX/current_temperature
int Current temperature in degrees fahrenheit
@ -123,70 +274,160 @@ int Setpoint in relative humidity
SUB omnilink/thermostatX/mode_state
PUB omnilink/thermostatX/mode_command
string auto, off, cool, heat, e_heat
SUB omnilink/thermostatX/mode_basic_state
string auto, off, cool, heat
SUB omnilink/thermostatX/fan_mode_state
PUB omnilink/thermostatX/fan_mode_command
string auto, on, cycle
SUB omnilink/thermostatX/hold_state
SUB omnilink/thermostatX/hold_state
string off, on, vacation
PUB omnilink/thermostatX/hold_command
string off, hold
string off, on
```
### Buttons
```
SUB omnilink/buttonX/name
string Button name
SUB omnilink/buttonX/state
string OFF
string OFF, ON
PUB omnilink/buttonX/command
string ON
```
## Change Log
Version 1.1.1 - 2018-10-18
- Added docker support
- Save subscriptions on change
### Messages
```
SUB omnilink/messageX/name
string Message name
Version 1.1.0 - 2018-10-13
- Renamed to OmniLinkBridge
- Restructured code to be event based with modules
- Added MQTT module for Home Assistant
- Added pushover notifications
- Added web service API subscriptions file to persist subscriptions
SUB omnilink/messageX/state
string off, displayed, displayed_not_acknowledged
Version 1.0.8 - 2016-11-28
- Fixed web service threading when multiple subscriptions exist
- Added additional zone types to contact and motion web service API
- Split command line options for config and log files
PUB omnilink/messageX/command
string show, show_no_beep, show_no_beep_or_led, clear
```
Version 1.0.7 - 2016-11-25
- Use previous area state when area is arming for web service API
- Add interactive command line option and use path separator for Mono compatibility
### Locks
```
SUB omnilink/lockX/name
string Lock name
Version 1.0.6 - 2016-11-20
- Added thermostat status and auxiliary temp to web service API
SUB omnilink/lockX/state
string locked, unlocked
Version 1.0.5 - 2016-11-15
- Added web service API for Samsung SmartThings integration
PUB omnilink/lockX/command
string lock, unlock
```
Version 1.0.4 - 2014-05-08
- Merged HAILogger.exe and HAILoggerService.exe
- Added immediate time sync after controller reconnect
### Audio Sources
```
SUB omnilink/sourceXX/name
string Audio source name
```
Version 1.0.3 - 2013-01-06
- Added setting for prowl console message notification
- Added settings for verbose output control
- Added setting to enable mySQL logging
- Added queue to mySQL logging
- Changed mySQL log time from mySQL NOW() to computer time
- Changed prowl notifications to be asynchronous
- Fixed crash when prowl api down
- Fixed setting yes/no parsing so no setting works
- Fixed incorrect thermostat out of date status warning
### Audio Zones
```
SUB omnilink/audioXX/name
string Audio zone name
Version 1.0.2 - 2012-12-30
- Fixed thermostat invalid mySQL logging error
SUB omnilink/audioXX/state
PUB omnilink/audioXX/command
string OFF, ON
note Use audio 0 to change all audio zones
Version 1.0.1 - 2012-12-30
- Added setting to adjust time sync interval
- Fixed crash when controller time not initially set
SUB omnilink/audioXX/mute_state
PUB omnilink/audioXX/mute_command
string OFF, ON
note Use audio 0 to change all audio zones
Version 1.0.0 - 2012-12-29
- Initial release
SUB omnilink/audioXX/source_state
PUB omnilink/audioXX/source_command
string Source name
note Refer to omnilink/sourceXX/name
SUB omnilink/audioXX/volume_state
PUB omnilink/audioXX/volume_command
int Level from 0 to 100 percent
double Level from 0.00 to 1.00 (mqtt_audio_volume_media_player = yes)
```
## Web API
To test the web service API you can use your browser to view a page or PowerShell (see below) to change a value.
```
Invoke-WebRequest -Uri "http://localhost:8000/SetUnit" -Method POST -ContentType "application/json" -Body (convertto-json -InputObject @{"id"=1;"value"=100}) -UseBasicParsing
```
### Subscription
```
POST /Subscribe
{ "callback": url }
Callback is a POST request with Type header added and json body identical to the related /Get
Type: area, contact, motion, water, smoke, co, temp, unit, thermostat
```
### Areas
```
GET /ListAreas
GET /GetArea?id=X
```
### Zones
```
GET /ListZonesContact
GET /ListZonesMotion
GET /ListZonesWater
GET /ListZonesSmoke
GET /ListZonesCO
GET /ListZonesTemp
GET /GetZone?id=X
```
### Units
```
GET /ListUnits
GET /GetZone?id=X
POST /SetUnit
POST /SetUnitKeypadPress
{ "id":X, "value":0-100 }
```
### Thermostats
```
GET /ListThermostats
GET /GetThermostat?id=X
POST /SetThermostatCoolSetpoint
POST /SetThermostatHeatSetpoint
POST /SetThermostatMode
POST /SetThermostatFanMode
POST /SetThermostatHold
{ "id":X, "value": }
int mode 0=off, 1=heat, 2=cool, 3=auto, 4=emergency heat
int fanmode 0=auto, 1=on, 2=circulate
int hold 0=off, 1=on
```
### Thermostats
```
GET /ListButtons
POST /PushButton
{ "id":X, "value":1 }
```
## MySQL
The [MySQL ODBC Connector](http://dev.mysql.com/downloads/connector/odbc/) is required for MySQL logging. The docker image comes with the MySQL ODBC connector installed. For Windows and Linux you will need to download and install it. The Home Assistant Add-on does not support MySQL logging.
Configure mysql_connection in OmniLinkBridge.ini. For Windows change DRIVER={MySQL} to name of the driver shown in the ODBC Data Source Administrator.
```
mysql_connection = DRIVER={MySQL};SERVER=localhost;DATABASE=OmniLinkBridge;USER=root;PASSWORD=myPassword;OPTION=3;
```
## Telemetry
OmniLink Bridge collects anonymous telemetry data to help improve the software. You can opt of telemetry by setting a TELEMETRY_OPTOUT environment variable to 1.