Compare commits

..

2 Commits

Author SHA1 Message Date
Gunnar Skjold
32fa2f5632 Merge branch 'master' into dev-v2.1.8 2022-10-06 17:30:49 +02:00
Gunnar Skjold
12be475b02 Reverted HA changes for 2.1.8 release 2022-10-06 17:29:01 +02:00
295 changed files with 12529 additions and 27308 deletions

2
.github/FUNDING.yml vendored
View File

@@ -1 +1 @@
custom: ["https://amsleser.no"]
custom: ["https://paypal.me/gskjold"]

View File

@@ -33,7 +33,6 @@ If applicable, add screenshots to help explain your problem.
**Relevant firmware information:**
- Version: [e.g. 2.1.0]
- MQTT: [yes/no]
- MQTT payload type: [e.g. JSON]
- HAN GPIO: [e.g. GPIO5]
- HAN baud and parity: [e.g. 2400 8E1]
- Temperature sensors [e.g. 3xDS18B20]

View File

@@ -1,8 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: Meter configuration
url: https://github.com/UtilitechAS/amsreader-firmware/wiki/Known-hardware-configurations
url: https://github.com/gskjold/AmsToMqttBridge/wiki/Known-hardware-configurations
about: Please check your meter configuration here first.
- name: Frequently asked questions
url: https://github.com/UtilitechAS/amsreader-firmware/wiki/FAQ
url: https://github.com/gskjold/AmsToMqttBridge/wiki/FAQ
about: Please check frequently asked questions first.

View File

@@ -20,7 +20,6 @@ A clear and concise description of what the problem is.
**Relevant firmware information:**
- Version: [e.g. 2.1.0]
- MQTT: [yes/no]
- MQTT payload type: [e.g. JSON]
- HAN GPIO: [e.g. GPIO5]
- HAN baud and parity: [e.g. 2400 8E1]
- Temperature sensors [e.g. 3xDS18B20]

View File

@@ -8,7 +8,6 @@ on:
- scripts/**
- web/**
- platformio.ini
- .github/workflows/**
branches:
- '*'
tags:
@@ -22,44 +21,26 @@ jobs:
steps:
- name: Check out code from repo
uses: actions/checkout@v4
- name: Inject secrets into ini file
run: |
sed -i 's/NO_AMS2MQTT_PRICE_KEY/AMS2MQTT_PRICE_KEY="${{secrets.AMS2MQTT_PRICE_KEY}}"/g' platformio.ini
sed -i 's/NO_AMS2MQTT_PRICE_AUTHENTICATION/AMS2MQTT_PRICE_AUTHENTICATION="${{secrets.AMS2MQTT_PRICE_AUTHENTICATION}}"/g' platformio.ini
sed -i 's/NO_ENERGY_SPEEDOMETER_USER/ENERGY_SPEEDOMETER_USER=\\"${{secrets.ENERGY_SPEEDOMETER_USER}}\\"/g' platformio.ini
sed -i 's/NO_ENERGY_SPEEDOMETER_PASS/ENERGY_SPEEDOMETER_PASS=\\"${{secrets.ENERGY_SPEEDOMETER_PASS}}\\"/g' platformio.ini
uses: actions/checkout@v1
- name: Cache Python dependencies
uses: actions/cache@v3
uses: actions/cache@v1
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('platformio.ini') }}
- name: Cache PlatformIO dependencies
uses: actions/cache@v3
uses: actions/cache@v1
with:
path: ~/.pio/libdeps
key: ${{ runner.os }}-pio-${{ hashFiles('platformio.ini') }}
- name: Set up Python 3.9
uses: actions/setup-python@v5
uses: actions/setup-python@v1
with:
python-version: 3.9
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio css_html_js_minify
- name: Set up node
uses: actions/setup-node@v4
with:
node-version: '16.x'
- name: Build with node
run: |
cd lib/SvelteUi/app
npm ci
npm run build
cd -
env:
CI: true
- name: PlatformIO lib install
run: pio pkg install
run: pio lib install
- name: PlatformIO run
run: pio run

View File

@@ -23,15 +23,6 @@ jobs:
env:
GITHUB_REF: ${{ github.ref }}
run: echo "GITHUB_TAG=$(echo ${GITHUB_REF##*/})" >> $GITHUB_ENV
- name: Inject secrets into ini file
run: |
sed -i 's/NO_AMS2MQTT_PRICE_KEY/AMS2MQTT_PRICE_KEY="${{secrets.AMS2MQTT_PRICE_KEY}}"/g' platformio.ini
sed -i 's/NO_AMS2MQTT_PRICE_AUTHENTICATION/AMS2MQTT_PRICE_AUTHENTICATION="${{secrets.AMS2MQTT_PRICE_AUTHENTICATION}}"/g' platformio.ini
sed -i 's/NO_AMS2MQTT_SC_KEY/AMS2MQTT_SC_KEY=\\"${{secrets.AMS2MQTT_SC_KEY}}\\"/g' platformio.ini
sed -i 's/NO_ENERGY_SPEEDOMETER_USER/ENERGY_SPEEDOMETER_USER=\\"${{secrets.ENERGY_SPEEDOMETER_USER}}\\"/g' platformio.ini
sed -i 's/NO_ENERGY_SPEEDOMETER_PASS/ENERGY_SPEEDOMETER_PASS=\\"${{secrets.ENERGY_SPEEDOMETER_PASS}}\\"/g' platformio.ini
- name: Cache Python dependencies
uses: actions/cache@v1
with:
@@ -50,23 +41,12 @@ jobs:
run: |
python -m pip install --upgrade pip
pip install -U platformio css_html_js_minify
- name: Set up node
uses: actions/setup-node@v1
with:
node-version: '16.x'
- name: Build with node
run: |
cd lib/SvelteUi/app
npm ci
npm run build
cd -
env:
CI: false
- name: PlatformIO lib install
run: pio lib install
- name: PlatformIO run
run: pio run
- name: Create zip files
run: /bin/sh scripts/mkzip.sh
- name: Create Release
id: create_release
uses: actions/create-release@v1.0.0
@@ -78,19 +58,6 @@ jobs:
draft: false
prerelease: false
- name: Build esp8266 firmware
run: pio run -e esp8266
- name: Create esp8266 zip file
run: /bin/sh scripts/esp8266/mkzip.sh
- name: Upload esp8266 binary to release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: .pio/build/esp8266/firmware.bin
asset_name: ams2mqtt-esp8266-${{ steps.release_tag.outputs.tag }}.bin
asset_content_type: application/octet-stream
- name: Upload esp8266 zip to release
uses: actions/upload-release-asset@v1
env:
@@ -100,20 +67,6 @@ jobs:
asset_path: esp8266.zip
asset_name: ams2mqtt-esp8266-${{ steps.release_tag.outputs.tag }}.zip
asset_content_type: application/zip
- name: Build esp32 firmware
run: pio run -e esp32
- name: Create esp32 zip file
run: /bin/sh scripts/esp32/mkzip.sh
- name: Upload esp32 binary to release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: .pio/build/esp32/firmware.bin
asset_name: ams2mqtt-esp32-${{ steps.release_tag.outputs.tag }}.bin
asset_content_type: application/octet-stream
- name: Upload esp32 zip to release
uses: actions/upload-release-asset@v1
env:
@@ -123,20 +76,6 @@ jobs:
asset_path: esp32.zip
asset_name: ams2mqtt-esp32-${{ steps.release_tag.outputs.tag }}.zip
asset_content_type: application/zip
- name: Build esp32s2 firmware
run: pio run -e esp32s2
- name: Create esp32s2 zip file
run: /bin/sh scripts/esp32s2/mkzip.sh
- name: Upload esp32s2 binary to release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: .pio/build/esp32s2/firmware.bin
asset_name: ams2mqtt-esp32s2-${{ steps.release_tag.outputs.tag }}.bin
asset_content_type: application/octet-stream
- name: Upload esp32s2 zip to release
uses: actions/upload-release-asset@v1
env:
@@ -147,33 +86,24 @@ jobs:
asset_name: ams2mqtt-esp32s2-${{ steps.release_tag.outputs.tag }}.zip
asset_content_type: application/zip
- name: Build esp32s3 firmware
run: pio run -e esp32s3
- name: Create esp32s3 zip file
run: /bin/sh scripts/esp32s3/mkzip.sh
- name: Upload esp32s3 binary to release
- name: Upload esp8266 binary to release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: .pio/build/esp32s3/firmware.bin
asset_name: ams2mqtt-esp32s3-${{ steps.release_tag.outputs.tag }}.bin
asset_path: .pio/build/esp8266/firmware.bin
asset_name: ams2mqtt-esp8266-${{ steps.release_tag.outputs.tag }}.bin
asset_content_type: application/octet-stream
- name: Upload esp32s3 zip to release
- name: Upload esp32 binary to release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: esp32s3.zip
asset_name: ams2mqtt-esp32s3-${{ steps.release_tag.outputs.tag }}.zip
asset_content_type: application/zip
- name: Build esp32solo firmware
run: pio run -e esp32solo
- name: Create esp32solo zip file
run: /bin/sh scripts/esp32solo/mkzip.sh
asset_path: .pio/build/esp32/firmware.bin
asset_name: ams2mqtt-esp32-${{ steps.release_tag.outputs.tag }}.bin
asset_content_type: application/octet-stream
- name: Upload esp32solo binary to release
uses: actions/upload-release-asset@v1
env:
@@ -183,35 +113,12 @@ jobs:
asset_path: .pio/build/esp32solo/firmware.bin
asset_name: ams2mqtt-esp32solo-${{ steps.release_tag.outputs.tag }}.bin
asset_content_type: application/octet-stream
- name: Upload esp32solo zip to release
- name: Upload esp32s2 binary to release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: esp32solo.zip
asset_name: ams2mqtt-esp32solo-${{ steps.release_tag.outputs.tag }}.zip
asset_content_type: application/zip
- name: Build esp32c3 firmware
run: pio run -e esp32c3
- name: Create esp32c3 zip file
run: /bin/sh scripts/esp32c3/mkzip.sh
- name: Upload esp32c3 binary to release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: .pio/build/esp32c3/firmware.bin
asset_name: ams2mqtt-esp32c3-${{ steps.release_tag.outputs.tag }}.bin
asset_path: .pio/build/esp32s2/firmware.bin
asset_name: ams2mqtt-esp32s2-${{ steps.release_tag.outputs.tag }}.bin
asset_content_type: application/octet-stream
- name: Upload esp32c3 zip to release
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: esp32c3.zip
asset_name: ams2mqtt-esp32c3-${{ steps.release_tag.outputs.tag }}.zip
asset_content_type: application/zip

View File

@@ -1,63 +0,0 @@
name: Test ESP8266
on:
workflow_dispatch:
jobs:
esp8266:
runs-on: esp8266
steps:
- uses: actions/checkout@v4
- name: Get commit hash
id: vars
run: echo "sha_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
- name: Check outputs
run: echo ${{ steps.vars.outputs.sha_short }}
- name: Inject secrets into ini file
run: |
sed -i 's/NO_AMS2MQTT_PRICE_KEY/AMS2MQTT_PRICE_KEY="${{secrets.AMS2MQTT_PRICE_KEY}}"/g' platformio.ini
sed -i 's/NO_AMS2MQTT_PRICE_AUTHENTICATION/AMS2MQTT_PRICE_AUTHENTICATION="${{secrets.AMS2MQTT_PRICE_AUTHENTICATION}}"/g' platformio.ini
sed -i 's/NO_ENERGY_SPEEDOMETER_USER/ENERGY_SPEEDOMETER_USER=\\"${{secrets.ENERGY_SPEEDOMETER_USER}}\\"/g' platformio.ini
sed -i 's/NO_ENERGY_SPEEDOMETER_PASS/ENERGY_SPEEDOMETER_PASS=\\"${{secrets.ENERGY_SPEEDOMETER_PASS}}\\"/g' platformio.ini
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -U platformio css_html_js_minify
- name: Set up node
uses: actions/setup-node@v4
with:
node-version: '16.x'
- name: Configure PlatformIO environment
run: |
echo "[platformio]
default_envs = dev8266
[env:dev8266]
platform = espressif8266@4.2.0
framework = arduino
board = esp12e
board_build.ldscript = eagle.flash.4m2m.ld
build_flags = \${common.build_flags}
lib_ldf_mode = off
lib_compat_mode = off
lib_deps = ESP8266WiFi, ESP8266mDNS, ESP8266WebServer, ESP8266HTTPClient, ESP8266httpUpdate, ESP8266SSDP, \${common.lib_deps}
lib_ignore = \${common.lib_ignore}
extra_scripts = \${common.extra_scripts}" > platformio-user.ini
- name: Build with node
run: |
cd lib/SvelteUi/app
npm ci
npm run build
cd -
env:
CI: true
- name: PlatformIO lib install
run: pio pkg update
- name: PlatformIO run
run: pio run -t upload --upload-port /dev/ttyUSB0
- name: Wait for device to come online
run: waitforhost 10.42.0.11 80
- name: Confirm version
run: curl -s http://10.42.0.11/sysinfo.json|jq -r .version | grep "${{ steps.vars.outputs.sha_short }}" || exit 1
- name: Running amsreader-test
run: amsreader-test 10.42.0.11

7
.gitignore vendored
View File

@@ -7,7 +7,7 @@
.vscode
.pio
platformio-user.ini
/lib/FirmwareVersion/src/generated_version.h
/src/version.h
/src/web/root
/src/AmsToMqttBridge.ino.cpp
/test
@@ -15,8 +15,3 @@ platformio-user.ini
/sdkconfig
/.tmp
/*.zip
node_modules
/gui/dist
/scripts/*dev
/src/KmpCommunicator.cpp
/src/KmpCommunicatorDefs.h

639
LICENSE
View File

@@ -1,44 +1,617 @@
Fair Source License, version 0.9
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2023 Utilitech AS
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.
Licensor: Utilitech AS
Preamble
Software: AMS reader
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
Use Limitation: 5 users
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
License Grant. Licensor hereby grants to each recipient of the
Software ("you") a non-exclusive, non-transferable, royalty-free and
fully-paid-up license, under all of the Licensor's copyright and
patent rights, to use, copy, distribute, prepare derivative works of,
publicly perform and display the Software, subject to the Use
Limitation and the conditions set forth below.
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.
Use Limitation. The license granted above allows use by up to the
number of users per entity set forth above (the "Use Limitation"). For
determining the number of users, "you" includes all affiliates,
meaning legal entities controlling, controlled by, or under common
control with you. If you exceed the Use Limitation, your use is
subject to payment of Licensor's then-current list price for licenses.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
Conditions. Redistribution in source code or other forms must include
a copy of this license document to be provided in a reasonable
manner. Any redistribution of the Software is only allowed subject to
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
Trademarks. This license does not grant you any right in the
trademarks, service marks, brand names or logos of Licensor.
The precise terms and conditions for copying, distribution and
modification follow.
DISCLAIMER. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OR
CONDITION, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. LICENSORS HEREBY DISCLAIM ALL LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE.
TERMS AND CONDITIONS
Termination. If you violate the terms of this license, your rights
will terminate automatically and will not be reinstated without the
prior written consent of Licensor. Any such termination will not
affect the right of others who may have received copies of the
Software from you.
0. Definitions.
"This License" refers to version 3 of the GNU Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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.

View File

@@ -1,12 +1,12 @@
# AMS Reader
# AMS MQTT Bridge
This code is designed to decode data from electric smart meters installed in many countries in Europe these days. The data is presented in a graphical web interface and can also send the data to a MQTT broker which makes it suitable for home automation project. Originally it was only designed to work with Norwegian meters, but has since been adapter to read any IEC-62056-7-5 or IEC-62056-21 compliant meters.
Later development have added Energy usage graph for both day and month, as well as future energy price. The code can run on any ESP8266 or ESP32 hardware which you can read more about in the [WiKi](https://github.com/UtilitechAS/amsreader-firmware/wiki). If you don't have the knowledge to set up a ESP device yourself, or you would like to support our work, please have a look at our shop at [amsleser.no](https://amsleser.no/).
Later development have added Energy usage graph for both day and month, as well as future energy price (Prices only available for ESP32). The code can run on any ESP8266 or ESP32 hardware which you can read more about in the [WiKi](https://github.com/gskjold/AmsToMqttBridge/wiki). If you don't have the knowledge to set up a ESP device yourself, have a look at the shop at [amsleser.no](https://amsleser.no/).
<img src="images/dashboard.png">
<img src="webui.png">
Go to the [WiKi](https://github.com/UtilitechAS/amsreader-firmware/wiki) for information on how to get your own device! And find the latest prebuilt firmware file at the [release section](https://github.com/UtilitechAS/amsreader-firmware/releases).
Go to the [WiKi](https://github.com/gskjold/AmsToMqttBridge/wiki) for information on how to get your own device! And find the latest prebuilt firmware file at the [release section](https://github.com/gskjold/AmsToMqttBridge/releases).
## Building this project with PlatformIO
To build this project, you need [PlatformIO](https://platformio.org/) installed.
@@ -18,12 +18,3 @@ It is recommended to use Visual Studio Code with the PlatformIO plugin for devel
[PlatformIO vscode plugin](https://platformio.org/install/ide?install=vscode)
For development purposes, copy the ```platformio-user.ini-example``` to ```platformio-user.ini``` and customize to your preference. The code will adapt to the platform and board set in your profile.
## Licensing
Initially, this project began as a hobby, consuming countless hours of our spare time. However, the time required to support this project has expanded beyond the scope of a hobby. As a result, we established Utilitech, a company dedicated to maintaining the software and hardware for this project as part of our regular work.
To ensure the sustainability of our venture, we have opted to license our software under the [Fair Source License] (https://fair.io). This approach allows the software to remain free for personal use, while also ensuring full transparency of our codes inner workings. It also prevents competitors from exploiting our work without contributing to the maintenance of the code or providing technical support to end users.
For more information, please refer to our [LICENSE](/LICENSE) file.
If your usage falls outside the scope of this license and you require a separate license, please contact us at [post@utilitech.no](mailto:post@utilitech.no) for further details.

Binary file not shown.

View File

@@ -42,4 +42,4 @@ DB
09 06 01 00 47 07 00 FF 12 00 54 02 02 0F FE 16 21
09 06 01 00 0D 07 00 FF 10 03 CF 02 02 0F FD 16 FF // Power factor
09 0C 31 37 38 32 31 30 30 31 35 31 36 35 // Meter ID
01 67
01 67

View File

@@ -1,33 +0,0 @@
7E
A0 76 CE FF 03 13 3C 02 E6 E7 00
DB
08 4C 47 5A 67 72 A9 A1 11
5E 30 00 21 80 F7 FE B8 07 C6
72 B1 90 AE AC 15 D0 AD 95 7B AC 13 7E 67 D8 A2
F0 43 51 3C 63 B6 A1 89 10 AE 9A 7E 55 4A 12 49
B9 6D EB A5 7B 57 03 69 9A BF 16 5E AD 2A 54 41
65 5E 79 C6 95 71 92 46 A2 3F 5B 63 0D 53 96 7D
42 52 1F A3 80 1C 00 E8 E3
A4 B3 9B 86 CB E5 2D 2C CA B0 E2 B7
AE 4D
7E
0f00057e41 // UI Frame header
0c07e60c0c010c232dff800000 // Date & time
020e // Structure with 14 items
1200ec // U1 = 236 V
1200ec // U2 = 236 V
1200ec // U3 = 236 V
120000 // I1 = 0.00 A
12002e // I2 = 0.46 A
12001a // I3 = 0.26 A
060000007d // Active import = 125 W
0600000000 // Active export = 0 W
0601a96ebd // Accumulated import = 27881.149 kWh
0600001dc3 // Accumulated export = 7.619 kWh
120190 // 400 ?
120003 // 3 ?
120120 // 288 ?
09083330313337313831 // Meter ID = 30137181

View File

@@ -1,34 +0,0 @@
02 12
09 10 49 53 4B 31 30 33 30 37 38 39 33 37 35 36 30 36 // str: ISK1030789375606 (device name)
09 08 31 36 38 32 30 30 30 35 // str: 16820005 (device id)
06 00 00 05 71 // active import
06 00 00 00 00 // active export
06 00 00 00 00 // reactive import
06 00 00 02 E2 // reactive export
12 09 4B // U1
12 09 4B // U2
12 08 F8 // U3
12 00 67 // I1
12 00 7D // I2
12 02 55 // I3
06 00 00 00 10 // L1 a+
06 00 00 00 33 // L2 a+
06 00 00 05 2D // L3 a+
06 00 00 00 00 // L1 a-
06 00 00 00 00 // L2 a-
06 00 00 00 00 // L3 a-
02 0C
09 10 49 53 4B 31 30 33 30 37 38 39 33 37 35 36 30 36
09 08 31 36 38 32 30 30 30 36
16 01 // Disconnect control
09 02 00 01 // Currently active energy tariff
06 00 00 CE 65 // 1.8.0 a+
06 00 00 35 19 // 1.8.1
06 00 00 99 4C // 1.8.2
06 00 02 B7 07 // 2.8.0 a-
06 00 01 33 17 // 2.8.1
06 00 01 83 F0 // 2.8.2
06 00 01 A5 6A // q+
06 00 00 A8 F5 // q-

View File

@@ -1 +1 @@
[See Hardware page in Wiki](https://github.com/UtilitechAS/amsreader-firmware/wiki)
[See Hardware page in Wiki](https://github.com/gskjold/AmsToMqttBridge/wiki)

View File

@@ -1,76 +0,0 @@
{
"board": {
"active_layer": 0,
"active_layer_preset": "",
"auto_track_width": true,
"hidden_nets": [],
"high_contrast_mode": 0,
"net_color_mode": 1,
"opacity": {
"pads": 1.0,
"tracks": 1.0,
"vias": 1.0,
"zones": 0.6
},
"ratsnest_display_mode": 0,
"selection_filter": {
"dimensions": true,
"footprints": true,
"graphics": true,
"keepouts": true,
"lockedItems": true,
"otherItems": true,
"pads": true,
"text": true,
"tracks": true,
"vias": true,
"zones": true
},
"visible_items": [
0,
1,
2,
3,
4,
5,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
32,
33,
34,
35,
36
],
"visible_layers": "fffffff_ffffffff",
"zone_display_mode": 0
},
"meta": {
"filename": "HAN_ESP_TSS721.kicad_prl",
"version": 3
},
"project": {
"files": []
}
}

View File

@@ -1,440 +0,0 @@
{
"board": {
"design_settings": {
"defaults": {
"board_outline_line_width": 0.15,
"copper_line_width": 0.19999999999999998,
"copper_text_italic": false,
"copper_text_size_h": 1.5,
"copper_text_size_v": 1.5,
"copper_text_thickness": 0.3,
"copper_text_upright": false,
"courtyard_line_width": 0.049999999999999996,
"dimension_precision": 4,
"dimension_units": 3,
"dimensions": {
"arrow_length": 1270000,
"extension_offset": 500000,
"keep_text_aligned": true,
"suppress_zeroes": false,
"text_position": 0,
"units_format": 1
},
"fab_line_width": 0.09999999999999999,
"fab_text_italic": false,
"fab_text_size_h": 1.0,
"fab_text_size_v": 1.0,
"fab_text_thickness": 0.15,
"fab_text_upright": false,
"other_line_width": 0.09999999999999999,
"other_text_italic": false,
"other_text_size_h": 1.0,
"other_text_size_v": 1.0,
"other_text_thickness": 0.15,
"other_text_upright": false,
"pads": {
"drill": 0.762,
"height": 1.524,
"width": 1.524
},
"silk_line_width": 0.15,
"silk_text_italic": false,
"silk_text_size_h": 1.0,
"silk_text_size_v": 1.0,
"silk_text_thickness": 0.15,
"silk_text_upright": false,
"zones": {
"45_degree_only": true,
"min_clearance": 0.508
}
},
"diff_pair_dimensions": [],
"drc_exclusions": [],
"meta": {
"filename": "board_design_settings.json",
"version": 2
},
"rule_severities": {
"annular_width": "error",
"clearance": "error",
"copper_edge_clearance": "error",
"courtyards_overlap": "error",
"diff_pair_gap_out_of_range": "error",
"diff_pair_uncoupled_length_too_long": "error",
"drill_out_of_range": "error",
"duplicate_footprints": "warning",
"extra_footprint": "warning",
"footprint_type_mismatch": "error",
"hole_clearance": "error",
"hole_near_hole": "error",
"invalid_outline": "error",
"item_on_disabled_layer": "error",
"items_not_allowed": "error",
"length_out_of_range": "error",
"malformed_courtyard": "error",
"microvia_drill_out_of_range": "error",
"missing_courtyard": "ignore",
"missing_footprint": "warning",
"net_conflict": "warning",
"npth_inside_courtyard": "ignore",
"padstack": "error",
"pth_inside_courtyard": "ignore",
"shorting_items": "error",
"silk_over_copper": "warning",
"silk_overlap": "warning",
"skew_out_of_range": "error",
"through_hole_pad_without_hole": "error",
"too_many_vias": "error",
"track_dangling": "warning",
"track_width": "error",
"tracks_crossing": "error",
"unconnected_items": "error",
"unresolved_variable": "error",
"via_dangling": "warning",
"zone_has_empty_net": "error",
"zones_intersect": "error"
},
"rules": {
"allow_blind_buried_vias": false,
"allow_microvias": false,
"max_error": 0.005,
"min_clearance": 0.0,
"min_copper_edge_clearance": 0.075,
"min_hole_clearance": 0.25,
"min_hole_to_hole": 0.25,
"min_microvia_diameter": 0.19999999999999998,
"min_microvia_drill": 0.09999999999999999,
"min_silk_clearance": 0.0,
"min_through_hole_diameter": 0.3,
"min_track_width": 0.19999999999999998,
"min_via_annular_width": 0.049999999999999996,
"min_via_diameter": 0.39999999999999997,
"use_height_for_length_calcs": true
},
"track_widths": [
0.0,
0.2,
0.4,
0.6,
1.0
],
"via_dimensions": [],
"zones_allow_external_fillets": false,
"zones_use_no_outline": true
},
"layer_presets": []
},
"boards": [],
"cvpcb": {
"equivalence_files": []
},
"erc": {
"erc_exclusions": [],
"meta": {
"version": 0
},
"pin_map": [
[
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
2
],
[
0,
2,
0,
1,
0,
0,
1,
0,
2,
2,
2,
2
],
[
0,
0,
0,
0,
0,
0,
1,
0,
1,
0,
1,
2
],
[
0,
1,
0,
0,
0,
0,
1,
1,
2,
1,
1,
2
],
[
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
2
],
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
2
],
[
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
2
],
[
0,
0,
0,
1,
0,
0,
1,
0,
0,
0,
0,
2
],
[
0,
2,
1,
2,
0,
0,
1,
0,
2,
2,
2,
2
],
[
0,
2,
0,
1,
0,
0,
1,
0,
2,
0,
0,
2
],
[
0,
2,
1,
1,
0,
0,
1,
0,
2,
0,
0,
2
],
[
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2
]
],
"rule_severities": {
"bus_definition_conflict": "error",
"bus_entry_needed": "error",
"bus_label_syntax": "error",
"bus_to_bus_conflict": "error",
"bus_to_net_conflict": "error",
"different_unit_footprint": "error",
"different_unit_net": "error",
"duplicate_reference": "error",
"duplicate_sheet_names": "error",
"extra_units": "error",
"global_label_dangling": "warning",
"hier_label_mismatch": "error",
"label_dangling": "error",
"lib_symbol_issues": "warning",
"multiple_net_names": "warning",
"net_not_bus_member": "warning",
"no_connect_connected": "warning",
"no_connect_dangling": "warning",
"pin_not_connected": "error",
"pin_not_driven": "error",
"pin_to_pin": "warning",
"power_pin_not_driven": "error",
"similar_labels": "warning",
"unannotated": "error",
"unit_value_mismatch": "error",
"unresolved_variable": "error",
"wire_dangling": "error"
}
},
"libraries": {
"pinned_footprint_libs": [],
"pinned_symbol_libs": []
},
"meta": {
"filename": "HAN_ESP_TSS721.kicad_pro",
"version": 1
},
"net_settings": {
"classes": [
{
"bus_width": 12.0,
"clearance": 0.2,
"diff_pair_gap": 0.25,
"diff_pair_via_gap": 0.25,
"diff_pair_width": 0.2,
"line_style": 0,
"microvia_diameter": 0.3,
"microvia_drill": 0.1,
"name": "Default",
"pcb_color": "rgba(0, 0, 0, 0.000)",
"schematic_color": "rgba(0, 0, 0, 0.000)",
"track_width": 0.25,
"via_diameter": 0.6,
"via_drill": 0.4,
"wire_width": 6.0
},
{
"bus_width": 12.0,
"clearance": 0.5,
"diff_pair_gap": 0.25,
"diff_pair_via_gap": 0.25,
"diff_pair_width": 0.2,
"line_style": 0,
"microvia_diameter": 0.5,
"microvia_drill": 0.2,
"name": "PWR",
"nets": [
"+3V3"
],
"pcb_color": "rgba(0, 0, 0, 0.000)",
"schematic_color": "rgba(0, 0, 0, 0.000)",
"track_width": 0.5,
"via_diameter": 0.8,
"via_drill": 0.6,
"wire_width": 6.0
}
],
"meta": {
"version": 2
},
"net_colors": null
},
"pcbnew": {
"last_paths": {
"gencad": "",
"idf": "",
"netlist": "",
"specctra_dsn": "",
"step": "",
"vrml": ""
},
"page_layout_descr_file": ""
},
"schematic": {
"annotate_start_num": 0,
"drawing": {
"default_line_thickness": 6.0,
"default_text_size": 50.0,
"field_names": [],
"intersheets_ref_own_page": false,
"intersheets_ref_prefix": "",
"intersheets_ref_short": false,
"intersheets_ref_show": false,
"intersheets_ref_suffix": "",
"junction_size_choice": 3,
"label_size_ratio": 0.25,
"pin_symbol_size": 0.0,
"text_offset_ratio": 0.08
},
"legacy_lib_dir": "",
"legacy_lib_list": [],
"meta": {
"version": 1
},
"net_format_name": "",
"ngspice": {
"fix_include_paths": true,
"fix_passive_vals": false,
"meta": {
"version": 0
},
"model_mode": 0,
"workbook_filename": ""
},
"page_layout_descr_file": "",
"plot_directory": "",
"spice_adjust_passive_values": false,
"spice_external_command": "spice \"%I\"",
"subpart_first_id": 65,
"subpart_id_separator": 0
},
"sheets": [],
"text_variables": {}
}

View File

@@ -1 +0,0 @@
0

View File

@@ -1,3 +0,0 @@
EESchema-DOCLIB Version 2.0
#
#End Doc Library

View File

@@ -1,21 +1,6 @@
EESchema-LIBRARY Version 2.4
#encoding utf-8
#
# +3.3V-power
#
DEF +3.3V-power #PWR 0 0 Y Y 1 F P
F0 "#PWR" 0 -150 50 H I C CNN
F1 "+3.3V-power" 0 140 50 H V C CNN
F2 "" 0 0 50 H I C CNN
F3 "" 0 0 50 H I C CNN
DRAW
P 2 0 1 0 -30 50 0 100 N
P 2 0 1 0 0 0 0 100 N
P 2 0 1 0 0 100 30 50 N
X +3V3 1 0 0 0 U 50 50 1 1 W N
ENDDRAW
ENDDEF
#
# CONN_01X08
#
DEF CONN_01X08 P 0 40 Y N 1 F N
@@ -50,23 +35,4 @@ X P8 8 -200 -350 150 R 50 50 1 1 P
ENDDRAW
ENDDEF
#
# Jumper-Device
#
DEF Jumper-Device JP 0 30 Y N 1 F N
F0 "JP" 0 150 50 H V C CNN
F1 "Jumper-Device" 0 -80 50 H V C CNN
F2 "" 0 0 50 H I C CNN
F3 "" 0 0 50 H I C CNN
$FPLIST
SolderJumper*
$ENDFPLIST
DRAW
C -100 0 35 0 1 0 N
A 0 -26 125 375 1422 0 1 0 N 99 50 -98 50
C 100 0 35 0 1 0 N
X 1 1 -300 0 165 R 50 50 0 1 P
X 2 2 300 0 165 L 50 50 0 1 P
ENDDRAW
ENDDEF
#
#End Library

View File

@@ -1,75 +0,0 @@
{
"board": {
"active_layer": 0,
"active_layer_preset": "",
"auto_track_width": true,
"hidden_nets": [],
"high_contrast_mode": 0,
"net_color_mode": 1,
"opacity": {
"pads": 1.0,
"tracks": 1.0,
"vias": 1.0,
"zones": 0.6
},
"ratsnest_display_mode": 0,
"selection_filter": {
"dimensions": true,
"footprints": true,
"graphics": true,
"keepouts": true,
"lockedItems": true,
"otherItems": true,
"pads": true,
"text": true,
"tracks": true,
"vias": true,
"zones": true
},
"visible_items": [
0,
1,
2,
3,
4,
5,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
32,
33,
34,
35,
36
],
"visible_layers": "fffffff_ffffffff",
"zone_display_mode": 0
},
"meta": {
"filename": "d1_mini_shield.kicad_prl",
"version": 3
},
"project": {
"files": []
}
}

View File

@@ -1,356 +0,0 @@
{
"board": {
"design_settings": {
"defaults": {
"board_outline_line_width": 0.15,
"copper_line_width": 0.2,
"copper_text_italic": false,
"copper_text_size_h": 1.5,
"copper_text_size_v": 1.5,
"copper_text_thickness": 0.3,
"copper_text_upright": true,
"courtyard_line_width": 0.05,
"other_line_width": 0.15,
"other_text_italic": false,
"other_text_size_h": 1.0,
"other_text_size_v": 1.0,
"other_text_thickness": 0.15,
"other_text_upright": true,
"silk_line_width": 0.15,
"silk_text_italic": false,
"silk_text_size_h": 1.0,
"silk_text_size_v": 1.0,
"silk_text_thickness": 0.15,
"silk_text_upright": true
},
"diff_pair_dimensions": [
{
"gap": 0.25,
"via_gap": 0.25,
"width": 0.2
}
],
"drc_exclusions": [],
"rule_severitieslegacy_courtyards_overlap": true,
"rule_severitieslegacy_no_courtyard_defined": false,
"rules": {
"allow_blind_buried_vias": false,
"allow_microvias": false,
"min_hole_to_hole": 0.25,
"min_microvia_diameter": 0.2,
"min_microvia_drill": 0.09999999999999999,
"min_through_hole_diameter": 0.3,
"min_track_width": 0.2,
"min_via_diameter": 0.4,
"solder_mask_clearance": 0.2,
"solder_mask_min_width": 0.0,
"solder_paste_clearance": 0.0,
"solder_paste_margin_ratio": -0.0
},
"track_widths": [
0.25,
0.5
],
"via_dimensions": [
{
"diameter": 0.6,
"drill": 0.4
}
]
},
"layer_presets": []
},
"boards": [],
"cvpcb": {
"equivalence_files": []
},
"erc": {
"erc_exclusions": [],
"meta": {
"version": 0
},
"pin_map": [
[
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
2
],
[
0,
2,
0,
1,
0,
0,
1,
0,
2,
2,
2,
2
],
[
0,
0,
0,
0,
0,
0,
1,
0,
1,
0,
1,
2
],
[
0,
1,
0,
0,
0,
0,
1,
1,
2,
1,
1,
2
],
[
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
2
],
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
2
],
[
1,
1,
1,
1,
1,
0,
1,
1,
1,
1,
1,
2
],
[
0,
0,
0,
1,
0,
0,
1,
0,
0,
0,
0,
2
],
[
0,
2,
1,
2,
0,
0,
1,
0,
2,
2,
2,
2
],
[
0,
2,
0,
1,
0,
0,
1,
0,
2,
0,
0,
2
],
[
0,
2,
1,
1,
0,
0,
1,
0,
2,
0,
0,
2
],
[
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2
]
],
"rule_severities": {
"bus_definition_conflict": "error",
"bus_entry_needed": "error",
"bus_label_syntax": "error",
"bus_to_bus_conflict": "error",
"bus_to_net_conflict": "error",
"different_unit_footprint": "error",
"different_unit_net": "error",
"duplicate_reference": "error",
"duplicate_sheet_names": "error",
"extra_units": "error",
"global_label_dangling": "warning",
"hier_label_mismatch": "error",
"label_dangling": "error",
"lib_symbol_issues": "warning",
"multiple_net_names": "warning",
"net_not_bus_member": "warning",
"no_connect_connected": "warning",
"no_connect_dangling": "warning",
"pin_not_connected": "error",
"pin_not_driven": "error",
"pin_to_pin": "warning",
"power_pin_not_driven": "error",
"similar_labels": "warning",
"unannotated": "error",
"unit_value_mismatch": "error",
"unresolved_variable": "error",
"wire_dangling": "error"
}
},
"libraries": {
"pinned_footprint_libs": [],
"pinned_symbol_libs": []
},
"meta": {
"filename": "d1_mini_shield.kicad_pro",
"version": 1
},
"net_settings": {
"classes": [
{
"bus_width": 12.0,
"clearance": 0.2,
"diff_pair_gap": 0.25,
"diff_pair_via_gap": 0.25,
"diff_pair_width": 0.2,
"line_style": 0,
"microvia_diameter": 0.3,
"microvia_drill": 0.1,
"name": "Default",
"pcb_color": "rgba(0, 0, 0, 0.000)",
"schematic_color": "rgba(0, 0, 0, 0.000)",
"track_width": 0.25,
"via_diameter": 0.8,
"via_drill": 0.4,
"wire_width": 6.0
}
],
"meta": {
"version": 2
},
"net_colors": null
},
"pcbnew": {
"last_paths": {
"gencad": "",
"idf": "",
"netlist": "d1_mini_shield.net",
"specctra_dsn": "",
"step": "",
"vrml": ""
},
"page_layout_descr_file": ""
},
"schematic": {
"annotate_start_num": 0,
"drawing": {
"default_line_thickness": 6.0,
"default_text_size": 50.0,
"field_names": [],
"intersheets_ref_own_page": false,
"intersheets_ref_prefix": "",
"intersheets_ref_short": false,
"intersheets_ref_show": false,
"intersheets_ref_suffix": "",
"junction_size_choice": 3,
"label_size_ratio": 0.25,
"pin_symbol_size": 0.0,
"text_offset_ratio": 0.08
},
"legacy_lib_dir": "",
"legacy_lib_list": [],
"meta": {
"version": 1
},
"net_format_name": "Pcbnew",
"ngspice": {
"fix_include_paths": true,
"fix_passive_vals": false,
"meta": {
"version": 0
},
"model_mode": 0,
"workbook_filename": ""
},
"page_layout_descr_file": "",
"plot_directory": "",
"spice_adjust_passive_values": false,
"spice_external_command": "spice \"%I\"",
"subpart_first_id": 65,
"subpart_id_separator": 0
},
"sheets": [],
"text_variables": {}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 173 KiB

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 35 KiB

BIN
images/status-bar.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 18 KiB

View File

@@ -1,363 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _AMSCONFIGURATION_h
#define _AMSCONFIGURATION_h
#include <EEPROM.h>
#include "Arduino.h"
#define EEPROM_SIZE 1024*3
#define EEPROM_CHECK_SUM 104 // Used to check if config is stored. Change if structure changes
#define EEPROM_CLEARED_INDICATOR 0xFC
#define EEPROM_CONFIG_ADDRESS 0
#define EEPROM_TEMP_CONFIG_ADDRESS 2048
#define CONFIG_SYSTEM_START 8
#define CONFIG_UPGRADE_INFO_START 16
#define CONFIG_NETWORK_START 40
#define CONFIG_METER_START 296
#define CONFIG_GPIO_START 368
#define CONFIG_PRICE_START 400
#define CONFIG_ENERGYACCOUNTING_START 472
#define CONFIG_WEB_START 496
#define CONFIG_DEBUG_START 632
#define CONFIG_NTP_START 640
#define CONFIG_MQTT_START 768
#define CONFIG_DOMOTICZ_START 1536
#define CONFIG_HA_START 1552
#define CONFIG_UI_START 1720
#define CONFIG_CLOUD_START 1742
#define CONFIG_METER_START_103 32
#define CONFIG_UPGRADE_INFO_START_103 216
#define CONFIG_UI_START_103 248
#define CONFIG_GPIO_START_103 266
#define CONFIG_ENTSOE_START_103 290
#define CONFIG_WIFI_START_103 360
#define CONFIG_ENERGYACCOUNTING_START_103 576
#define CONFIG_WEB_START_103 648
#define CONFIG_DEBUG_START_103 824
#define CONFIG_DOMOTICZ_START_103 856
#define CONFIG_NTP_START_103 872
#define CONFIG_MQTT_START_103 1004
#define CONFIG_HA_START_103 1680
#define LED_BEHAVIOUR_DEFAULT 0
#define LED_BEHAVIOUR_BOOT 1
#define LED_BEHAVIOUR_ERROR_ONLY 3
#define LED_BEHAVIOUR_OFF 9
struct ResetDataContainer {
uint8_t cause;
uint8_t last_cause;
uint8_t magic;
};
struct SystemConfig {
uint8_t boardType;
bool vendorConfigured;
bool userConfigured;
uint8_t dataCollectionConsent; // 0 = unknown, 1 = accepted, 2 = declined
char country[3];
uint8_t energyspeedometer;
}; // 9
struct NetworkConfig {
char ssid[32];
char psk[64];
char ip[16];
char gateway[16];
char subnet[16];
char dns1[16];
char dns2[16];
char hostname[32];
bool mdns;
uint8_t power;
uint8_t sleep;
uint8_t use11b;
bool ipv6;
uint8_t mode;
}; // 214
struct MqttConfig {
char host[128];
uint16_t port;
char clientId[32];
char publishTopic[64];
char subscribeTopic[64];
char username[128];
char password[256];
uint8_t payloadFormat;
bool ssl;
}; // 676
struct WebConfig {
uint8_t security;
char username[37];
char password[37];
char context[37];
}; // 112
struct WebConfig103 {
uint8_t security;
char username[64];
char password[64];
}; // 129
struct MeterConfig {
uint32_t baud;
uint8_t parity;
bool invert;
uint8_t distributionSystem;
uint16_t mainFuse;
uint16_t productionCapacity;
uint8_t encryptionKey[16];
uint8_t authenticationKey[16];
uint32_t wattageMultiplier;
uint32_t voltageMultiplier;
uint32_t amperageMultiplier;
uint32_t accumulatedMultiplier;
uint8_t source;
uint8_t parser;
uint8_t bufferSize;
uint8_t rxPin;
bool rxPinPullup;
uint8_t txPin;
}; // 65
struct DebugConfig {
bool telnet;
bool serial;
uint8_t level;
}; // 3
struct GpioConfig {
uint8_t apPin;
uint8_t ledPin;
bool ledInverted;
uint8_t ledPinRed;
uint8_t ledPinGreen;
uint8_t ledPinBlue;
bool ledRgbInverted;
uint8_t tempSensorPin;
uint8_t tempAnalogSensorPin;
uint8_t vccPin;
int16_t vccOffset;
uint16_t vccMultiplier;
uint8_t vccBootLimit;
uint16_t vccResistorGnd;
uint16_t vccResistorVcc;
uint8_t ledDisablePin;
uint8_t ledBehaviour;
}; // 21
struct GpioConfig103 {
uint8_t hanPin;
uint8_t apPin;
uint8_t ledPin;
bool ledInverted;
uint8_t ledPinRed;
uint8_t ledPinGreen;
uint8_t ledPinBlue;
bool ledRgbInverted;
uint8_t tempSensorPin;
uint8_t tempAnalogSensorPin;
uint8_t vccPin;
int16_t vccOffset;
uint16_t vccMultiplier;
uint8_t vccBootLimit;
uint16_t vccResistorGnd;
uint16_t vccResistorVcc;
bool hanPinPullup;
uint8_t ledDisablePin;
uint8_t ledBehaviour;
}; // 23
struct DomoticzConfig {
uint16_t elidx;
uint16_t vl1idx;
uint16_t vl2idx;
uint16_t vl3idx;
uint16_t cl1idx;
}; // 10
struct HomeAssistantConfig {
char discoveryPrefix[64];
char discoveryHostname[64];
char discoveryNameTag[16];
}; // 145
struct NtpConfig {
bool enable;
bool dhcp;
char server[64];
char timezone[32];
}; // 98
struct PriceServiceConfig {
char entsoeToken[37];
char area[17];
char currency[4];
uint32_t unused1;
bool enabled;
uint16_t unused2;
}; // 64
struct EnergyAccountingConfig {
uint16_t thresholds[10];
uint8_t hours;
}; // 21
struct EnergyAccountingConfig101 {
uint8_t thresholds[10];
uint8_t hours;
}; // 11
struct UiConfig {
uint8_t showImport;
uint8_t showExport;
uint8_t showVoltage;
uint8_t showAmperage;
uint8_t showReactive;
uint8_t showRealtime;
uint8_t showPeaks;
uint8_t showPricePlot;
uint8_t showDayPlot;
uint8_t showMonthPlot;
uint8_t showTemperaturePlot;
uint8_t showRealtimePlot;
uint8_t showPerPhasePower;
uint8_t showPowerFactor;
uint8_t darkMode;
char language[3];
}; // 15
struct UpgradeInformation {
char fromVersion[8];
char toVersion[8];
int16_t exitCode;
int16_t errorCode;
}; // 20
struct CloudConfig {
bool enabled;
uint8_t interval;
char hostname[64];
uint16_t port;
uint8_t clientId[16];
}; // 69
class AmsConfiguration {
public:
bool hasConfig();
int getConfigVersion();
bool save();
bool getSystemConfig(SystemConfig&);
bool setSystemConfig(SystemConfig&);
bool isSystemConfigChanged();
void ackSystemConfigChanged();
bool getNetworkConfig(NetworkConfig&);
bool setNetworkConfig(NetworkConfig&);
void clearNetworkConfig(NetworkConfig&);
void clearNetworkConfigIp(NetworkConfig&);
bool isNetworkConfigChanged();
void ackNetworkConfigChange();
bool getMqttConfig(MqttConfig&);
bool setMqttConfig(MqttConfig&);
void clearMqtt(MqttConfig&);
void setMqttChanged();
bool isMqttChanged();
void ackMqttChange();
bool getWebConfig(WebConfig&);
bool setWebConfig(WebConfig&);
void clearWebConfig(WebConfig&);
bool getMeterConfig(MeterConfig&);
bool setMeterConfig(MeterConfig&);
void clearMeter(MeterConfig&);
void setMeterChanged();
bool isMeterChanged();
void ackMeterChanged();
bool getDebugConfig(DebugConfig&);
bool setDebugConfig(DebugConfig&);
void clearDebug(DebugConfig&);
bool pinUsed(uint8_t, GpioConfig&);
bool getGpioConfig(GpioConfig&);
bool setGpioConfig(GpioConfig&);
void clearGpio(GpioConfig&);
void print(Print* debugger);
bool getDomoticzConfig(DomoticzConfig&);
bool setDomoticzConfig(DomoticzConfig&);
void clearDomo(DomoticzConfig&);
bool getHomeAssistantConfig(HomeAssistantConfig&);
bool setHomeAssistantConfig(HomeAssistantConfig&);
void clearHomeAssistantConfig(HomeAssistantConfig&);
bool getNtpConfig(NtpConfig&);
bool setNtpConfig(NtpConfig&);
void clearNtp(NtpConfig&);
bool isNtpChanged();
void ackNtpChange();
bool getPriceServiceConfig(PriceServiceConfig&);
bool setPriceServiceConfig(PriceServiceConfig&);
void clearPriceServiceConfig(PriceServiceConfig&);
bool isPriceServiceChanged();
void ackPriceServiceChange();
bool getEnergyAccountingConfig(EnergyAccountingConfig&);
bool setEnergyAccountingConfig(EnergyAccountingConfig&);
void clearEnergyAccountingConfig(EnergyAccountingConfig&);
bool isEnergyAccountingChanged();
void ackEnergyAccountingChange();
bool getUiConfig(UiConfig&);
bool setUiConfig(UiConfig&);
void clearUiConfig(UiConfig&);
void setUiLanguageChanged();
bool isUiLanguageChanged();
void ackUiLanguageChange();
bool getUpgradeInformation(UpgradeInformation&);
bool setUpgradeInformation(int16_t exitCode, int16_t errorCode, const char* currentVersion, const char* nextVersion);
void clearUpgradeInformation(UpgradeInformation&);
bool getCloudConfig(CloudConfig&);
bool setCloudConfig(CloudConfig&);
void clearCloudConfig(CloudConfig&);
bool isCloudChanged();
void ackCloudConfig();
void clear();
protected:
private:
uint8_t configVersion = 0;
bool sysChanged = false, networkChanged, mqttChanged, meterChanged = true, ntpChanged = true, priceChanged = false, energyAccountingChanged = true, cloudChanged = true, uiLanguageChanged = false;
bool relocateConfig101(); // 2.2.0 through 2.2.8
bool relocateConfig102(); // 2.2.9 through 2.2.11
bool relocateConfig103(); // 2.2.12, until, but not including 2.3
void saveToFs();
bool loadFromFs(uint8_t version);
void deleteFromFs(uint8_t version);
};
#endif

View File

@@ -1,92 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include <Timezone.h>
#define JULY1970 15634800
TimeChangeRule TC_GMT = {"GMT", Last, Sun, Jan, 0, 0};
TimeChangeRule TC_WET = {"WET", Last, Sun, Oct, 2, 0};
TimeChangeRule TC_WEST = {"WEST", Last, Sun, Mar, 1, 60};
TimeChangeRule TC_CET = {"CET", Last, Sun, Oct, 3, 60};
TimeChangeRule TC_CEST = {"CEST", Last, Sun, Mar, 2, 120};
TimeChangeRule TC_EET = {"EET", Last, Sun, Oct, 4, 120};
TimeChangeRule TC_EEST = {"EEST", Last, Sun, Mar, 3, 180};
Timezone GMT = Timezone(TC_GMT);
Timezone WesterEuropean = Timezone(TC_WET, TC_WEST);
Timezone CentralEuropean = Timezone(TC_CET, TC_CEST);
Timezone EasternEuropean = Timezone(TC_EET, TC_EEST);
Timezone* resolveTimezone(char* name) {
if(strncmp_P(name, PSTR("Europe/"), 7) == 0) {
if(strncmp_P(name+7, PSTR("Amsterdam"), 9) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Athens"), 6) == 0)
return &EasternEuropean;
if(strncmp_P(name+7, PSTR("Belfast"), 7) == 0)
return &WesterEuropean;
if(strncmp_P(name+7, PSTR("Berlin"), 6) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Bratislava"), 10) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Brussels"), 8) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Bucharest"), 9) == 0)
return &EasternEuropean;
if(strncmp_P(name+7, PSTR("Budapest"), 8) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Copenhagen"), 10) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Dublin"), 6) == 0)
return &WesterEuropean;
if(strncmp_P(name+7, PSTR("Helsinki"), 8) == 0)
return &EasternEuropean;
if(strncmp_P(name+7, PSTR("Lisbon"), 6) == 0)
return &WesterEuropean;
if(strncmp_P(name+7, PSTR("Ljubljana"), 9) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("London"), 6) == 0)
return &WesterEuropean;
if(strncmp_P(name+7, PSTR("Luxembourg"), 10) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Madrid"), 6) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Malta"), 5) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Nicosia"), 7) == 0)
return &EasternEuropean;
if(strncmp_P(name+7, PSTR("Oslo"), 4) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Paris"), 5) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Podgorica"), 9) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Prague"), 6) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Riga"), 4) == 0)
return &EasternEuropean;
if(strncmp_P(name+7, PSTR("Rome"), 4) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Sofia"), 5) == 0)
return &EasternEuropean;
if(strncmp_P(name+7, PSTR("Stockholm"), 9) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Tallinn"), 7) == 0)
return &EasternEuropean;
if(strncmp_P(name+7, PSTR("Vienna"), 6) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Vilnius"), 7) == 0)
return &EasternEuropean;
if(strncmp_P(name+7, PSTR("Warsaw"), 6) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Zagreb"), 6) == 0)
return &CentralEuropean;
if(strncmp_P(name+7, PSTR("Zurich"), 6) == 0)
return &CentralEuropean;
}
return &GMT;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,48 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "hexutils.h"
String toHex(uint8_t* in) {
return toHex(in, sizeof(in)*2);
}
String toHex(uint8_t* in, uint16_t size) {
String hex;
for(int i = 0; i < size; i++) {
if(in[i] < 0x10) {
hex += '0';
}
hex += String(in[i], HEX);
}
hex.toUpperCase();
return hex;
}
void fromHex(uint8_t *out, String in, uint16_t size) {
for(int i = 0; i < size*2; i += 2) {
out[i/2] = strtol(in.substring(i, i+2).c_str(), 0, 16);
}
}
bool stripNonAscii(uint8_t* in, uint16_t size, bool extended) {
bool ret = false;
for(uint16_t i = 0; i < size; i++) {
if(in[i] == 0) { // Clear the rest with null-terminator
memset(in+i, 0, size-i);
break;
}
if(extended && (in[i] < 32 || in[i] == 127 || in[i] == 129 || in[i] == 141 || in[i] == 143 || in[i] == 144 || in[i] == 157)) {
memset(in+i, ' ', 1);
ret = true;
} else if(!extended && (in[i] < 32 || in[i] > 126)) {
memset(in+i, ' ', 1);
ret = true;
}
}
memset(in+size-1, 0, 1); // Make sure the last character is null-terminator
return ret;
}

View File

@@ -1,81 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _OBISCODES_H
#define _OBISCODES_H
#include "lwip/def.h"
#define OBIS_MEDIUM_ABSTRACT 0
#define OBIS_MEDIUM_ELECTRICITY 1
#define OBIS_CHAN_0 0
#define OBIS_CHAN_1 1
#define OBIS_RANGE_NA 0xFF
struct OBIS_head_t {
uint8_t medium;
uint8_t channel;
} __attribute__((packed));
struct OBIS_code_t {
uint8_t sensor;
uint8_t gr;
uint8_t tariff;
} __attribute__((packed));
struct OBIS_t {
OBIS_head_t head;
OBIS_code_t code;
uint8_t range;
} __attribute__((packed));
const OBIS_code_t OBIS_NULL PROGMEM = { 0, 0, 0 };
const OBIS_code_t OBIS_FIRMWARE_VERSION PROGMEM = { 0, 2, 0 };
const OBIS_code_t OBIS_VERSION PROGMEM = { 0, 2, 129 };
const OBIS_code_t OBIS_METER_MODEL PROGMEM = { 96, 1, 1 };
const OBIS_code_t OBIS_METER_MODEL_2 PROGMEM = { 96, 1, 7 };
const OBIS_code_t OBIS_METER_ID PROGMEM = { 96, 1, 0 };
const OBIS_code_t OBIS_METER_ID_2 PROGMEM = { 0, 0, 5 };
const OBIS_code_t OBIS_METER_TIMESTAMP PROGMEM = { 1, 0, 0 };
const OBIS_code_t OBIS_ACTIVE_IMPORT PROGMEM = { 1, 7, 0 };
const OBIS_code_t OBIS_ACTIVE_IMPORT_COUNT PROGMEM = { 1, 8, 0 };
const OBIS_code_t OBIS_ACTIVE_EXPORT PROGMEM = { 2, 7, 0 };
const OBIS_code_t OBIS_ACTIVE_EXPORT_COUNT PROGMEM = { 2, 8, 0 };
const OBIS_code_t OBIS_REACTIVE_IMPORT PROGMEM = { 3, 7, 0 };
const OBIS_code_t OBIS_REACTIVE_IMPORT_COUNT PROGMEM = { 3, 8, 0 };
const OBIS_code_t OBIS_REACTIVE_EXPORT PROGMEM = { 4, 7, 0 };
const OBIS_code_t OBIS_REACTIVE_EXPORT_COUNT PROGMEM = { 4, 8, 0 };
const OBIS_code_t OBIS_POWER_FACTOR PROGMEM = { 13, 7, 0 };
const OBIS_code_t OBIS_ACTIVE_IMPORT_L1 PROGMEM = { 21, 7, 0 };
const OBIS_code_t OBIS_ACTIVE_EXPORT_L1 PROGMEM = { 22, 7, 0 };
const OBIS_code_t OBIS_CURRENT_L1 PROGMEM = { 31, 7, 0 };
const OBIS_code_t OBIS_VOLTAGE_L1 PROGMEM = { 32, 7, 0 };
const OBIS_code_t OBIS_POWER_FACTOR_L1 PROGMEM = { 33, 7, 0 };
const OBIS_code_t OBIS_ACTIVE_IMPORT_L2 PROGMEM = { 41, 7, 0 };
const OBIS_code_t OBIS_ACTIVE_EXPORT_L2 PROGMEM = { 42, 7, 0 };
const OBIS_code_t OBIS_CURRENT_L2 PROGMEM = { 51, 7, 0 };
const OBIS_code_t OBIS_VOLTAGE_L2 PROGMEM = { 52, 7, 0 };
const OBIS_code_t OBIS_POWER_FACTOR_L2 PROGMEM = { 53, 7, 0 };
const OBIS_code_t OBIS_ACTIVE_IMPORT_L3 PROGMEM = { 61, 7, 0 };
const OBIS_code_t OBIS_ACTIVE_EXPORT_L3 PROGMEM = { 62, 7, 0 };
const OBIS_code_t OBIS_CURRENT_L3 PROGMEM = { 71, 7, 0 };
const OBIS_code_t OBIS_VOLTAGE_L3 PROGMEM = { 72, 7, 0 };
const OBIS_code_t OBIS_POWER_FACTOR_L3 PROGMEM = { 73, 7, 0 };
#endif

View File

@@ -1,366 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "AmsData.h"
AmsData::AmsData() {}
void AmsData::apply(AmsData& other) {
if(other.getListType() < 3) {
unsigned long ms = this->lastUpdateMillis > other.getLastUpdateMillis() ? 0 : other.getLastUpdateMillis() - this->lastUpdateMillis;
if(ms > 0) {
if(other.getActiveImportPower() > 0) {
uint32_t power = (activeImportPower + other.getActiveImportPower()) / 2;
float add = power * (((float) ms) / 3600000.0);
activeImportCounter += add / 1000.0;
//Serial.printf("%dW, %dms, %.6fkWh added\n", other.getActiveImportPower(), ms, add);
}
if(other.getListType() > 1) {
ms = this->lastList2 > other.getLastUpdateMillis() ? 0 : other.getLastUpdateMillis() - this->lastList2;
if(other.getActiveExportPower() > 0) {
uint32_t power = (activeExportPower + other.getActiveExportPower()) / 2;
float add = power * (((float) ms) / 3600000.0);
activeExportCounter += add / 1000.0;
}
if(other.getReactiveImportPower() > 0) {
uint32_t power = (reactiveImportPower + other.getReactiveImportPower()) / 2;
float add = power * (((float) ms) / 3600000.0);
reactiveImportCounter += add / 1000.0;
}
if(other.getReactiveExportPower() > 0) {
uint32_t power = (reactiveExportPower + other.getReactiveExportPower()) / 2;
float add = power * (((float) ms) / 3600000.0);
reactiveExportCounter += add / 1000.0;
}
}
counterEstimated = true;
}
}
this->lastUpdateMillis = other.getLastUpdateMillis();
if(other.getListType() > 1) {
this->lastList2 = this->lastUpdateMillis;
}
this->packageTimestamp = other.getPackageTimestamp();
if(other.getListType() > this->listType)
this->listType = other.getListType();
switch(other.getListType()) {
case 4:
this->powerFactor = other.getPowerFactor();
this->l1PowerFactor = other.getL1PowerFactor();
this->l2PowerFactor = other.getL2PowerFactor();
this->l3PowerFactor = other.getL3PowerFactor();
this->l1activeImportPower = other.getL1ActiveImportPower();
this->l2activeImportPower = other.getL2ActiveImportPower();
this->l3activeImportPower = other.getL3ActiveImportPower();
this->l1activeExportPower = other.getL1ActiveExportPower();
this->l2activeExportPower = other.getL2ActiveExportPower();
this->l3activeExportPower = other.getL3ActiveExportPower();
this->l1activeImportCounter = other.getL1ActiveImportCounter();
this->l2activeImportCounter = other.getL2ActiveImportCounter();
this->l3activeImportCounter = other.getL3ActiveImportCounter();
this->l1activeExportCounter = other.getL1ActiveExportCounter();
this->l2activeExportCounter = other.getL2ActiveExportCounter();
this->l3activeExportCounter = other.getL3ActiveExportCounter();
case 3:
this->meterTimestamp = other.getMeterTimestamp();
this->activeImportCounter = other.getActiveImportCounter();
this->activeExportCounter = other.getActiveExportCounter();
this->reactiveImportCounter = other.getReactiveImportCounter();
this->reactiveExportCounter = other.getReactiveExportCounter();
this->counterEstimated = false;
case 2:
this->listId = other.getListId();
this->meterId = other.getMeterId();
this->meterType = other.getMeterType();
this->meterModel = other.getMeterModel();
this->reactiveImportPower = other.getReactiveImportPower();
this->reactiveExportPower = other.getReactiveExportPower();
this->l1current = other.getL1Current();
this->l2current = other.getL2Current();
this->l2currentMissing = other.isL2currentMissing();
this->l3current = other.getL3Current();
this->l1voltage = other.getL1Voltage();
this->l2voltage = other.getL2Voltage();
this->l3voltage = other.getL3Voltage();
this->threePhase = other.isThreePhase();
this->twoPhase = other.isTwoPhase();
}
// Moved outside switch to handle meters alternating between sending active and accumulated values
if(other.getListType() == 1 || (other.getActiveImportPower() > 0 || other.getActiveExportPower() > 0))
this->activeImportPower = other.getActiveImportPower();
if(other.getListType() == 2 || (other.getActiveImportPower() > 0 || other.getActiveExportPower() > 0))
this->activeExportPower = other.getActiveExportPower();
}
void AmsData::apply(OBIS_code_t obis, double value) {
switch(obis.gr) {
case 1:
switch(obis.sensor) {
case 7:
switch(obis.tariff) {
case 0:
activeImportPower = value;
listType = max(listType, (uint8_t) 1);
break;
}
break;
case 8:
switch(obis.tariff) {
case 0:
activeImportCounter = value;
listType = max(listType, (uint8_t) 3);
break;
}
break;
}
break;
case 2:
switch(obis.sensor) {
case 7:
switch(obis.tariff) {
case 0:
activeExportPower = value;
listType = max(listType, (uint8_t) 2);
break;
}
break;
case 8:
switch(obis.tariff) {
case 0:
activeExportCounter = value;
listType = max(listType, (uint8_t) 3);
break;
}
break;
}
break;
case 3:
switch(obis.sensor) {
case 7:
switch(obis.tariff) {
case 0:
reactiveImportPower = value;
listType = max(listType, (uint8_t) 2);
break;
}
break;
case 8:
switch(obis.tariff) {
case 0:
reactiveImportCounter = value;
listType = max(listType, (uint8_t) 3);
break;
}
break;
}
break;
case 4:
switch(obis.sensor) {
case 7:
switch(obis.tariff) {
case 0:
reactiveExportPower = value;
listType = max(listType, (uint8_t) 2);
break;
}
break;
case 8:
switch(obis.tariff) {
case 0:
reactiveExportCounter = value;
listType = max(listType, (uint8_t) 3);
break;
}
break;
}
break;
}
}
uint64_t AmsData::getLastUpdateMillis() {
return this->lastUpdateMillis;
}
time_t AmsData::getPackageTimestamp() {
return this->packageTimestamp;
}
uint8_t AmsData::getListType() {
return this->listType;
}
String AmsData::getListId() {
return this->listId;
}
String AmsData::getMeterId() {
return this->meterId;
}
uint8_t AmsData::getMeterType() {
return this->meterType;
}
String AmsData::getMeterModel() {
return this->meterModel;
}
time_t AmsData::getMeterTimestamp() {
return this->meterTimestamp;
}
uint32_t AmsData::getActiveImportPower() {
return this->activeImportPower;
}
uint32_t AmsData::getReactiveImportPower() {
return this->reactiveImportPower;
}
uint32_t AmsData::getActiveExportPower() {
return this->activeExportPower;
}
uint32_t AmsData::getReactiveExportPower() {
return this->reactiveExportPower;
}
float AmsData::getL1Voltage() {
return this->l1voltage;
}
float AmsData::getL2Voltage() {
return this->l2voltage;
}
float AmsData::getL3Voltage() {
return this->l3voltage;
}
float AmsData::getL1Current() {
return this->l1current;
}
float AmsData::getL2Current() {
return this->l2current;
}
float AmsData::getL3Current() {
return this->l3current;
}
float AmsData::getPowerFactor() {
return this->powerFactor;
}
float AmsData::getL1PowerFactor() {
return this->l1PowerFactor;
}
float AmsData::getL2PowerFactor() {
return this->l2PowerFactor;
}
float AmsData::getL3PowerFactor() {
return this->l3PowerFactor;
}
uint32_t AmsData::getL1ActiveImportPower() {
return this->l1activeImportPower;
}
uint32_t AmsData::getL2ActiveImportPower() {
return this->l2activeImportPower;
}
uint32_t AmsData::getL3ActiveImportPower() {
return this->l3activeImportPower;
}
uint32_t AmsData::getL1ActiveExportPower() {
return this->l1activeExportPower;
}
uint32_t AmsData::getL2ActiveExportPower() {
return this->l2activeExportPower;
}
uint32_t AmsData::getL3ActiveExportPower() {
return this->l3activeExportPower;
}
double AmsData::getL1ActiveImportCounter() {
return this->l1activeImportCounter;
}
double AmsData::getL2ActiveImportCounter() {
return this->l2activeImportCounter;
}
double AmsData::getL3ActiveImportCounter() {
return this->l3activeImportCounter;
}
double AmsData::getL1ActiveExportCounter() {
return this->l1activeExportCounter;
}
double AmsData::getL2ActiveExportCounter() {
return this->l2activeExportCounter;
}
double AmsData::getL3ActiveExportCounter() {
return this->l3activeExportCounter;
}
double AmsData::getActiveImportCounter() {
return this->activeImportCounter;
}
double AmsData::getReactiveImportCounter() {
return this->reactiveImportCounter;
}
double AmsData::getActiveExportCounter() {
return this->activeExportCounter;
}
double AmsData::getReactiveExportCounter() {
return this->reactiveExportCounter;
}
bool AmsData::isThreePhase() {
return this->threePhase;
}
bool AmsData::isTwoPhase() {
return this->twoPhase;
}
bool AmsData::isCounterEstimated() {
return this->counterEstimated;
}
bool AmsData::isL2currentMissing() {
return this->l2currentMissing;
}
int8_t AmsData::getLastError() {
return lastErrorCount > 2 ? lastError : 0;
}
void AmsData::setLastError(int8_t lastError) {
this->lastError = lastError;
if(lastError == 0) {
lastErrorCount = 0;
} else {
lastErrorCount++;
}
}

View File

@@ -1,600 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "AmsDataStorage.h"
#include <lwip/apps/sntp.h>
#include "LittleFS.h"
#include "AmsStorage.h"
#include "FirmwareVersion.h"
AmsDataStorage::AmsDataStorage(RemoteDebug* debugger) {
day.version = 6;
day.accuracy = 1;
month.version = 7;
month.accuracy = 1;
this->debugger = debugger;
}
void AmsDataStorage::setTimezone(Timezone* tz) {
this->tz = tz;
}
bool AmsDataStorage::update(AmsData* data) {
if(isHappy()) {
return false;
}
time_t now = time(nullptr);
if(tz == NULL) {
return false;
}
if(now < FirmwareVersion::BuildEpoch) {
if(data->getMeterTimestamp() > FirmwareVersion::BuildEpoch) {
now = data->getMeterTimestamp();
} else if(data->getPackageTimestamp() > FirmwareVersion::BuildEpoch) {
now = data->getPackageTimestamp();
}
}
if(now < FirmwareVersion::BuildEpoch) {
return false;
}
tmElements_t utc, ltz, utcYesterday, ltzYesterDay;
breakTime(now, utc);
breakTime(tz->toLocal(now), ltz);
breakTime(now-3600, utcYesterday);
breakTime(tz->toLocal(now-3600), ltzYesterDay);
uint64_t importCounter = data->getActiveImportCounter() * 1000;
uint64_t exportCounter = data->getActiveExportCounter() * 1000;
// Clear hours between last update and now
if(day.lastMeterReadTime > now) {
day.activeImport = importCounter;
day.activeExport = exportCounter;
day.lastMeterReadTime = now;
} else if((importCounter > 0 && day.activeImport == 0) || now - day.lastMeterReadTime > 86400) {
day.activeImport = importCounter;
day.activeExport = exportCounter;
day.lastMeterReadTime = now;
for(int i = 0; i<24; i++) {
setHourImport(i, 0);
setHourExport(i, 0);
}
} else {
tmElements_t last;
breakTime(day.lastMeterReadTime, last);
uint8_t endHour = utc.Hour;
if(last.Hour > utc.Hour){
for(int i = 0; i < utc.Hour; i++) {
setHourImport(i, 0);
setHourExport(i, 0);
}
endHour = 24;
}
for(int i = last.Hour; i < endHour; i++) {
setHourImport(i, 0);
setHourExport(i, 0);
}
}
// Clear days between last update and now
if(month.lastMeterReadTime > now) {
month.activeImport = importCounter;
month.activeExport = exportCounter;
month.lastMeterReadTime = now;
} else if((importCounter > 0 && month.activeImport == 0) || now - month.lastMeterReadTime > 2682000) {
month.activeImport = importCounter;
month.activeExport = exportCounter;
month.lastMeterReadTime = now;
for(int i = 1; i<=31; i++) {
setDayImport(i, 0);
setDayExport(i, 0);
}
} else {
tmElements_t last;
breakTime(tz->toLocal(month.lastMeterReadTime), last);
uint8_t endDay = ltz.Day;
if(last.Day > ltz.Day) {
for(int i = 1; i < ltz.Day; i++) {
setDayImport(i, 0);
setDayExport(i, 0);
}
endDay = 31;
}
for(int i = last.Day; i < endDay; i++) {
setDayImport(i, 0);
setDayExport(i, 0);
}
}
if(data->getListType() < 3) {
return false;
}
bool ret = false;
// Update day plot
if(!isDayHappy()) {
if(day.activeImport > importCounter || day.activeExport > exportCounter) {
day.activeImport = importCounter;
day.activeExport = exportCounter;
day.lastMeterReadTime = now;
setHourImport(utcYesterday.Hour, 0);
setHourExport(utcYesterday.Hour, 0);
} else if(now - day.lastMeterReadTime < 4000) {
uint32_t imp = importCounter - day.activeImport;
uint32_t exp = exportCounter - day.activeExport;
setHourImport(utcYesterday.Hour, imp);
setHourExport(utcYesterday.Hour, exp);
day.activeImport = importCounter;
day.activeExport = exportCounter;
day.lastMeterReadTime = now;
} else {
float mins = (now - day.lastMeterReadTime) / 60.0;
uint32_t im = importCounter - day.activeImport;
uint32_t ex = exportCounter - day.activeExport;
float ipm = im / mins;
float epm = ex / mins;
tmElements_t last;
breakTime(day.lastMeterReadTime, last);
day.lastMeterReadTime = day.lastMeterReadTime - (last.Minute * 60) - last.Second;
time_t stopAt = now - (utc.Minute * 60) - utc.Second;
while(day.lastMeterReadTime < stopAt) {
time_t cur = min(day.lastMeterReadTime + 3600, stopAt);
uint8_t minutes = round((cur - day.lastMeterReadTime) / 60.0);
if(minutes < 1) break;
breakTime(day.lastMeterReadTime, last);
float imp = (ipm * minutes);
float exp = (epm * minutes);
setHourImport(last.Hour, imp);
setHourExport(last.Hour, exp);
day.activeImport += imp;
day.activeExport += exp;
day.lastMeterReadTime = cur;
}
}
ret = true;
}
// Update month plot
if(ltz.Hour == 0 && !isMonthHappy()) {
if(month.activeImport > importCounter || month.activeExport > exportCounter) {
month.activeImport = importCounter;
month.activeExport = exportCounter;
month.lastMeterReadTime = now;
setDayImport(ltzYesterDay.Day, 0);
setDayExport(ltzYesterDay.Day, 0);
} else if(now - month.lastMeterReadTime < 90100 && now - month.lastMeterReadTime > 82700) { // DST days are 23h (82800s) and 25h (90000)
uint32_t imp = importCounter - month.activeImport;
uint32_t exp = exportCounter - month.activeExport;
setDayImport(ltzYesterDay.Day, imp);
setDayExport(ltzYesterDay.Day, exp);
month.activeImport = importCounter;
month.activeExport = exportCounter;
month.lastMeterReadTime = now;
} else {
// Make sure last month read is at midnight
tmElements_t last;
breakTime(tz->toLocal(month.lastMeterReadTime), last);
month.lastMeterReadTime = month.lastMeterReadTime - (last.Hour * 3600) - (last.Minute * 60) - last.Second;
float hrs = (now - month.lastMeterReadTime) / 3600.0;
uint32_t im = importCounter - month.activeImport;
uint32_t ex = exportCounter - month.activeExport;
float iph = im / hrs;
float eph = ex / hrs;
time_t stopAt = now - (ltz.Hour * 3600) - (ltz.Minute * 60) - ltz.Second;
while(month.lastMeterReadTime < stopAt) {
time_t cur = min(month.lastMeterReadTime + 86400, stopAt);
uint8_t hours = round((cur - month.lastMeterReadTime) / 3600.0);
breakTime(tz->toLocal(month.lastMeterReadTime), last);
float imp = (iph * hours);
float exp = (eph * hours);
setDayImport(last.Day, imp);
setDayExport(last.Day, exp);
month.activeImport += imp;
month.activeExport += exp;
month.lastMeterReadTime = cur;
}
}
ret = true;
}
return ret;
}
void AmsDataStorage::setHourImport(uint8_t hour, uint32_t val) {
if(hour < 0 || hour > 24) return;
uint8_t accuracy = day.accuracy;
uint32_t update = val / pow(10, accuracy);
while(update > UINT16_MAX) {
accuracy++;
update = val / pow(10, accuracy);
}
if(accuracy != day.accuracy) {
setDayAccuracy(accuracy);
}
day.hImport[hour] = update;
uint32_t max = 0;
for(uint8_t i = 0; i < 24; i++) {
if(day.hImport[i] > max)
max = day.hImport[i];
if(day.hExport[i] > max)
max = day.hExport[i];
}
while(max < UINT16_MAX/10 && accuracy > 0) {
accuracy--;
max = max*10;
}
if(accuracy != day.accuracy) {
setDayAccuracy(accuracy);
}
}
uint32_t AmsDataStorage::getHourImport(uint8_t hour) {
if(hour < 0 || hour > 24) return 0;
return day.hImport[hour] * pow(10, day.accuracy);
}
void AmsDataStorage::setHourExport(uint8_t hour, uint32_t val) {
if(hour < 0 || hour > 24) return;
uint8_t accuracy = day.accuracy;
uint32_t update = val / pow(10, accuracy);
while(update > UINT16_MAX) {
accuracy++;
update = val / pow(10, accuracy);
}
if(accuracy != day.accuracy) {
setDayAccuracy(accuracy);
}
day.hExport[hour] = update;
uint32_t max = 0;
for(uint8_t i = 0; i < 24; i++) {
if(day.hImport[i] > max)
max = day.hImport[i];
if(day.hExport[i] > max)
max = day.hExport[i];
}
while(max < UINT16_MAX/10 && accuracy > 0) {
accuracy--;
max = max*10;
}
if(accuracy != day.accuracy) {
setDayAccuracy(accuracy);
}
}
uint32_t AmsDataStorage::getHourExport(uint8_t hour) {
if(hour < 0 || hour > 24) return 0;
return day.hExport[hour] * pow(10, day.accuracy);
}
void AmsDataStorage::setDayImport(uint8_t day, uint32_t val) {
if(day < 1 || day > 31) return;
uint8_t accuracy = month.accuracy;
uint32_t update = val / pow(10, accuracy);
while(update > UINT16_MAX) {
accuracy++;
update = val / pow(10, accuracy);
}
if(accuracy != month.accuracy) {
setMonthAccuracy(accuracy);
}
month.dImport[day-1] = update;
uint32_t max = 0;
for(uint8_t i = 0; i < 31; i++) {
if(month.dImport[i] > max)
max = month.dImport[i];
if(month.dExport[i] > max)
max = month.dExport[i];
}
while(max < UINT16_MAX/10 && accuracy > 0) {
accuracy--;
max = max*10;
}
if(accuracy != month.accuracy) {
setMonthAccuracy(accuracy);
}
}
uint32_t AmsDataStorage::getDayImport(uint8_t day) {
if(day < 1 || day > 31) return 0;
return (month.dImport[day-1] * pow(10, month.accuracy));
}
void AmsDataStorage::setDayExport(uint8_t day, uint32_t val) {
if(day < 1 || day > 31) return;
uint8_t accuracy = month.accuracy;
uint32_t update = val / pow(10, accuracy);
while(update > UINT16_MAX) {
accuracy++;
update = val / pow(10, accuracy);
}
if(accuracy != month.accuracy) {
setMonthAccuracy(accuracy);
}
month.dExport[day-1] = update;
uint32_t max = 0;
for(uint8_t i = 0; i < 31; i++) {
if(month.dImport[i] > max)
max = month.dImport[i];
if(month.dExport[i] > max)
max = month.dExport[i];
}
while(max < UINT16_MAX/10 && accuracy > 0) {
accuracy--;
max = max*10;
}
if(accuracy != month.accuracy) {
setMonthAccuracy(accuracy);
}
}
uint32_t AmsDataStorage::getDayExport(uint8_t day) {
if(day < 1 || day > 31) return 0;
return (month.dExport[day-1] * pow(10, month.accuracy));
}
bool AmsDataStorage::load() {
if(!LittleFS.begin()) {
return false;
}
bool ret = false;
if(LittleFS.exists(FILE_DAYPLOT)) {
File file = LittleFS.open(FILE_DAYPLOT, "r");
char buf[file.size()];
file.readBytes(buf, file.size());
if(buf[0] > 5) {
DayDataPoints* day = (DayDataPoints*) buf;
ret = setDayData(*day);
} else {
DayDataPoints5* old = (DayDataPoints5*) buf;
DayDataPoints day = { old->version };
day.lastMeterReadTime = old->lastMeterReadTime;
day.activeImport = old->activeImport;
day.activeExport = old->activeExport;
day.accuracy = old->accuracy;
for(uint8_t i = 0; i < 24; i++) {
day.hImport[i] = old->hImport[i];
day.hExport[i] = old->hExport[i];
}
ret = setDayData(day);
}
file.close();
}
if(LittleFS.exists(FILE_MONTHPLOT)) {
File file = LittleFS.open(FILE_MONTHPLOT, "r");
char buf[file.size()];
file.readBytes(buf, file.size());
if(buf[0] > 6) {
MonthDataPoints* month = (MonthDataPoints*) buf;
ret &= setMonthData(*month);
} else {
MonthDataPoints6* old = (MonthDataPoints6*) buf;
MonthDataPoints month = { old->version };
month.lastMeterReadTime = old->lastMeterReadTime;
month.activeImport = old->activeImport;
month.activeExport = old->activeExport;
month.accuracy = old->accuracy;
for(uint8_t i = 0; i < 31; i++) {
month.dImport[i] = old->dImport[i];
month.dExport[i] = old->dExport[i];
}
ret &= setMonthData(month);
}
file.close();
}
return ret;
}
bool AmsDataStorage::save() {
if(!LittleFS.begin()) {
return false;
}
{
File file = LittleFS.open(FILE_DAYPLOT, "w");
char buf[sizeof(day)];
memcpy(buf, &day, sizeof(day));
for(unsigned long i = 0; i < sizeof(day); i++) {
file.write(buf[i]);
}
file.close();
}
{
File file = LittleFS.open(FILE_MONTHPLOT, "w");
char buf[sizeof(month)];
memcpy(buf, &month, sizeof(month));
for(unsigned long i = 0; i < sizeof(month); i++) {
file.write(buf[i]);
}
file.close();
}
return true;
}
DayDataPoints AmsDataStorage::getDayData() {
return day;
}
MonthDataPoints AmsDataStorage::getMonthData() {
return month;
}
bool AmsDataStorage::setDayData(DayDataPoints& day) {
if(day.version == 5 || day.version == 6) {
this->day = day;
this->day.version = 6;
return true;
} else if(day.version == 4) {
this->day = day;
this->day.accuracy = 1;
this->day.version = 6;
return true;
} else if(day.version == 3) {
this->day = day;
for(uint8_t i = 0; i < 24; i++) this->day.hExport[i] = 0;
this->day.accuracy = 1;
this->day.version = 6;
return true;
}
return false;
}
bool AmsDataStorage::setMonthData(MonthDataPoints& month) {
if(month.version == 6 || month.version == 7) {
this->month = month;
this->month.version = 7;
return true;
} else if(month.version == 5) {
this->month = month;
this->month.accuracy = 1;
this->month.version = 7;
return true;
} else if(month.version == 4) {
this->month = month;
for(uint8_t i = 0; i < 31; i++) this->month.dExport[i] = 0;
this->month.accuracy = 1;
this->month.version = 7;
return true;
}
return false;
}
uint8_t AmsDataStorage::getDayAccuracy() {
return day.accuracy;
}
void AmsDataStorage::setDayAccuracy(uint8_t accuracy) {
if(day.accuracy != accuracy) {
double multiplier = pow(10, day.accuracy)/pow(10, accuracy);
for(uint8_t i = 0; i < 24; i++) {
day.hImport[i] = day.hImport[i] * multiplier;
day.hExport[i] = day.hExport[i] * multiplier;
}
day.accuracy = accuracy;
}
}
uint8_t AmsDataStorage::getMonthAccuracy() {
return month.accuracy;
}
void AmsDataStorage::setMonthAccuracy(uint8_t accuracy) {
if(month.accuracy != accuracy) {
double multiplier = pow(10, month.accuracy)/pow(10, accuracy);
for(uint8_t i = 0; i < 31; i++) {
month.dImport[i] = month.dImport[i] * multiplier;
month.dExport[i] = month.dExport[i] * multiplier;
}
month.accuracy = accuracy;
}
month.accuracy = accuracy;
}
bool AmsDataStorage::isHappy() {
return isDayHappy() && isMonthHappy();
}
bool AmsDataStorage::isDayHappy() {
if(tz == NULL) {
return false;
}
time_t now = time(nullptr);
if(now < FirmwareVersion::BuildEpoch) return false;
if(now < day.lastMeterReadTime) {
return false;
}
if(now-day.lastMeterReadTime > 3600) {
return false;
}
tmElements_t tm, last;
breakTime(tz->toLocal(now), tm);
breakTime(tz->toLocal(day.lastMeterReadTime), last);
if(tm.Hour != last.Hour) {
return false;
}
return true;
}
bool AmsDataStorage::isMonthHappy() {
if(tz == NULL) {
return false;
}
time_t now = time(nullptr);
if(now < FirmwareVersion::BuildEpoch) return false;
tmElements_t tm, last;
if(now < month.lastMeterReadTime) {
return false;
}
breakTime(tz->toLocal(now), tm);
breakTime(tz->toLocal(month.lastMeterReadTime), last);
if(tm.Day != last.Day) {
return false;
}
if(now-month.lastMeterReadTime > 90100) {
return false;
}
return true;
}
double AmsDataStorage::getEstimatedImportCounter() {
if(day.lastMeterReadTime == 0) return 0;
time_t now = time(nullptr);
double hours = (now - day.lastMeterReadTime) / 3600.0;
uint64_t total = 0;
for(uint8_t i = 0; i < 24; i++) {
total += getHourImport(i);
}
double perHour = total / 24.0;
return (day.activeImport + (perHour * hours)) / 1000.0;
}

View File

@@ -1,17 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _CRC_H
#define _CRC_H
#include "Arduino.h"
#include <stdint.h>
uint16_t crc16(const uint8_t* p, int len);
uint16_t crc16_x25(const uint8_t* p, int len);
uint16_t crc16_1021(const uint8_t* p, int len);
#endif

View File

@@ -1,54 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "crc.h"
uint16_t crc16_x25(const uint8_t* p, int len)
{
uint16_t crc = UINT16_MAX;
while(len--)
for (uint16_t i = 0, d = 0xff & *p++; i < 8; i++, d >>= 1)
crc = ((crc & 1) ^ (d & 1)) ? (crc >> 1) ^ 0x8408 : (crc >> 1);
return (~crc << 8) | (~crc >> 8 & 0xff);
}
uint16_t crc16 (const uint8_t *p, int len) {
uint16_t crc = 0;
while (len--) {
uint8_t i;
crc ^= *p++;
for (i = 0 ; i < 8 ; ++i) {
if (crc & 1)
crc = (crc >> 1) ^ 0xa001;
else
crc = (crc >> 1);
}
}
return crc;
}
uint16_t crc16_1021(const uint8_t *p, int len) {
uint32_t crc = 0x0000;
for(int i = 0; i < len; i++) {
int mask = 0x80;
while(mask > 0) {
crc <<= 1;
if (p[i] & mask){
crc |= 1;
}
mask>>=1;
if (crc & 0x10000) {
crc &= 0xffff;
crc ^= 0x1021;
}
}
}
return crc;
}

View File

@@ -1,70 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _AMSMQTTHANDLER_H
#define _AMSMQTTHANDLER_H
#include "Arduino.h"
#include <MQTT.h>
#include "AmsData.h"
#include "AmsConfiguration.h"
#include "EnergyAccounting.h"
#include "HwTools.h"
#include "PriceService.h"
#if defined(ESP32)
#include <esp_task_wdt.h>
#endif
class AmsMqttHandler {
public:
AmsMqttHandler(MqttConfig& mqttConfig, RemoteDebug* debugger, char* buf) {
this->mqttConfig = mqttConfig;
this->mqttConfigChanged = true;
this->debugger = debugger;
this->json = buf;
mqtt.dropOverflow(true);
};
void setCaVerification(bool);
void setConfig(MqttConfig& mqttConfig);
bool connect();
void disconnect();
lwmqtt_err_t lastError();
bool connected();
bool loop();
virtual uint8_t getFormat() { return 0; };
virtual bool publish(AmsData* data, AmsData* previousState, EnergyAccounting* ea, PriceService* ps) { return false; };
virtual bool publishTemperatures(AmsConfiguration*, HwTools*) { return false; };
virtual bool publishPrices(PriceService* ps) { return false; };
virtual bool publishSystem(HwTools*, PriceService*, EnergyAccounting*) { return false; };
virtual bool publishRaw(String data) { return false; };
virtual void onMessage(String &topic, String &payload) {};
virtual ~AmsMqttHandler() {
if(mqttClient != NULL) {
mqttClient->stop();
delete mqttClient;
}
};
protected:
RemoteDebug* debugger;
MqttConfig mqttConfig;
bool mqttConfigChanged = true;
MQTTClient mqtt = MQTTClient(256);
unsigned long lastMqttRetry = -10000;
bool caVerification = true;
WiFiClient *mqttClient = NULL;
WiFiClientSecure *mqttSecureClient = NULL;
char* json;
uint16_t BufferSize = 2048;
};
#endif

View File

@@ -1,167 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "AmsMqttHandler.h"
#include "FirmwareVersion.h"
#include "AmsStorage.h"
#include "LittleFS.h"
void AmsMqttHandler::setCaVerification(bool caVerification) {
this->caVerification = caVerification;
}
void AmsMqttHandler::setConfig(MqttConfig& mqttConfig) {
this->mqttConfig = mqttConfig;
this->mqttConfigChanged = true;
}
bool AmsMqttHandler::connect() {
if(millis() - lastMqttRetry < 10000) {
yield();
return false;
}
lastMqttRetry = millis();
time_t epoch = time(nullptr);
WiFiClient *actualClient = NULL;
if(mqttConfig.ssl) {
if(epoch < FirmwareVersion::BuildEpoch) {
return false;
}
if(mqttSecureClient == NULL) {
mqttSecureClient = new WiFiClientSecure();
#if defined(ESP8266)
mqttSecureClient->setBufferSizes(512, 512);
return false;
#endif
}
if(mqttConfigChanged) {
if(caVerification && LittleFS.begin()) {
File file;
if(LittleFS.exists(FILE_MQTT_CA)) {
file = LittleFS.open(FILE_MQTT_CA, (char*) "r");
#if defined(ESP8266)
BearSSL::X509List *serverTrustedCA = new BearSSL::X509List(file);
mqttSecureClient->setTrustAnchors(serverTrustedCA);
#elif defined(ESP32)
if(!mqttSecureClient->loadCACert(file, file.size())) {
return false;
}
#endif
file.close();
} else {
mqttSecureClient->setInsecure();
}
#if defined(ESP8266)
if(LittleFS.exists(FILE_MQTT_CERT) && LittleFS.exists(FILE_MQTT_KEY)) {
file = LittleFS.open(FILE_MQTT_CERT, (char*) "r");
BearSSL::X509List *serverCertList = new BearSSL::X509List(file);
file.close();
file = LittleFS.open(FILE_MQTT_KEY, (char*) "r");
BearSSL::PrivateKey *serverPrivKey = new BearSSL::PrivateKey(file);
file.close();
mqttSecureClient->setClientRSACert(serverCertList, serverPrivKey);
}
#endif
#if defined(ESP32)
if(LittleFS.exists(FILE_MQTT_CERT)) {
file = LittleFS.open(FILE_MQTT_CERT, (char*) "r");
mqttSecureClient->loadCertificate(file, file.size());
file.close();
}
if(LittleFS.exists(FILE_MQTT_KEY)) {
file = LittleFS.open(FILE_MQTT_KEY, (char*) "r");
mqttSecureClient->loadPrivateKey(file, file.size());
file.close();
}
#endif
} else {
mqttSecureClient->setInsecure();
}
}
actualClient = mqttSecureClient;
} else {
if(mqttClient == NULL) {
mqttClient = new WiFiClient();
}
actualClient = mqttClient;
}
mqttConfigChanged = false;
mqtt.begin(mqttConfig.host, mqttConfig.port, *actualClient);
String statusTopic = String(mqttConfig.publishTopic) + "/status";
mqtt.setWill(statusTopic.c_str(), "offline", true, 0);
#if defined(ESP8266)
if(mqttSecureClient) {
time_t epoch = time(nullptr);
mqttSecureClient->setX509Time(epoch);
}
#endif
// Connect to a unsecure or secure MQTT server
if ((strlen(mqttConfig.username) == 0 && mqtt.connect(mqttConfig.clientId)) ||
(strlen(mqttConfig.username) > 0 && mqtt.connect(mqttConfig.clientId, mqttConfig.username, mqttConfig.password))) {
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("Successfully connected to MQTT\n"));
mqtt.onMessage(std::bind(&AmsMqttHandler::onMessage, this, std::placeholders::_1, std::placeholders::_2));
if(strlen(mqttConfig.subscribeTopic) > 0) {
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR(" Subscribing to [%s]\n"), mqttConfig.subscribeTopic);
if(!mqtt.subscribe(mqttConfig.subscribeTopic)) {
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR(" Unable to subscribe to to [%s]\n"), mqttConfig.subscribeTopic);
}
}
mqtt.publish(statusTopic, "online", true, 0);
mqtt.loop();
return true;
} else {
if (debugger->isActive(RemoteDebug::ERROR)) {
debugger->printf_P(PSTR("Failed to connect to MQTT: %d\n"), mqtt.lastError());
#if defined(ESP8266)
if(mqttSecureClient) {
mqttSecureClient->getLastSSLError((char*) json, BufferSize);
debugger->println((char*) json);
}
#endif
}
return false;
}
}
void AmsMqttHandler::disconnect() {
mqtt.disconnect();
mqtt.loop();
delay(10);
yield();
}
lwmqtt_err_t AmsMqttHandler::lastError() {
return mqtt.lastError();
}
bool AmsMqttHandler::connected() {
return mqtt.connected();
}
bool AmsMqttHandler::loop() {
bool ret = mqtt.loop();
delay(10);
yield();
#if defined(ESP32)
esp_task_wdt_reset();
#elif defined(ESP8266)
ESP.wdtFeed();
#endif
return ret;
}

View File

@@ -1,114 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _CLOUDCONNECTOR_H
#define _CLOUDCONNECTOR_H
#include "RemoteDebug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/platform.h"
#include "mbedtls/net.h"
#include "mbedtls/esp_debug.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/error.h"
#include "mbedtls/certs.h"
#include "mbedtls/rsa.h"
#include "AmsConfiguration.h"
#include "AmsData.h"
#include "EnergyAccounting.h"
#include "HwTools.h"
#include "AmsMqttHandler.h"
#include "ConnectionHandler.h"
#if defined(ESP8266)
#include <ESP8266HTTPClient.h>
#elif defined(ESP32) // ARDUINO_ARCH_ESP32
#include <HTTPClient.h>
#include <esp_wifi.h>
#include <esp_task_wdt.h>
#include <WiFiUdp.h>
#else
#warning "Unsupported board type"
#endif
#define CC_BUF_SIZE 2048
static const char CC_JSON_POWER[] PROGMEM = ",\"%s\":{\"P\":%lu,\"Q\":%lu}";
static const char CC_JSON_POWER_LIST3[] PROGMEM = ",\"%s\":{\"P\":%lu,\"Q\":%lu,\"tP\":%.3f,\"tQ\":%.3f}";
static const char CC_JSON_PHASE[] PROGMEM = "%s\"%d\":{\"u\":%.2f,\"i\":%s}";
static const char CC_JSON_PHASE_LIST4[] PROGMEM = "%s\"%d\":{\"u\":%.2f,\"i\":%s,\"Pim\":%lu,\"Pex\":%lu,\"pf\":%.2f}";
static const char CC_JSON_STATUS[] PROGMEM = ",\"status\":{\"esp\":{\"state\":%d,\"error\":%d},\"han\":{\"state\":%d,\"error\":%d},\"wifi\":{\"state\":%d,\"error\":%d},\"mqtt\":{\"state\":%d,\"error\":%d}}";
static const char CC_JSON_INIT[] PROGMEM = ",\"init\":{\"mac\":\"%s\",\"apmac\":\"%s\",\"version\":\"%s\",\"boardType\":%d,\"bootReason\":%d,\"bootCause\":%d,\"utcOffset\":%d},\"meter\":{\"manufacturerId\":%d,\"manufacturer\":\"%s\",\"model\":\"%s\",\"id\":\"%s\",\"system\":\"%s\",\"fuse\":%d,\"import\":%d,\"export\":%d},\"network\":{\"ip\":\"%s\",\"mask\":\"%s\",\"gw\":\"%s\",\"dns1\":\"%s\",\"dns2\":\"%s\"}";
struct CloudData {
uint8_t type;
int16_t data;
} __attribute__((packed));
class CloudConnector {
public:
CloudConnector(RemoteDebug*);
bool setup(CloudConfig& config, MeterConfig& meter, SystemConfig& system, HwTools* hw, ResetDataContainer* rdc);
void setMqttHandler(AmsMqttHandler* mqttHandler);
void update(AmsData& data, EnergyAccounting& ea);
void forceUpdate();
void setTimezone(Timezone* tz);
void setConnectionHandler(ConnectionHandler* ch);
private:
RemoteDebug* debugger = NULL;
HwTools* hw = NULL;
ConnectionHandler* ch = NULL;
ResetDataContainer* rdc = NULL;
Timezone* tz = NULL;
AmsMqttHandler* mqttHandler = NULL;
CloudConfig config;
HTTPClient http;
WiFiUDP udp;
int maxPwr = 0;
uint8_t boardType = 0;
uint8_t distributionSystem = 0;
uint16_t mainFuse = 0, productionCapacity = 0;
String uuid;
bool initialized = false;
unsigned long lastUpdate = 0;
char mac[18];
char apmac[18];
char clearBuffer[CC_BUF_SIZE];
unsigned char encryptedBuffer[256];
mbedtls_rsa_context* rsa = nullptr;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_entropy_context entropy;
char* pers = "amsreader";
bool init();
void debugPrint(byte *buffer, int start, int length);
String meterManufacturer(uint8_t type) {
switch(type) {
case AmsTypeAidon: return F("Aidon");
case AmsTypeKaifa: return F("Kaifa");
case AmsTypeKamstrup: return F("Kamstrup");
case AmsTypeIskra: return F("Iskra");
case AmsTypeLandisGyr: return F("Landis+Gyr");
case AmsTypeSagemcom: return F("Sagemcom");
}
return F("");
}
String distributionSystemStr(uint8_t ds) {
switch(ds) {
case 1: return F("IT");
case 2: return F("TN");
}
return F("");
}
};
#endif

View File

@@ -1,409 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "CloudConnector.h"
#include "FirmwareVersion.h"
#include "crc.h"
#include "Uptime.h"
#include "hexutils.h"
#if defined(ESP32)
#include <ESPRandom.h>
#endif
#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4
#include "esp32/rom/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32S2
#include "esp32s2/rom/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32C3
#include "esp32c3/rom/rtc.h"
#elif CONFIG_IDF_TARGET_ESP32S3
#include "esp32s3/rom/rtc.h"
#endif
CloudConnector::CloudConnector(RemoteDebug* debugger) {
this->debugger = debugger;
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
http.setReuse(false);
http.setTimeout(60000);
http.setUserAgent("ams2mqtt/" + String(FirmwareVersion::VersionString));
http.useHTTP10(true);
uint8_t mac[6];
uint8_t apmac[6];
#if defined(ESP8266)
wifi_get_macaddr(STATION_IF, mac);
wifi_get_macaddr(SOFTAP_IF, apmac);
#elif defined(ESP32)
esp_wifi_get_mac((wifi_interface_t)ESP_IF_WIFI_STA, mac);
esp_wifi_get_mac((wifi_interface_t)ESP_IF_WIFI_AP, apmac);
#endif
sprintf_P(this->mac, PSTR("%02X:%02X:%02X:%02X:%02X:%02X"), mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
sprintf_P(this->apmac, PSTR("%02X:%02X:%02X:%02X:%02X:%02X"), apmac[0], apmac[1], apmac[2], apmac[3], apmac[4], apmac[5]);
}
bool CloudConnector::setup(CloudConfig& config, MeterConfig& meter, SystemConfig& system, HwTools* hw, ResetDataContainer* rdc) {
bool ret = false;
#if defined(ESP32)
if(!ESPRandom::isValidV4Uuid(config.clientId)) {
ESPRandom::uuid4(config.clientId);
ret = true;
}
uuid = ESPRandom::uuidToString(config.clientId);
#endif
this->config = config;
this->hw = hw;
this->rdc = rdc;
this->boardType = system.boardType;
this->maxPwr = 0;
this->distributionSystem = meter.distributionSystem;
this->mainFuse = meter.mainFuse;
this->productionCapacity = meter.productionCapacity;
this->initialized = false;
return ret;
}
void CloudConnector::setMqttHandler(AmsMqttHandler* mqttHandler) {
this->mqttHandler = mqttHandler;
}
bool CloudConnector::init() {
if(config.enabled) {
//if(config.port == 0)
config.port = 7443;
//if(strlen(config.hostname) == 0)
strcpy_P(config.hostname, PSTR("cloud.amsleser.no"));
snprintf_P(clearBuffer, CC_BUF_SIZE, PSTR("http://%s/hub/cloud/public.key"), config.hostname);
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("(CloudConnector) Downloading public key from %s\n"), clearBuffer);
#if defined(ESP8266)
WiFiClient client;
client.setTimeout(5000);
if(http.begin(client, clearBuffer)) {
#elif defined(ESP32)
if(http.begin(clearBuffer)) {
#endif
int status = http.GET();
#if defined(ESP32)
esp_task_wdt_reset();
#elif defined(ESP8266)
ESP.wdtFeed();
#endif
if(status == HTTP_CODE_OK) {
String pub = http.getString();
http.end();
memset(clearBuffer, 0, CC_BUF_SIZE);
snprintf(clearBuffer, CC_BUF_SIZE, pub.c_str());
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf_P(PSTR("Cloud public key:\n%s\n"), clearBuffer);
mbedtls_pk_context pk;
mbedtls_pk_init(&pk);
int error_code = 0;
if((error_code = mbedtls_pk_parse_public_key(&pk, (unsigned char*) clearBuffer, strlen((const char*) clearBuffer)+1)) == 0){
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf_P(PSTR("RSA public key OK\n"));
rsa = mbedtls_pk_rsa(pk);
mbedtls_ctr_drbg_init(&ctr_drbg);
mbedtls_entropy_init(&entropy);
int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
&entropy, (const unsigned char *) pers,
strlen(pers));
if(ret != 0) {
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("mbedtls_ctr_drbg_seed return code: %d\n"), ret);
}
return ret == 0;
} else {
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf("RSA public key read error: ");
mbedtls_strerror(error_code, clearBuffer, CC_BUF_SIZE);
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf("%s\n", clearBuffer);
}
} else {
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("(CloudConnector) Communication error, returned status: %d\n"), status);
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf(http.errorToString(status).c_str());
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf(http.getString().c_str());
http.end();
}
}
}
return false;
}
void CloudConnector::update(AmsData& data, EnergyAccounting& ea) {
if(!config.enabled) return;
unsigned long now = millis();
if(now-lastUpdate < config.interval*1000) return;
if(!ESPRandom::isValidV4Uuid(config.clientId)) {
if(debugger->isActive(RemoteDebug::WARNING)) debugger->printf_P(PSTR("(CloudConnector) Client ID is not valid\n"));
return;
}
if(data.getListType() < 2) return;
if(!initialized && !init()) {
if(debugger->isActive(RemoteDebug::WARNING)) debugger->printf_P(PSTR("Unable to initialize cloud connector\n"));
return;
}
initialized = true;
memset(clearBuffer, 0, CC_BUF_SIZE);
int pos = 0;
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, PSTR("{\"id\":\"%s\""), uuid.c_str());
if(lastUpdate == 0) {
if(mainFuse > 0 && distributionSystem > 0) {
int voltage = distributionSystem == 2 ? 400 : 230;
if(data.isThreePhase()) {
maxPwr = mainFuse * sqrt(3) * voltage;
} else if(data.isTwoPhase()) {
maxPwr = mainFuse * voltage;
} else {
maxPwr = mainFuse * 230;
}
}
IPAddress localIp;
IPAddress subnet;
IPAddress gateway;
IPAddress dns1;
IPAddress dns2;
if(ch == NULL) {
localIp = WiFi.localIP();
subnet = IPAddress(255,255,255,0);
gateway = WiFi.subnetMask();
dns1 = WiFi.dnsIP(0);
dns2 = WiFi.dnsIP(1);
} else {
localIp = ch->getIP();
subnet = ch->getSubnetMask();
gateway = ch->getGateway();
dns1 = ch->getDns(0);
dns2 = ch->getDns(1);
}
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, CC_JSON_INIT,
mac,
apmac,
FirmwareVersion::VersionString,
boardType,
rtc_get_reset_reason(0),
rdc == NULL ? 0 : rdc->last_cause,
tz == NULL ? 0 : (tz->toLocal(now)-now)/3600,
data.getMeterType(),
meterManufacturer(data.getMeterType()).c_str(),
data.getMeterModel().c_str(),
data.getMeterId().c_str(),
distributionSystemStr(distributionSystem).c_str(),
mainFuse,
maxPwr,
productionCapacity,
localIp.toString().c_str(),
subnet.toString().c_str(),
gateway.toString().c_str(),
dns1.toString().c_str(),
dns2.toString().c_str()
);
}
float vcc = 0.0;
int rssi = 0;
float temperature = -127;
if(hw != NULL) {
vcc = hw->getVcc();
rssi = hw->getWifiRssi();
temperature = hw->getTemperature();
}
uint8_t espStatus;
#if defined(ESP8266)
if(vcc < 2.0) { // Voltage not correct, ESP would not run on this voltage
espStatus = 1;
} else if(vcc > 2.8 && vcc < 3.5) {
espStatus = 1;
} else if(vcc > 2.7 && vcc < 3.6) {
espStatus = 2;
} else {
espStatus = 3;
}
#elif defined(ESP32)
if(vcc < 2.0) { // Voltage not correct, ESP would not run on this voltage
espStatus = 1;
} else if(vcc > 3.1 && vcc < 3.5) {
espStatus = 1;
} else if(vcc > 3.0 && vcc < 3.6) {
espStatus = 2;
} else {
espStatus = 3;
}
#endif
uint8_t hanStatus;
if(data.getLastError() != 0) {
hanStatus = 3;
} else if(data.getLastUpdateMillis() == 0 && now < 30000) {
hanStatus = 0;
} else if(now - data.getLastUpdateMillis() < 15000) {
hanStatus = 1;
} else if(now - data.getLastUpdateMillis() < 30000) {
hanStatus = 2;
} else {
hanStatus = 3;
}
uint8_t wifiStatus;
if(rssi > -75) {
wifiStatus = 1;
} else if(rssi > -95) {
wifiStatus = 2;
} else {
wifiStatus = 3;
}
uint8_t mqttStatus;
if(mqttHandler == NULL) {
mqttStatus = 0;
} else if(mqttHandler->connected()) {
mqttStatus = 1;
} else if(mqttHandler->lastError() == 0) {
mqttStatus = 2;
} else {
mqttStatus = 3;
}
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, PSTR(",\"data\":{\"clock\":%lu,\"up\":%lu,\"lastUpdate\":%lu,\"est\":%s"),
(uint32_t) time(nullptr),
(uint32_t) (millis64()/1000),
(uint32_t) (data.getLastUpdateMillis()/1000),
data.isCounterEstimated() ? "true" : "false"
);
if(data.getListType() > 2) {
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, CC_JSON_POWER_LIST3, "import", data.getActiveImportPower(), data.getReactiveImportPower(), data.getActiveImportCounter(), data.getReactiveImportCounter());
} else {
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, CC_JSON_POWER, "import", data.getActiveImportPower(), data.getReactiveImportPower());
}
if(data.getListType() > 2) {
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, CC_JSON_POWER_LIST3, "export", data.getActiveExportPower(), data.getReactiveExportPower(), data.getActiveExportCounter(), data.getReactiveExportCounter());
} else {
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, CC_JSON_POWER, "export", data.getActiveExportPower(), data.getReactiveExportPower());
}
if(data.getListType() > 1) {
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, PSTR(",\"phases\":{"));
bool first = true;
if(data.getL1Voltage() > 0.0) {
if(data.getListType() > 3) {
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, CC_JSON_PHASE_LIST4, first ? "" : ",", 1, data.getL1Voltage(), String(data.getL1Current(), 2).c_str(), data.getL1ActiveImportPower(), data.getL1ActiveExportPower(), data.getL1PowerFactor());
} else {
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, CC_JSON_PHASE, first ? "" : ",", 1, data.getL1Voltage(), String(data.getL1Current(), 2).c_str());
}
first = false;
}
if(data.getL2Voltage() > 0.0) {
if(data.getListType() > 3) {
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, CC_JSON_PHASE_LIST4, first ? "" : ",", 2, data.getL2Voltage(), String(data.getL2Current(), 2).c_str(), data.getL2ActiveImportPower(), data.getL2ActiveExportPower(), data.getL2PowerFactor());
} else {
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, CC_JSON_PHASE, first ? "" : ",", 2, data.getL2Voltage(), data.isL2currentMissing() ? "null" : String(data.getL2Current(), 2).c_str());
}
first = false;
}
if(data.getL3Voltage() > 0.0) {
if(data.getListType() > 3) {
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, CC_JSON_PHASE_LIST4, first ? "" : ",", 3, data.getL3Voltage(), String(data.getL3Current(), 2).c_str(), data.getL3ActiveImportPower(), data.getL3ActiveExportPower(), data.getL3PowerFactor());
} else {
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, CC_JSON_PHASE, first ? "" : ",", 3, data.getL3Voltage(), String(data.getL3Current(), 2).c_str());
}
first = false;
}
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, PSTR("}"));
}
if(data.getListType() > 3) {
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, PSTR(",\"pf\":%.2f"), data.getPowerFactor());
}
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, PSTR(",\"realtime\":{\"import\":%.3f,\"export\":%.3f}"), ea.getUseThisHour(), ea.getProducedThisHour());
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, PSTR(",\"vcc\":%.2f,\"temp\":%.2f,\"rssi\":%d,\"free\":%d"), vcc, temperature, rssi, ESP.getFreeHeap());
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, CC_JSON_STATUS,
espStatus, 0,
hanStatus, data.getLastError(),
wifiStatus, 0,
mqttStatus, mqttHandler == NULL ? 0 : mqttHandler->lastError()
);
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, PSTR("}"));
uint16_t crc = crc16((uint8_t*) clearBuffer, pos);
pos += snprintf_P(clearBuffer+pos, CC_BUF_SIZE-pos, PSTR(",\"crc\":\"%04X\"}"), crc);
if(rsa == nullptr) return;
int ret = mbedtls_rsa_check_pubkey(rsa);
if(ret != 0) {
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("mbedtls_rsa_pkcs1_encrypt return code: %d\n"), ret);
mbedtls_strerror(ret, clearBuffer, CC_BUF_SIZE);
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("%s\n"), clearBuffer);
return;
}
memset(encryptedBuffer, 0, rsa->len);
int maxlen = 100 * (rsa->len/128);
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf("(CloudConnector) Sending %d bytes and maxlen %d\n", pos, maxlen);
udp.beginPacket(config.hostname,7443);
for(int i = 0; i < pos; i += maxlen) {
int size = min(maxlen, pos-i);
int ret = mbedtls_rsa_pkcs1_encrypt(rsa, mbedtls_ctr_drbg_random, &ctr_drbg, MBEDTLS_RSA_PUBLIC, size, (unsigned char*) (clearBuffer+i), encryptedBuffer);
if(ret == 0) {
udp.write(encryptedBuffer, rsa->len);
delay(1);
} else {
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("mbedtls_rsa_pkcs1_encrypt return code: %d\n"), ret);
mbedtls_strerror(ret, clearBuffer, CC_BUF_SIZE);
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("%s\n"), clearBuffer);
}
}
udp.endPacket();
lastUpdate = now;
}
void CloudConnector::forceUpdate() {
lastUpdate = 0;
}
void CloudConnector::setTimezone(Timezone* tz) {
this->tz = tz;
}
void CloudConnector::setConnectionHandler(ConnectionHandler* ch) {
this->ch = ch;
}
void CloudConnector::debugPrint(byte *buffer, int start, int length) {
for (int i = start; i < start + length; i++) {
if (buffer[i] < 0x10)
debugger->print(F("0"));
debugger->print(buffer[i], HEX);
debugger->print(F(" "));
if ((i - start + 1) % 16 == 0)
debugger->println(F(""));
else if ((i - start + 1) % 4 == 0)
debugger->print(F(" "));
yield(); // Let other get some resources too
}
debugger->println(F(""));
}

View File

@@ -1,48 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _CONNECTIONHANDLER_H
#define _CONNECTIONHANDLER_H
#include "AmsConfiguration.h"
#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
esp_netif_t* get_esp_interface_netif(esp_interface_t interface);
#endif
#define NETWORK_MODE_WIFI_CLIENT 1
#define NETWORK_MODE_WIFI_AP 2
#define NETWORK_MODE_ETH_CLIENT 3
class ConnectionHandler {
public:
virtual ~ConnectionHandler() {};
virtual bool connect(NetworkConfig config, SystemConfig sys);
virtual void disconnect(unsigned long reconnectDelay);
virtual bool isConnected();
virtual bool isConfigChanged();
virtual void getCurrentConfig(NetworkConfig& networkConfig);
virtual IPAddress getIP();
virtual IPAddress getSubnetMask();
virtual IPAddress getGateway();
virtual IPAddress getDns(uint8_t idx);
#if defined(ESP32)
virtual IPv6Address getIPv6();
virtual IPv6Address getDNSv6(uint8_t idx);
virtual void eventHandler(WiFiEvent_t event, WiFiEventInfo_t info);
#endif
uint8_t getMode() {
return this->mode;
}
protected:
uint8_t mode;
};
#endif

View File

@@ -1,49 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _ETHERNETCONNECTIONHANDLER_H
#define _ETHERNETCONNECTIONHANDLER_H
#include "ConnectionHandler.h"
#include <Arduino.h>
#include "RemoteDebug.h"
#define CONNECTION_TIMEOUT 30000
class EthernetConnectionHandler : public ConnectionHandler {
public:
EthernetConnectionHandler(RemoteDebug* debugger);
bool connect(NetworkConfig config, SystemConfig sys);
void disconnect(unsigned long reconnectDelay);
bool isConnected();
bool isConfigChanged();
void getCurrentConfig(NetworkConfig& networkConfig);
IPAddress getIP();
IPAddress getSubnetMask();
IPAddress getGateway();
IPAddress getDns(uint8_t idx);
#if defined(ESP32)
IPv6Address getIPv6();
IPv6Address getDNSv6(uint8_t idx);
void eventHandler(WiFiEvent_t event, WiFiEventInfo_t info);
#endif
private:
RemoteDebug* debugger;
NetworkConfig config;
bool connected = false;
bool configChanged = false;
unsigned long timeout = CONNECTION_TIMEOUT;
unsigned long lastRetry = 0;
int8_t ethPowerPin = -1;
uint8_t ethEnablePin = 0;
};
#endif

View File

@@ -1,44 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _WIFIACCESSPOINTCONNECTIONHANDLER_H
#define _WIFIACCESSPOINTCONNECTIONHANDLER_H
#include "ConnectionHandler.h"
#include <Arduino.h>
#include "RemoteDebug.h"
#include <DNSServer.h>
class WiFiAccessPointConnectionHandler : public ConnectionHandler {
public:
WiFiAccessPointConnectionHandler(RemoteDebug* debugger);
bool connect(NetworkConfig config, SystemConfig sys);
void disconnect(unsigned long reconnectDelay);
bool isConnected();
bool isConfigChanged();
void getCurrentConfig(NetworkConfig& networkConfig);
IPAddress getIP();
IPAddress getSubnetMask();
IPAddress getGateway();
IPAddress getDns(uint8_t idx);
#if defined(ESP32)
IPv6Address getIPv6();
IPv6Address getDNSv6(uint8_t idx);
void eventHandler(WiFiEvent_t event, WiFiEventInfo_t info);
#endif
private:
RemoteDebug* debugger;
NetworkConfig config;
DNSServer dnsServer;
bool connected = false;
bool configChanged = false;
};
#endif

View File

@@ -1,56 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _WIFICLIENTCONNECTIONHANDLER_H
#define _WIFICLIENTCONNECTIONHANDLER_H
#include "ConnectionHandler.h"
#include <Arduino.h>
#include "RemoteDebug.h"
#define CONNECTION_TIMEOUT 30000
#define RECONNECT_TIMEOUT 5000
#if defined(ESP32)
esp_err_t set_esp_interface_ip(esp_interface_t interface, IPAddress local_ip=INADDR_NONE, IPAddress gateway=INADDR_NONE, IPAddress subnet=INADDR_NONE, IPAddress dhcp_lease_start=INADDR_NONE);
#endif
class WiFiClientConnectionHandler : public ConnectionHandler {
public:
WiFiClientConnectionHandler(RemoteDebug* debugger);
bool connect(NetworkConfig config, SystemConfig sys);
void disconnect(unsigned long reconnectDelay);
bool isConnected();
bool isConfigChanged();
void getCurrentConfig(NetworkConfig& networkConfig);
IPAddress getIP();
IPAddress getSubnetMask();
IPAddress getGateway();
IPAddress getDns(uint8_t idx);
#if defined(ESP32)
IPv6Address getIPv6();
IPv6Address getDNSv6(uint8_t idx);
void eventHandler(WiFiEvent_t event, WiFiEventInfo_t info);
#endif
private:
RemoteDebug* debugger;
NetworkConfig config;
bool busPowered = false;
bool firstConnect = true;
bool configChanged = false;
unsigned long timeout = CONNECTION_TIMEOUT;
unsigned long lastRetry = 0;
wl_status_t begin(const char* ssid, const char* psk);
#if defined(ESP32)
void wifi_sta_config(wifi_config_t * wifi_config, const char * ssid=NULL, const char * password=NULL, const uint8_t * bssid=NULL, uint8_t channel=0, wifi_auth_mode_t min_security=WIFI_AUTH_WPA2_PSK, wifi_scan_method_t scan_method=WIFI_ALL_CHANNEL_SCAN, wifi_sort_method_t sort_method=WIFI_CONNECT_AP_BY_SIGNAL, uint16_t listen_interval=0, bool pmf_required=false);
#endif
};
#endif

View File

@@ -1,223 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "EthernetConnectionHandler.h"
#if defined(ESP32)
#include <ETH.h>
#include <esp_wifi.h>
#include <lwip/dns.h>
#endif
EthernetConnectionHandler::EthernetConnectionHandler(RemoteDebug* debugger) {
this->debugger = debugger;
this->mode = NETWORK_MODE_ETH_CLIENT;
}
bool EthernetConnectionHandler::connect(NetworkConfig config, SystemConfig sys) {
if(lastRetry > 0 && (millis() - lastRetry) < timeout) {
delay(50);
return false;
}
lastRetry = millis();
#if defined(ESP32)
if (!connected) {
eth_phy_type_t ethType = ETH_PHY_LAN8720;
eth_clock_mode_t ethClkMode = ETH_CLOCK_GPIO0_IN;
uint8_t ethAddr = 0;
uint8_t ethMdc = 0;
uint8_t ethMdio = 0;
if(sys.boardType == 241) { // LilyGO T-ETH-POE
ethType = ETH_PHY_LAN8720;
ethEnablePin = -1;
ethAddr = 0;
ethClkMode = ETH_CLOCK_GPIO17_OUT;
ethPowerPin = 5;
ethMdc = 23;
ethMdio = 18;
} else if(sys.boardType == 242) { // M5 PoESP32
ethType = ETH_PHY_IP101;
ethEnablePin = -1;
ethAddr = 1;
ethClkMode = ETH_CLOCK_GPIO0_IN;
ethPowerPin = 5;
ethMdc = 23;
ethMdio = 18;
} else if(sys.boardType == 243) { // WT32-ETH01
ethType = ETH_PHY_LAN8720;
ethEnablePin = -1;
ethAddr = 1;
ethClkMode = ETH_CLOCK_GPIO17_OUT;
ethPowerPin = 16;
ethMdc = 23;
ethMdio = 18;
} else if(sys.boardType == 244) {
if (debugger->isActive(RemoteDebug::DEBUG)) debugger->printf_P(PSTR("LilyGO T-ETH-Lite\n"));
return false; // TODO
} else {
if (debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("Board type %d incompatible with ETH\n"), sys.boardType);
return false;
}
if(ethEnablePin > 0) {
pinMode(ethEnablePin, OUTPUT);
digitalWrite(ethEnablePin, 1);
}
if (debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("Connecting to Ethernet\n"));
if(ETH.begin(ethAddr, ethPowerPin, ethMdc, ethMdio, ethType, ethClkMode)) {
#if defined(ESP32)
if(strlen(config.hostname) > 0) {
ETH.setHostname(config.hostname);
}
#endif
if(strlen(config.ip) > 0) {
IPAddress ip, gw, sn(255,255,255,0), dns1, dns2;
ip.fromString(config.ip);
gw.fromString(config.gateway);
sn.fromString(config.subnet);
if(strlen(config.dns1) > 0) {
dns1.fromString(config.dns1);
} else if(strlen(config.gateway) > 0) {
dns1.fromString(config.gateway); // If no DNS, set gateway by default
}
if(strlen(config.dns2) > 0) {
dns2.fromString(config.dns2);
} else if(dns1.toString().isEmpty()) {
dns2.fromString(F("208.67.220.220")); // Add OpenDNS as second by default if nothing is configured
}
if(!ETH.config(ip, gw, sn, dns1, dns2)) {
debugger->printf_P(PSTR("Static IP configuration is invalid, not using\n"));
}
}
} else {
if (debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("Unable to start Ethernet\n"));
}
}
#endif
return false;
}
void EthernetConnectionHandler::disconnect(unsigned long reconnectDelay) {
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("Disconnecting!\n"));
}
bool EthernetConnectionHandler::isConnected() {
return connected;
}
#if defined(ESP32)
void EthernetConnectionHandler::eventHandler(WiFiEvent_t event, WiFiEventInfo_t info) {
switch(event) {
case ARDUINO_EVENT_ETH_CONNECTED:
connected = true;
if(debugger->isActive(RemoteDebug::INFO)) {
debugger->printf_P(PSTR("Successfully connected to Ethernet!\n"));
}
break;
case ARDUINO_EVENT_ETH_GOT_IP:
if(debugger->isActive(RemoteDebug::INFO)) {
debugger->printf_P(PSTR("IP: %s\n"), getIP().toString().c_str());
debugger->printf_P(PSTR("GW: %s\n"), getGateway().toString().c_str());
for(uint8_t i = 0; i < 3; i++) {
IPAddress dns4 = getDns(i);
if(!dns4.isAny()) debugger->printf_P(PSTR("DNS: %s\n"), dns4.toString().c_str());
}
}
break;
case ARDUINO_EVENT_ETH_GOT_IP6: {
if(debugger->isActive(RemoteDebug::INFO)) {
IPv6Address ipv6 = getIPv6();
if(ipv6 == IPv6Address()) {
// No IP
} else {
debugger->printf_P(PSTR("IPv6: %s\n"), ipv6.toString().c_str());
}
for(uint8_t i = 0; i < 3; i++) {
IPv6Address dns6 = getDNSv6(i);
if(dns6 == IPv6Address()) {
// No IP
} else {
debugger->printf_P(PSTR("DNSv6: %s\n"), dns6.toString().c_str());
}
}
}
break;
}
case ARDUINO_EVENT_ETH_DISCONNECTED:
connected = false;
if(debugger->isActive(RemoteDebug::WARNING)) {
debugger->printf_P(PSTR("Ethernet was disconnected!\n"));
}
break;
}
}
#endif
bool EthernetConnectionHandler::isConfigChanged() {
return configChanged;
}
void EthernetConnectionHandler::getCurrentConfig(NetworkConfig& networkConfig) {
networkConfig = this->config;
}
IPAddress EthernetConnectionHandler::getIP() {
#if defined(ESP32)
return ETH.localIP();
#else
return NULL;
#endif
}
IPAddress EthernetConnectionHandler::getSubnetMask() {
#if defined(ESP32)
return ETH.subnetMask();
#else
return NULL;
#endif
}
IPAddress EthernetConnectionHandler::getGateway() {
#if defined(ESP32)
return ETH.gatewayIP();
#else
return NULL;
#endif
}
IPAddress EthernetConnectionHandler::getDns(uint8_t idx) {
#if defined(ESP32)
return ETH.dnsIP(idx);
#else
return NULL;
#endif
}
#if defined(ESP32)
IPv6Address EthernetConnectionHandler::getIPv6() {
esp_ip6_addr_t addr;
if(esp_netif_get_ip6_global(get_esp_interface_netif(ESP_IF_ETH), &addr) == ESP_OK) {
return IPv6Address(addr.addr);
}
return IPv6Address();
}
IPv6Address EthernetConnectionHandler::getDNSv6(uint8_t idx) {
for(uint8_t i = 0; i < 3; i++) {
const ip_addr_t * dns = dns_getserver(i);
if(dns->type == IPADDR_TYPE_V6) {
if(idx-- == 0) return IPv6Address(dns->u_addr.ip6.addr);
}
}
return IPv6Address();
}
#endif

View File

@@ -1,102 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "WiFiAccessPointConnectionHandler.h"
WiFiAccessPointConnectionHandler::WiFiAccessPointConnectionHandler(RemoteDebug* debugger) {
this->debugger = debugger;
this->mode = NETWORK_MODE_WIFI_AP;
}
bool WiFiAccessPointConnectionHandler::connect(NetworkConfig config, SystemConfig sys) {
//wifi_softap_set_dhcps_offer_option(OFFER_ROUTER, 0); // Disable default gw
WiFi.mode(WIFI_AP);
WiFi.softAP(config.ssid, config.psk);
dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
dnsServer.start(53, PSTR("*"), WiFi.softAPIP());
connected = true;
return true;
}
void WiFiAccessPointConnectionHandler::disconnect(unsigned long reconnectDelay) {
WiFi.disconnect(true);
WiFi.softAPdisconnect(true);
WiFi.enableAP(false);
WiFi.mode(WIFI_OFF);
yield();
}
bool WiFiAccessPointConnectionHandler::isConnected() {
return connected;
}
#if defined(ESP32)
void WiFiAccessPointConnectionHandler::eventHandler(WiFiEvent_t event, WiFiEventInfo_t info) {
uint8_t mac[6];
IPAddress stationIP;
switch(event) {
case ARDUINO_EVENT_WIFI_AP_START:
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("WiFi access point started with SSID %s\n"), config.ssid);
break;
case ARDUINO_EVENT_WIFI_AP_STOP:
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("WiFi access point stopped!\n"));
break;
case ARDUINO_EVENT_WIFI_AP_STACONNECTED:
memcpy(mac, info.wifi_ap_staconnected.mac, 6);
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("Client connected to AP, client MAC: %02x:%02x:%02x:%02x:%02x:%02x\n"), mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
break;
case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED:
memcpy(mac, info.wifi_ap_staconnected.mac, 6);
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("Client disconnected from AP, client MAC: %02x:%02x:%02x:%02x:%02x:%02x\n"), mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
break;
case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED:
stationIP = info.wifi_ap_staipassigned.ip.addr;
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("Client was assigned IP %s\n"), stationIP.toString().c_str());
break;
}
}
#endif
bool WiFiAccessPointConnectionHandler::isConfigChanged() {
return configChanged;
}
void WiFiAccessPointConnectionHandler::getCurrentConfig(NetworkConfig& networkConfig) {
networkConfig = this->config;
}
IPAddress WiFiAccessPointConnectionHandler::getIP() {
return WiFi.softAPIP();
}
IPAddress WiFiAccessPointConnectionHandler::getSubnetMask() {
#if defined(ESP32)
return WiFi.softAPSubnetMask();
#else
return IPAddress(255,255,255,0);
#endif
}
IPAddress WiFiAccessPointConnectionHandler::getGateway() {
return WiFi.softAPIP();
}
IPAddress WiFiAccessPointConnectionHandler::getDns(uint8_t idx) {
return WiFi.softAPIP();
}
#if defined(ESP32)
IPv6Address WiFiAccessPointConnectionHandler::getIPv6() {
return IPv6Address();
}
IPv6Address WiFiAccessPointConnectionHandler::getDNSv6(uint8_t idx) {
return IPv6Address();
}
#endif

View File

@@ -1,389 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "WiFiClientConnectionHandler.h"
#if defined(ESP32)
#include <esp_wifi.h>
#include <lwip/dns.h>
#endif
WiFiClientConnectionHandler::WiFiClientConnectionHandler(RemoteDebug* debugger) {
this->debugger = debugger;
this->mode = NETWORK_MODE_WIFI_CLIENT;
}
bool WiFiClientConnectionHandler::connect(NetworkConfig config, SystemConfig sys) {
if(lastRetry > 0 && (millis() - lastRetry) < timeout) {
delay(50);
return false;
}
lastRetry = millis();
if (WiFi.status() != WL_CONNECTED) {
if(config.mode != this->mode || strlen(config.ssid) == 0) {
return false;
}
if(WiFi.getMode() != WIFI_OFF) {
if (debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("Not connected to WiFi, closing resources\n"));
disconnect(RECONNECT_TIMEOUT);
return false;
}
timeout = CONNECTION_TIMEOUT;
if (debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("Connecting to WiFi network: %s\n"), config.ssid);
switch(sys.boardType) {
case 2: // spenceme
case 3: // Pow-K UART0
case 4: // Pow-U UART0
case 5: // Pow-K+
case 6: // Pow-P1
case 7: // Pow-U+
case 8: // dbeinder: HAN mosquito
busPowered = true;
break;
default:
busPowered = false;
}
firstConnect = sys.dataCollectionConsent == 0;
#if defined(ESP32)
if(strlen(config.hostname) > 0) {
WiFi.setHostname(config.hostname);
}
#endif
WiFi.mode(WIFI_STA);
if(strlen(config.ip) > 0) {
IPAddress ip, gw, sn(255,255,255,0), dns1, dns2;
ip.fromString(config.ip);
gw.fromString(config.gateway);
sn.fromString(config.subnet);
if(strlen(config.dns1) > 0) {
dns1.fromString(config.dns1);
} else if(strlen(config.gateway) > 0) {
dns1.fromString(config.gateway); // If no DNS, set gateway by default
}
if(strlen(config.dns2) > 0) {
dns2.fromString(config.dns2);
} else if(dns1.toString().isEmpty()) {
dns2.fromString(F("208.67.220.220")); // Add OpenDNS as second by default if nothing is configured
}
if(!WiFi.config(ip, gw, sn, dns1, dns2)) {
debugger->printf_P(PSTR("Static IP configuration is invalid, not using\n"));
}
}
#if defined(ESP8266)
if(strlen(config.hostname) > 0) {
WiFi.hostname(config.hostname);
}
//wifi_set_phy_mode(PHY_MODE_11N);
if(!config.use11b) {
wifi_set_user_sup_rate(RATE_11G6M, RATE_11G54M);
wifi_set_user_rate_limit(RC_LIMIT_11G, 0x00, RATE_11G_G54M, RATE_11G_G6M);
wifi_set_user_rate_limit(RC_LIMIT_11N, 0x00, RATE_11N_MCS7S, RATE_11N_MCS0);
wifi_set_user_limit_rate_mask(LIMIT_RATE_MASK_ALL);
}
#endif
WiFi.setAutoReconnect(true);
#if defined(ESP32)
if(begin(config.ssid, config.psk)) {
#else
if(WiFi.begin(config.ssid, config.psk)) {
#endif
if(config.sleep <= 2) {
switch(config.sleep) {
case 0:
WiFi.setSleep(WIFI_PS_NONE);
break;
case 1:
WiFi.setSleep(WIFI_PS_MIN_MODEM);
break;
case 2:
WiFi.setSleep(WIFI_PS_MAX_MODEM);
break;
}
}
yield();
} else {
if (debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("Unable to start WiFi\n"));
}
this->config = config;
return true;
}
return false;
}
#if defined(ESP32)
wl_status_t WiFiClientConnectionHandler::begin(const char* ssid, const char* passphrase) {
if(!WiFi.enableSTA(true)) {
log_e("STA enable failed!");
return WL_CONNECT_FAILED;
}
if(!ssid || *ssid == 0x00 || strlen(ssid) > 32) {
log_e("SSID too long or missing!");
return WL_CONNECT_FAILED;
}
if(passphrase && strlen(passphrase) > 64) {
log_e("passphrase too long!");
return WL_CONNECT_FAILED;
}
wifi_config_t conf;
memset(&conf, 0, sizeof(wifi_config_t));
wifi_sta_config(&conf, ssid, passphrase, NULL, 0, WIFI_AUTH_WPA2_PSK, WIFI_ALL_CHANNEL_SCAN, WIFI_CONNECT_AP_BY_SIGNAL);
wifi_config_t current_conf;
if(esp_wifi_get_config((wifi_interface_t)ESP_IF_WIFI_STA, &current_conf) != ESP_OK){
log_e("get current config failed!");
return WL_CONNECT_FAILED;
}
if(memcmp(&current_conf, &conf, sizeof(wifi_config_t)) == 0) {
if(esp_wifi_disconnect()){
log_e("disconnect failed!");
return WL_CONNECT_FAILED;
}
if(esp_wifi_set_config((wifi_interface_t)ESP_IF_WIFI_STA, &conf) != ESP_OK){
log_e("set config failed!");
return WL_CONNECT_FAILED;
}
} else if(WiFi.status() == WL_CONNECTED){
return WL_CONNECTED;
} else {
if(esp_wifi_set_config((wifi_interface_t)ESP_IF_WIFI_STA, &conf) != ESP_OK){
log_e("set config failed!");
return WL_CONNECT_FAILED;
}
}
if(strlen(config.ip) > 0){
if(set_esp_interface_ip(ESP_IF_WIFI_STA) != ESP_OK) {
return WL_CONNECT_FAILED;
}
}
if(esp_wifi_connect() != ESP_OK) {
log_e("connect failed!");
return WL_CONNECT_FAILED;
}
return WiFi.status();
}
void WiFiClientConnectionHandler::wifi_sta_config(wifi_config_t * wifi_config, const char * ssid, const char * password, const uint8_t * bssid, uint8_t channel, wifi_auth_mode_t min_security, wifi_scan_method_t scan_method, wifi_sort_method_t sort_method, uint16_t listen_interval, bool pmf_required){
wifi_config->sta.channel = channel;
wifi_config->sta.listen_interval = listen_interval;
wifi_config->sta.scan_method = scan_method;//WIFI_ALL_CHANNEL_SCAN or WIFI_FAST_SCAN
wifi_config->sta.sort_method = sort_method;//WIFI_CONNECT_AP_BY_SIGNAL or WIFI_CONNECT_AP_BY_SECURITY
wifi_config->sta.threshold.rssi = -127;
wifi_config->sta.pmf_cfg.capable = true;
wifi_config->sta.pmf_cfg.required = pmf_required;
wifi_config->sta.bssid_set = 0;
memset(wifi_config->sta.bssid, 0, 6);
wifi_config->sta.threshold.authmode = WIFI_AUTH_OPEN;
wifi_config->sta.ssid[0] = 0;
wifi_config->sta.password[0] = 0;
if(ssid != NULL && ssid[0] != 0){
strncpy((char*)wifi_config->sta.ssid, ssid, 32);
if(password != NULL && password[0] != 0){
wifi_config->sta.threshold.authmode = min_security;
strncpy((char*)wifi_config->sta.password, password, 64);
}
if(bssid != NULL){
wifi_config->sta.bssid_set = 1;
memcpy(wifi_config->sta.bssid, bssid, 6);
}
}
wifi_config->sta.rm_enabled = true;
wifi_config->sta.btm_enabled = true;
wifi_config->sta.mbo_enabled = true;
}
#endif
void WiFiClientConnectionHandler::disconnect(unsigned long reconnectDelay) {
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("Disconnecting!\n"));
#if defined(ESP8266)
WiFiClient::stopAll();
#endif
WiFi.disconnect(true);
WiFi.softAPdisconnect(true);
WiFi.enableAP(false);
WiFi.mode(WIFI_OFF);
yield();
timeout = reconnectDelay;
}
bool WiFiClientConnectionHandler::isConnected() {
return WiFi.status() == WL_CONNECTED;
}
#if defined(ESP32)
void WiFiClientConnectionHandler::eventHandler(WiFiEvent_t event, WiFiEventInfo_t info) {
switch(event) {
case ARDUINO_EVENT_WIFI_READY:
if (!config.use11b) {
esp_wifi_config_11b_rate(WIFI_IF_AP, true);
esp_wifi_config_11b_rate(WIFI_IF_STA, true);
}
break;
case ARDUINO_EVENT_WIFI_STA_CONNECTED:
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("Successfully connected to WiFi!\n"));
if(config.ipv6 && !WiFi.enableIpV6()) {
debugger->printf_P(PSTR("Unable to enable IPv6\n"));
}
#if defined(ESP32)
if(firstConnect && config.use11b) {
// If first boot and phyMode is better than 11b, disable 11b for BUS powered devices
if(busPowered) {
wifi_phy_mode_t phyMode;
if(esp_wifi_sta_get_negotiated_phymode(&phyMode) == ESP_OK) {
if(phyMode > WIFI_PHY_MODE_11B) {
if (debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("WiFi supports better rates than 802.11b, disabling\n"));
config.use11b = false;
configChanged = true;
return;
}
}
}
}
if(config.power >= 195)
WiFi.setTxPower(WIFI_POWER_19_5dBm);
else if(config.power >= 190)
WiFi.setTxPower(WIFI_POWER_19dBm);
else if(config.power >= 185)
WiFi.setTxPower(WIFI_POWER_18_5dBm);
else if(config.power >= 170)
WiFi.setTxPower(WIFI_POWER_17dBm);
else if(config.power >= 150)
WiFi.setTxPower(WIFI_POWER_15dBm);
else if(config.power >= 130)
WiFi.setTxPower(WIFI_POWER_13dBm);
else if(config.power >= 110)
WiFi.setTxPower(WIFI_POWER_11dBm);
else if(config.power >= 85)
WiFi.setTxPower(WIFI_POWER_8_5dBm);
else if(config.power >= 70)
WiFi.setTxPower(WIFI_POWER_7dBm);
else if(config.power >= 50)
WiFi.setTxPower(WIFI_POWER_5dBm);
else if(config.power >= 20)
WiFi.setTxPower(WIFI_POWER_2dBm);
else
WiFi.setTxPower(WIFI_POWER_MINUS_1dBm);
#elif defined(ESP8266)
WiFi.setOutputPower(config.power / 10.0);
#endif
break;
case ARDUINO_EVENT_WIFI_STA_GOT_IP: {
if(debugger->isActive(RemoteDebug::INFO)) {
debugger->printf_P(PSTR("IP: %s\n"), getIP().toString().c_str());
debugger->printf_P(PSTR("GW: %s\n"), getGateway().toString().c_str());
for(uint8_t i = 0; i < 3; i++) {
IPAddress dns4 = getDns(i);
if(!dns4.isAny()) debugger->printf_P(PSTR("DNS: %s\n"), dns4.toString().c_str());
}
}
break;
}
case ARDUINO_EVENT_WIFI_STA_GOT_IP6: {
if(debugger->isActive(RemoteDebug::INFO)) {
IPv6Address ipv6 = getIPv6();
if(ipv6 == IPv6Address()) {
// No IP
} else {
debugger->printf_P(PSTR("IPv6: %s\n"), ipv6.toString().c_str());
}
for(uint8_t i = 0; i < 3; i++) {
IPv6Address dns6 = getDNSv6(i);
if(dns6 == IPv6Address()) {
// No IP
} else {
debugger->printf_P(PSTR("DNSv6: %s\n"), dns6.toString().c_str());
}
}
}
break;
}
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: {
wifi_err_reason_t reason = (wifi_err_reason_t) info.wifi_sta_disconnected.reason;
const char* descr = WiFi.disconnectReasonName(reason);
switch(reason) {
case WIFI_REASON_ASSOC_LEAVE:
break;
default:
if(strlen(descr) > 0) {
if(debugger->isActive(RemoteDebug::WARNING)) {
debugger->printf_P(PSTR("WiFi disconnected, reason %s\n"), descr);
}
disconnect(RECONNECT_TIMEOUT);
}
}
break;
}
}
}
#endif
bool WiFiClientConnectionHandler::isConfigChanged() {
return configChanged;
}
void WiFiClientConnectionHandler::getCurrentConfig(NetworkConfig& networkConfig) {
networkConfig = this->config;
}
IPAddress WiFiClientConnectionHandler::getIP() {
return WiFi.localIP();
}
IPAddress WiFiClientConnectionHandler::getSubnetMask() {
return WiFi.subnetMask();
}
IPAddress WiFiClientConnectionHandler::getGateway() {
return WiFi.gatewayIP();
}
IPAddress WiFiClientConnectionHandler::getDns(uint8_t idx) {
#if defined(ESP32)
for(uint8_t i = 0; i < 3; i++) {
const ip_addr_t * dns = dns_getserver(i);
if(dns->type == IPADDR_TYPE_V4) {
if(idx-- == 0) return IPAddress(dns->u_addr.ip4.addr);
}
}
#else
return WiFi.dnsIP(idx);
#endif
return IPAddress();
}
#if defined(ESP32)
IPv6Address WiFiClientConnectionHandler::getIPv6() {
esp_ip6_addr_t addr;
if(esp_netif_get_ip6_global(get_esp_interface_netif(ESP_IF_WIFI_STA), &addr) == ESP_OK) {
return IPv6Address(addr.addr);
}
return IPv6Address();
}
IPv6Address WiFiClientConnectionHandler::getDNSv6(uint8_t idx) {
for(uint8_t i = 0; i < 3; i++) {
const ip_addr_t * dns = dns_getserver(i);
if(dns->type == IPADDR_TYPE_V6) {
if(idx-- == 0) return IPv6Address(dns->u_addr.ip6.addr);
}
}
return IPv6Address();
}
#endif

View File

@@ -1 +0,0 @@
json/*.h

View File

@@ -1,33 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _DOMOTICZMQTTHANDLER_H
#define _DOMOTICZMQTTHANDLER_H
#include "AmsMqttHandler.h"
#include "AmsConfiguration.h"
class DomoticzMqttHandler : public AmsMqttHandler {
public:
DomoticzMqttHandler(MqttConfig& mqttConfig, RemoteDebug* debugger, char* buf, DomoticzConfig config) : AmsMqttHandler(mqttConfig, debugger, buf) {
this->config = config;
};
bool publish(AmsData* data, AmsData* previousState, EnergyAccounting* ea, PriceService* ps);
bool publishTemperatures(AmsConfiguration*, HwTools*);
bool publishPrices(PriceService*);
bool publishSystem(HwTools* hw, PriceService* ps, EnergyAccounting* ea);
bool publishRaw(String data);
void onMessage(String &topic, String &payload);
uint8_t getFormat();
private:
DomoticzConfig config;
double energy = 0.0;
};
#endif

View File

@@ -1,76 +0,0 @@
import os
import re
import shutil
import subprocess
try:
from css_html_js_minify import js_minify
except:
from SCons.Script import (
ARGUMENTS,
COMMAND_LINE_TARGETS,
DefaultEnvironment,
)
env = DefaultEnvironment()
env.Execute(
env.VerboseAction(
'$PYTHONEXE -m pip install "css_html_js_minify" ',
"Installing Python dependencies",
)
)
try:
from css_html_js_minify import js_minify
except:
print("WARN: Unable to load minifier")
webroot = "lib/DomoticzMqttHandler/json"
srcroot = "lib/DomoticzMqttHandler/include/json"
version = os.environ.get('GITHUB_TAG')
if version == None:
try:
result = subprocess.run(['git','rev-parse','--short','HEAD'], capture_output=True, check=False)
if result.returncode == 0:
version = result.stdout.decode('utf-8').strip()
else:
version = "SNAPSHOT"
except:
version = "SNAPSHOT"
if os.path.exists(srcroot):
shutil.rmtree(srcroot)
os.mkdir(srcroot)
else:
os.mkdir(srcroot)
for filename in os.listdir(webroot):
basename = re.sub("[^0-9a-zA-Z]+", "_", filename)
srcfile = webroot + "/" + filename
dstfile = srcroot + "/" + basename + ".h"
varname = basename.upper()
with open(srcfile, encoding="utf-8") as f:
content = f.read().replace("${version}", version)
try:
if (filename.endswith(".js") and filename != 'gaugemeter.js') or filename.endswith(".json"):
content = js_minify(content)
except:
print("WARN: Unable to minify")
with open(dstfile, "w") as dst:
dst.write("static const char ")
dst.write(varname)
dst.write("[] PROGMEM = R\"==\"==(")
dst.write(content)
dst.write(")==\"==\";\n")
dst.write("const int ");
dst.write(varname)
dst.write("_LEN PROGMEM = ");
dst.write(str(len(content)))
dst.write(";");

View File

@@ -1,140 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _ENERGYACCOUNTING_H
#define _ENERGYACCOUNTING_H
#include "Arduino.h"
#include "AmsData.h"
#include "AmsDataStorage.h"
#include "PriceService.h"
struct EnergyAccountingPeak {
uint8_t day;
uint16_t value;
};
struct EnergyAccountingData {
uint8_t version;
uint8_t month;
int32_t costYesterday;
int32_t costThisMonth;
int32_t costLastMonth;
int32_t incomeYesterday;
int32_t incomeThisMonth;
int32_t incomeLastMonth;
uint32_t lastMonthImport;
uint32_t lastMonthExport;
uint8_t lastMonthAccuracy;
EnergyAccountingPeak peaks[5];
};
struct EnergyAccountingData5 {
uint8_t version;
uint8_t month;
uint16_t costYesterday;
uint16_t costThisMonth;
uint16_t costLastMonth;
uint16_t incomeYesterday;
uint16_t incomeThisMonth;
uint16_t incomeLastMonth;
EnergyAccountingPeak peaks[5];
};
struct EnergyAccountingData4 {
uint8_t version;
uint8_t month;
uint16_t costYesterday;
uint16_t costThisMonth;
uint16_t costLastMonth;
EnergyAccountingPeak peaks[5];
};
struct EnergyAccountingData2 {
uint8_t version;
uint8_t month;
uint16_t maxHour;
uint16_t costYesterday;
uint16_t costThisMonth;
uint16_t costLastMonth;
};
struct EnergyAccountingRealtimeData {
uint8_t magic;
uint8_t currentHour;
uint8_t currentDay;
uint8_t currentThresholdIdx;
float use;
float costHour;
float costDay;
float produce;
float incomeHour;
float incomeDay;
unsigned long lastImportUpdateMillis;
unsigned long lastExportUpdateMillis;
};
class EnergyAccounting {
public:
EnergyAccounting(RemoteDebug*, EnergyAccountingRealtimeData*);
void setup(AmsDataStorage *ds, EnergyAccountingConfig *config);
void setPriceService(PriceService *ps);
void setTimezone(Timezone*);
EnergyAccountingConfig* getConfig();
bool update(AmsData* amsData);
bool load();
bool save();
bool isInitialized();
float getUseThisHour();
float getUseToday();
float getUseThisMonth();
float getUseLastMonth();
float getProducedThisHour();
float getProducedToday();
float getProducedThisMonth();
float getProducedLastMonth();
float getCostThisHour();
float getCostToday();
float getCostYesterday();
float getCostThisMonth();
float getCostLastMonth();
float getIncomeThisHour();
float getIncomeToday();
float getIncomeYesterday();
float getIncomeThisMonth();
float getIncomeLastMonth();
float getMonthMax();
uint8_t getCurrentThreshold();
EnergyAccountingPeak getPeak(uint8_t);
EnergyAccountingData getData();
void setData(EnergyAccountingData&);
void setCurrency(String currency);
float getPriceForHour(uint8_t d, uint8_t h);
private:
RemoteDebug* debugger = NULL;
bool init = false, initPrice = false;
AmsDataStorage *ds = NULL;
PriceService *ps = NULL;
EnergyAccountingConfig *config = NULL;
Timezone *tz = NULL;
EnergyAccountingData data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
EnergyAccountingRealtimeData* realtimeData = NULL;
String currency = "";
void calcDayCost();
bool updateMax(uint16_t val, uint8_t day);
};
#endif

View File

@@ -1,552 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "EnergyAccounting.h"
#include "LittleFS.h"
#include "AmsStorage.h"
#include "FirmwareVersion.h"
EnergyAccounting::EnergyAccounting(RemoteDebug* debugger, EnergyAccountingRealtimeData* rtd) {
data.version = 1;
this->debugger = debugger;
if(rtd->magic != 0x6A) {
rtd->magic = 0x6A;
rtd->currentHour = 0;
rtd->currentDay = 0;
rtd->currentThresholdIdx = 0;
rtd->use = 0;
rtd->costHour = 0;
rtd->costDay = 0;
rtd->produce = 0;
rtd->incomeHour = 0;
rtd->incomeDay = 0;
rtd->lastImportUpdateMillis = 0;
rtd->lastExportUpdateMillis = 0;
}
this->realtimeData = rtd;
}
void EnergyAccounting::setup(AmsDataStorage *ds, EnergyAccountingConfig *config) {
this->ds = ds;
this->config = config;
}
void EnergyAccounting::setPriceService(PriceService *ps) {
this->ps = ps;
}
EnergyAccountingConfig* EnergyAccounting::getConfig() {
return config;
}
void EnergyAccounting::setTimezone(Timezone* tz) {
this->tz = tz;
}
bool EnergyAccounting::isInitialized() {
return this->init;
}
bool EnergyAccounting::update(AmsData* amsData) {
if(config == NULL) return false;
time_t now = time(nullptr);
if(now < FirmwareVersion::BuildEpoch) return false;
if(tz == NULL) {
return false;
}
bool ret = false;
tmElements_t local;
breakTime(tz->toLocal(now), local);
if(!init) {
this->realtimeData->lastImportUpdateMillis = 0;
this->realtimeData->lastExportUpdateMillis = 0;
this->realtimeData->currentHour = local.Hour;
this->realtimeData->currentDay = local.Day;
if(!load()) {
data = { 6, local.Month,
0, 0, 0, // Cost
0, 0, 0, // Income
0, 0, 0, // Last month import, export and accuracy
0, 0, // Peak 1
0, 0, // Peak 2
0, 0, // Peak 3
0, 0, // Peak 4
0, 0 // Peak 5
};
}
init = true;
}
float price = getPriceForHour(PRICE_DIRECTION_IMPORT, 0);
if(!initPrice && price != PRICE_NO_VALUE) {
calcDayCost();
}
if(local.Hour != this->realtimeData->currentHour && (amsData->getListType() >= 3 || local.Minute == 1)) {
tmElements_t oneHrAgo, oneHrAgoLocal;
breakTime(now-3600, oneHrAgo);
uint16_t val = round(ds->getHourImport(oneHrAgo.Hour) / 10.0);
breakTime(tz->toLocal(now-3600), oneHrAgoLocal);
ret |= updateMax(val, oneHrAgoLocal.Day);
this->realtimeData->currentHour = local.Hour; // Need to be defined here so that day cost is correctly calculated
if(local.Hour > 0) {
calcDayCost();
}
this->realtimeData->use = 0;
this->realtimeData->produce = 0;
this->realtimeData->costHour = 0;
this->realtimeData->incomeHour = 0;
uint8_t prevDay = this->realtimeData->currentDay;
if(local.Day != this->realtimeData->currentDay) {
data.costYesterday = this->realtimeData->costDay * 100;
data.costThisMonth += this->realtimeData->costDay * 100;
this->realtimeData->costDay = 0;
data.incomeYesterday = this->realtimeData->incomeDay * 100;
data.incomeThisMonth += this->realtimeData->incomeDay * 100;
this->realtimeData->incomeDay = 0;
this->realtimeData->currentDay = local.Day;
ret = true;
}
if(local.Month != data.month) {
data.costLastMonth = data.costThisMonth;
data.costThisMonth = 0;
data.incomeLastMonth = data.incomeThisMonth;
data.incomeThisMonth = 0;
for(uint8_t i = 0; i < 5; i++) {
data.peaks[i] = { 0, 0 };
}
uint64_t totalImport = 0, totalExport = 0;
for(uint8_t i = 1; i <= prevDay; i++) {
totalImport += ds->getDayImport(i);
totalExport += ds->getDayExport(i);
}
uint8_t accuracy = 0;
uint64_t importUpdate = totalImport, exportUpdate = totalExport;
while(importUpdate > UINT32_MAX || exportUpdate > UINT32_MAX) {
accuracy++;
importUpdate = totalImport / pow(10, accuracy);
exportUpdate = totalExport / pow(10, accuracy);
}
data.lastMonthImport = importUpdate;
data.lastMonthExport = exportUpdate;
data.lastMonthAccuracy = accuracy;
data.month = local.Month;
this->realtimeData->currentThresholdIdx = 0;
ret = true;
}
}
if(this->realtimeData->lastImportUpdateMillis < amsData->getLastUpdateMillis()) {
unsigned long ms = amsData->getLastUpdateMillis() - this->realtimeData->lastImportUpdateMillis;
float kwhi = (amsData->getActiveImportPower() * (((float) ms) / 3600000.0)) / 1000.0;
if(kwhi > 0) {
this->realtimeData->use += kwhi;
if(price != PRICE_NO_VALUE) {
float cost = price * kwhi;
this->realtimeData->costHour += cost;
this->realtimeData->costDay += cost;
}
}
this->realtimeData->lastImportUpdateMillis = amsData->getLastUpdateMillis();
}
if(amsData->getListType() > 1 && this->realtimeData->lastExportUpdateMillis < amsData->getLastUpdateMillis()) {
unsigned long ms = amsData->getLastUpdateMillis() - this->realtimeData->lastExportUpdateMillis;
float kwhe = (amsData->getActiveExportPower() * (((float) ms) / 3600000.0)) / 1000.0;
if(kwhe > 0) {
this->realtimeData->produce += kwhe;
if(price != PRICE_NO_VALUE) {
float income = price * kwhe;
this->realtimeData->incomeHour += income;
this->realtimeData->incomeDay += income;
}
}
this->realtimeData->lastExportUpdateMillis = amsData->getLastUpdateMillis();
}
if(config != NULL) {
while(getMonthMax() > config->thresholds[this->realtimeData->currentThresholdIdx] && this->realtimeData->currentThresholdIdx < 10) this->realtimeData->currentThresholdIdx++;
}
return ret;
}
void EnergyAccounting::calcDayCost() {
time_t now = time(nullptr);
tmElements_t local, utc;
if(tz == NULL) return;
breakTime(tz->toLocal(now), local);
if(getPriceForHour(PRICE_DIRECTION_IMPORT, 0) != PRICE_NO_VALUE) {
if(initPrice) {
this->realtimeData->costDay = 0;
this->realtimeData->incomeDay = 0;
}
for(uint8_t i = 0; i < this->realtimeData->currentHour; i++) {
breakTime(now - ((local.Hour - i) * 3600), utc);
float priceIn = getPriceForHour(PRICE_DIRECTION_IMPORT, i - local.Hour);
if(priceIn != PRICE_NO_VALUE) {
int16_t wh = ds->getHourImport(utc.Hour);
this->realtimeData->costDay += priceIn * (wh / 1000.0);
}
float priceOut = getPriceForHour(PRICE_DIRECTION_EXPORT, i - local.Hour);
if(priceOut != PRICE_NO_VALUE) {
int16_t wh = ds->getHourExport(utc.Hour);
this->realtimeData->incomeDay += priceOut * (wh / 1000.0);
}
}
initPrice = true;
}
}
float EnergyAccounting::getUseThisHour() {
return this->realtimeData->use;
}
float EnergyAccounting::getUseToday() {
if(tz == NULL) return 0.0;
float ret = 0.0;
time_t now = time(nullptr);
if(now < FirmwareVersion::BuildEpoch) return 0.0;
tmElements_t utc, local;
breakTime(tz->toLocal(now), local);
for(uint8_t i = 0; i < this->realtimeData->currentHour; i++) {
breakTime(now - ((local.Hour - i) * 3600), utc);
ret += ds->getHourImport(utc.Hour) / 1000.0;
}
return ret + getUseThisHour();
}
float EnergyAccounting::getUseThisMonth() {
time_t now = time(nullptr);
if(now < FirmwareVersion::BuildEpoch) return 0.0;
float ret = 0;
for(uint8_t i = 1; i < this->realtimeData->currentDay; i++) {
ret += ds->getDayImport(i) / 1000.0;
}
return ret + getUseToday();
}
float EnergyAccounting::getUseLastMonth() {
return (data.lastMonthImport * pow(10, data.lastMonthAccuracy)) / 1000;
}
float EnergyAccounting::getProducedThisHour() {
return this->realtimeData->produce;
}
float EnergyAccounting::getProducedToday() {
if(tz == NULL) return 0.0;
float ret = 0.0;
time_t now = time(nullptr);
if(now < FirmwareVersion::BuildEpoch) return 0.0;
tmElements_t utc, local;
breakTime(tz->toLocal(now), local);
for(uint8_t i = 0; i < this->realtimeData->currentHour; i++) {
breakTime(now - ((local.Hour - i) * 3600), utc);
ret += ds->getHourExport(utc.Hour) / 1000.0;
}
return ret + getProducedThisHour();
}
float EnergyAccounting::getProducedThisMonth() {
time_t now = time(nullptr);
if(now < FirmwareVersion::BuildEpoch) return 0.0;
float ret = 0;
for(uint8_t i = 1; i < this->realtimeData->currentDay; i++) {
ret += ds->getDayExport(i) / 1000.0;
}
return ret + getProducedToday();
}
float EnergyAccounting::getProducedLastMonth() {
return (data.lastMonthExport * pow(10, data.lastMonthAccuracy)) / 1000;
}
float EnergyAccounting::getCostThisHour() {
return this->realtimeData->costHour;
}
float EnergyAccounting::getCostToday() {
return this->realtimeData->costDay;
}
float EnergyAccounting::getCostYesterday() {
return data.costYesterday / 100.0;
}
float EnergyAccounting::getCostThisMonth() {
return (data.costThisMonth / 100.0) + getCostToday();
}
float EnergyAccounting::getCostLastMonth() {
return data.costLastMonth / 100.0;
}
float EnergyAccounting::getIncomeThisHour() {
return this->realtimeData->incomeHour;
}
float EnergyAccounting::getIncomeToday() {
return this->realtimeData->incomeDay;
}
float EnergyAccounting::getIncomeYesterday() {
return data.incomeYesterday / 100.0;
}
float EnergyAccounting::getIncomeThisMonth() {
return (data.incomeThisMonth / 100.0) + getIncomeToday();
}
float EnergyAccounting::getIncomeLastMonth() {
return data.incomeLastMonth / 100.0;
}
uint8_t EnergyAccounting::getCurrentThreshold() {
if(config == NULL)
return 0;
return config->thresholds[this->realtimeData->currentThresholdIdx];
}
float EnergyAccounting::getMonthMax() {
if(config == NULL)
return 0.0;
uint8_t count = 0;
uint32_t maxHour = 0.0;
bool included[5] = { false, false, false, false, false };
for(uint8_t x = 0;x < min((uint8_t) 5, config->hours); x++) {
uint8_t maxIdx = 0;
uint16_t maxVal = 0;
for(uint8_t i = 0; i < 5; i++) {
if(included[i]) continue;
if(data.peaks[i].day == 0) continue;
if(data.peaks[i].value > maxVal) {
maxVal = data.peaks[i].value;
maxIdx = i;
}
}
if(maxVal > 0) {
included[maxIdx] = true;
count++;
}
}
for(uint8_t i = 0; i < 5; i++) {
if(!included[i]) continue;
maxHour += data.peaks[i].value;
}
return maxHour > 0 ? maxHour / count / 100.0 : 0.0;
}
EnergyAccountingPeak EnergyAccounting::getPeak(uint8_t num) {
if(config == NULL)
return EnergyAccountingPeak({0,0});
if(num < 1 || num > 5) return EnergyAccountingPeak({0,0});
uint8_t count = 0;
bool included[5] = { false, false, false, false, false };
for(uint8_t x = 0;x < min((uint8_t) 5, config->hours); x++) {
uint8_t maxIdx = 0;
uint16_t maxVal = 0;
for(uint8_t i = 0; i < 5; i++) {
if(included[i]) continue;
if(data.peaks[i].value > maxVal) {
maxVal = data.peaks[i].value;
maxIdx = i;
}
}
if(maxVal > 0) {
included[maxIdx] = true;
count++;
}
}
uint8_t pos = 0;
for(uint8_t i = 0; i < 5; i++) {
if(!included[i]) continue;
pos++;
if(pos == num) {
return data.peaks[i];
}
}
return EnergyAccountingPeak({0,0});
}
bool EnergyAccounting::load() {
if(!LittleFS.begin()) {
return false;
}
bool ret = false;
if(LittleFS.exists(FILE_ENERGYACCOUNTING)) {
File file = LittleFS.open(FILE_ENERGYACCOUNTING, "r");
char buf[file.size()];
file.readBytes(buf, file.size());
if(buf[0] == 6) {
EnergyAccountingData* data = (EnergyAccountingData*) buf;
memcpy(&this->data, data, sizeof(this->data));
ret = true;
} else if(buf[0] == 5) {
EnergyAccountingData5* data = (EnergyAccountingData5*) buf;
this->data = { 6, data->month,
((uint32_t) data->costYesterday) * 10,
((uint32_t) data->costThisMonth) * 100,
((uint32_t) data->costLastMonth) * 100,
((uint32_t) data->incomeYesterday) * 10,
((uint32_t) data->incomeThisMonth) * 100,
((uint32_t) data->incomeLastMonth) * 100,
0,0,0, // Last month import, export and accuracy
data->peaks[0].day, data->peaks[0].value,
data->peaks[1].day, data->peaks[1].value,
data->peaks[2].day, data->peaks[2].value,
data->peaks[3].day, data->peaks[3].value,
data->peaks[4].day, data->peaks[4].value
};
ret = true;
} else if(buf[0] == 4) {
EnergyAccountingData4* data = (EnergyAccountingData4*) buf;
this->data = { 5, data->month,
((uint32_t) data->costYesterday) * 10,
((uint32_t) data->costThisMonth) * 100,
((uint32_t) data->costLastMonth) * 100,
0,0,0, // Income from production
0,0,0, // Last month import, export and accuracy
data->peaks[0].day, data->peaks[0].value,
data->peaks[1].day, data->peaks[1].value,
data->peaks[2].day, data->peaks[2].value,
data->peaks[3].day, data->peaks[3].value,
data->peaks[4].day, data->peaks[4].value
};
ret = true;
} else if(buf[0] == 3) {
EnergyAccountingData* data = (EnergyAccountingData*) buf;
this->data = { 5, data->month,
data->costYesterday * 10,
data->costThisMonth,
data->costLastMonth,
0,0,0, // Income from production
0,0,0, // Last month import, export and accuracy
data->peaks[0].day, data->peaks[0].value,
data->peaks[1].day, data->peaks[1].value,
data->peaks[2].day, data->peaks[2].value,
data->peaks[3].day, data->peaks[3].value,
data->peaks[4].day, data->peaks[4].value
};
ret = true;
} else {
data = { 5, 0,
0, 0, 0, // Cost
0,0,0, // Income from production
0,0,0, // Last month import, export and accuracy
0, 0, // Peak 1
0, 0, // Peak 2
0, 0, // Peak 3
0, 0, // Peak 4
0, 0 // Peak 5
};
if(buf[0] == 2) {
EnergyAccountingData2* data = (EnergyAccountingData2*) buf;
this->data.month = data->month;
this->data.costYesterday = data->costYesterday * 10;
this->data.costThisMonth = data->costThisMonth;
this->data.costLastMonth = data->costLastMonth;
uint8_t b = 0;
for(uint8_t i = sizeof(this->data); i < file.size(); i+=2) {
this->data.peaks[b].day = b;
memcpy(&this->data.peaks[b].value, buf+i, 2);
b++;
if(b >= config->hours || b >= 5) break;
}
ret = true;
} else {
ret = false;
}
}
file.close();
}
return ret;
}
bool EnergyAccounting::save() {
if(!LittleFS.begin()) {
return false;
}
{
File file = LittleFS.open(FILE_ENERGYACCOUNTING, "w");
char buf[sizeof(data)];
memcpy(buf, &data, sizeof(data));
for(uint8_t i = 0; i < sizeof(buf); i++) {
file.write(buf[i]);
}
file.close();
}
return true;
}
EnergyAccountingData EnergyAccounting::getData() {
return this->data;
}
void EnergyAccounting::setData(EnergyAccountingData& data) {
this->data = data;
}
bool EnergyAccounting::updateMax(uint16_t val, uint8_t day) {
for(uint8_t i = 0; i < 5; i++) {
if(data.peaks[i].day == day || data.peaks[i].day == 0) {
if(val > data.peaks[i].value) {
data.peaks[i].day = day;
data.peaks[i].value = val;
return true;
}
return false;
}
}
uint16_t test = val;
uint8_t idx = 255;
for(uint8_t i = 0; i < 5; i++) {
if(val > data.peaks[i].value) {
if(test > data.peaks[i].value) {
test = data.peaks[i].value;
idx = i;
}
}
}
if(idx < 5) {
data.peaks[idx].value = val;
data.peaks[idx].day = day;
return true;
}
return false;
}
void EnergyAccounting::setCurrency(String currency) {
this->currency = currency;
}
float EnergyAccounting::getPriceForHour(uint8_t d, uint8_t h) {
if(ps == NULL) return PRICE_NO_VALUE;
return ps->getValueForHour(d, h);
}

View File

@@ -1,18 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _FIRMWARE_VERSION_h
#define _FIRMWARE_VERSION_h
class FirmwareVersion {
public:
static long BuildEpoch;
static const char* VersionString;
};
#endif

View File

@@ -1,11 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "FirmwareVersion.h"
#include "generated_version.h"
long FirmwareVersion::BuildEpoch = BUILD_EPOCH;
const char* FirmwareVersion::VersionString = VERSION_STRING;

View File

@@ -1 +0,0 @@
json/*.h

View File

@@ -1,189 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _HOMEASSISTANTMQTTHANDLER_H
#define _HOMEASSISTANTMQTTHANDLER_H
#include "AmsMqttHandler.h"
#include "HomeAssistantStatic.h"
#include "AmsConfiguration.h"
class HomeAssistantMqttHandler : public AmsMqttHandler {
public:
HomeAssistantMqttHandler(MqttConfig& mqttConfig, RemoteDebug* debugger, char* buf, uint8_t boardType, HomeAssistantConfig config, HwTools* hw) : AmsMqttHandler(mqttConfig, debugger, buf) {
this->hw = hw;
l1Init = l2Init = l2eInit = l3Init = l3eInit = l4Init = l4eInit = rtInit = rteInit = pInit = sInit = false;
topic = String(mqttConfig.publishTopic);
if(strlen(config.discoveryNameTag) > 0) {
snprintf_P(buf, 128, PSTR("AMS reader (%s)"), config.discoveryNameTag);
deviceName = String(buf);
snprintf_P(buf, 128, PSTR("[%s] "), config.discoveryNameTag);
sensorNamePrefix = String(buf);
} else {
deviceName = F("AMS reader");
sensorNamePrefix = "";
}
deviceModel = boardTypeToString(boardType);
manufacturer = boardManufacturerToString(boardType);
#if defined(ESP8266)
String hostname = WiFi.hostname();
#elif defined(ESP32)
String hostname = WiFi.getHostname();
#endif
deviceUid = hostname; // Maybe configurable in the future?
if(strlen(config.discoveryHostname) > 0) {
if(strncmp_P(config.discoveryHostname, PSTR("http"), 4) == 0) {
deviceUrl = String(config.discoveryHostname);
} else {
snprintf_P(buf, 128, PSTR("http://%s/"), config.discoveryHostname);
deviceUrl = String(buf);
}
} else {
snprintf_P(buf, 128, PSTR("http://%s.local/"), hostname);
deviceUrl = String(buf);
}
if(strlen(config.discoveryPrefix) > 0) {
snprintf_P(json, 128, PSTR("%s/status"), config.discoveryPrefix);
statusTopic = String(buf);
snprintf_P(buf, 128, PSTR("%s/sensor/"), config.discoveryPrefix);
discoveryTopic = String(buf);
} else {
statusTopic = F("homeassistant/status");
discoveryTopic = F("homeassistant/sensor/");
}
strcpy(this->mqttConfig.subscribeTopic, statusTopic.c_str());
};
bool publish(AmsData* data, AmsData* previousState, EnergyAccounting* ea, PriceService* ps);
bool publishTemperatures(AmsConfiguration*, HwTools*);
bool publishPrices(PriceService*);
bool publishSystem(HwTools* hw, PriceService* ps, EnergyAccounting* ea);
bool publishRaw(String data);
void onMessage(String &topic, String &payload);
uint8_t getFormat();
private:
String topic;
String deviceName;
String deviceModel;
String deviceUid;
String manufacturer;
String deviceUrl;
String statusTopic;
String discoveryTopic;
String sensorNamePrefix;
bool l1Init, l2Init, l2eInit, l3Init, l3eInit, l4Init, l4eInit, rtInit, rteInit, pInit, sInit;
bool tInit[32] = {false};
bool prInit[38] = {false};
HwTools* hw;
bool publishList1(AmsData* data, EnergyAccounting* ea);
bool publishList2(AmsData* data, EnergyAccounting* ea);
bool publishList3(AmsData* data, EnergyAccounting* ea);
bool publishList4(AmsData* data, EnergyAccounting* ea);
String getMeterModel(AmsData* data);
bool publishRealtime(AmsData* data, EnergyAccounting* ea, PriceService* ps);
void publishSensor(const HomeAssistantSensor sensor);
void publishList1Sensors();
void publishList1ExportSensors();
void publishList2Sensors();
void publishList2ExportSensors();
void publishList3Sensors();
void publishList3ExportSensors();
void publishList4Sensors();
void publishList4ExportSensors();
void publishRealtimeSensors(EnergyAccounting* ea, PriceService* ps);
void publishRealtimeExportSensors(EnergyAccounting* ea, PriceService* ps);
void publishTemperatureSensor(uint8_t index, String id);
void publishPriceSensors(PriceService* ps);
void publishSystemSensors();
String boardTypeToString(uint8_t b) {
switch(b) {
case 5:
#if defined(ESP8266)
return F("Pow-K");
#elif defined(ESP32)
return F("Pow-K+");
#endif
case 7:
#if defined(ESP8266)
return F("Pow-U");
#elif defined(ESP32)
return F("Pow-U+");
#endif
case 6:
return F("Pow-P1");
case 51:
return F("S2 mini");
case 50:
return F("ESP32-S2");
case 201:
return F("LOLIN D32");
case 202:
return F("HUZZAH32");
case 203:
return F("DevKitC");
case 200:
return F("ESP32");
case 2:
return F("HAN Reader 2.0 by Max Spencer");
case 0:
return F("Custom hardware by Roar Fredriksen");
case 1:
return F("Kamstrup module by Egil Opsahl");
case 3:
return F("Pow-K");
case 4:
return F("Pow-U");
case 101:
return F("D1 mini");
case 100:
return F("ESP8266");
case 70:
return F("ESP32-C3");
case 71:
return F("ESP32-C3-DevKitM-1");
case 80:
return F("ESP32-S3");
}
#if defined(ESP8266)
return F("ESP8266");
#elif defined(ESP32)
return F("ESP32");
#endif
};
String boardManufacturerToString(uint8_t b) {
if(b >= 3 && b <= 7)
return F("amsleser.no");
if(b < 50)
return F("Custom");
switch(b) {
case 51:
case 101:
case 201:
return F("Wemos");
case 202:
return F("Adafruit");
}
return F("Espressif");
};
};
#endif

View File

@@ -1,126 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _HOMEASSISTANTSTATIC_H
#define _HOMEASSISTANTSTATIC_H
#include "Arduino.h"
struct HomeAssistantSensor {
const char* name;
const char* topic;
const char* path;
uint16_t ttl;
const char* uom;
const char* devcl;
const char* stacl;
};
const uint8_t List1SensorCount PROGMEM = 1;
const HomeAssistantSensor List1Sensors[List1SensorCount] PROGMEM = {
{"Active import", "/power", "P", 30, "W", "power", "measurement"}
};
const uint8_t List2SensorCount PROGMEM = 8;
const HomeAssistantSensor List2Sensors[List2SensorCount] PROGMEM = {
{"Reactive import", "/power", "Q", 30, "var", "reactive_power", "measurement"},
{"Reactive export", "/power", "QO", 30, "var", "reactive_power", "measurement"},
{"L1 current", "/power", "I1", 30, "A", "current", "measurement"},
{"L2 current", "/power", "I2", 30, "A", "current", "measurement"},
{"L3 current", "/power", "I3", 30, "A", "current", "measurement"},
{"L1 voltage", "/power", "U1", 30, "V", "voltage", "measurement"},
{"L2 voltage", "/power", "U2", 30, "V", "voltage", "measurement"},
{"L3 voltage", "/power", "U3", 30, "V", "voltage", "measurement"}
};
const uint8_t List2ExportSensorCount PROGMEM = 1;
const HomeAssistantSensor List2ExportSensors[List2ExportSensorCount] PROGMEM = {
{"Active export", "/power", "PO", 30, "W", "power", "measurement"}
};
const uint8_t List3SensorCount PROGMEM = 3;
const HomeAssistantSensor List3Sensors[List3SensorCount] PROGMEM = {
{"Accumulated active import", "/energy", "tPI", 4000, "kWh", "energy", "total_increasing"},
{"Accumulated reactive import","/energy", "tQI", 4000, "kvarh","", "total_increasing"},
{"Accumulated reactive export","/energy", "tQO", 4000, "kvarh","", "total_increasing"}
};
const uint8_t List3ExportSensorCount PROGMEM = 1;
const HomeAssistantSensor List3ExportSensors[List3ExportSensorCount] PROGMEM = {
{"Accumulated active export", "/energy", "tPO", 4000, "kWh", "energy", "total_increasing"}
};
const uint8_t List4SensorCount PROGMEM = 10;
const HomeAssistantSensor List4Sensors[List4SensorCount] PROGMEM = {
{"Power factor", "/power", "PF", 30, "%", "power_factor", "measurement"},
{"L1 power factor", "/power", "PF1", 30, "%", "power_factor", "measurement"},
{"L2 power factor", "/power", "PF2", 30, "%", "power_factor", "measurement"},
{"L3 power factor", "/power", "PF3", 30, "%", "power_factor", "measurement"},
{"L1 active import", "/power", "P1", 30, "W", "power", "measurement"},
{"L2 active import", "/power", "P2", 30, "W", "power", "measurement"},
{"L3 active import", "/power", "P3", 30, "W", "power", "measurement"},
{"L1 accumulated active import","/power", "tPI1", 30, "kWh", "energy", "total_increasing"},
{"L2 accumulated active import","/power", "tPI2", 30, "kWh", "energy", "total_increasing"},
{"L3 accumulated active import","/power", "tPI3", 30, "kWh", "energy", "total_increasing"}
};
const uint8_t List4ExportSensorCount PROGMEM = 6;
const HomeAssistantSensor List4ExportSensors[List4ExportSensorCount] PROGMEM = {
{"L1 active export", "/power", "PO1", 30, "W", "power", "measurement"},
{"L2 active export", "/power", "PO2", 30, "W", "power", "measurement"},
{"L3 active export", "/power", "PO3", 30, "W", "power", "measurement"},
{"L1 accumulated active export","/power", "tPO1", 30, "kWh", "energy", "total_increasing"},
{"L2 accumulated active export","/power", "tPO2", 30, "kWh", "energy", "total_increasing"},
{"L3 accumulated active export","/power", "tPO3", 30, "kWh", "energy", "total_increasing"}
};
const uint8_t RealtimeSensorCount PROGMEM = 8;
const HomeAssistantSensor RealtimeSensors[RealtimeSensorCount] PROGMEM = {
{"Month max", "/realtime","max", 120, "kWh", "energy", "total_increasing"},
{"Tariff threshold", "/realtime","threshold", 120, "kWh", "energy", "total_increasing"},
{"Current hour used", "/realtime","hour.use", 120, "kWh", "energy", "total_increasing"},
{"Current hour cost", "/realtime","hour.cost", 120, "", "monetary", ""},
{"Current day used", "/realtime","day.use", 120, "kWh", "energy", "total_increasing"},
{"Current day cost", "/realtime","day.cost", 120, "", "monetary", ""},
{"Current month used", "/realtime","month.use", 120, "kWh", "energy", "total_increasing"},
{"Current month cost", "/realtime","month.cost", 120, "", "monetary", ""}
};
const uint8_t RealtimeExportSensorCount PROGMEM = 6;
const HomeAssistantSensor RealtimeExportSensors[RealtimeExportSensorCount] PROGMEM = {
{"Current hour produced", "/realtime","hour.produced", 120, "kWh", "energy", "total_increasing"},
{"Current hour income", "/realtime","hour.income", 120, "", "monetary", ""},
{"Current day produced", "/realtime","day.produced", 120, "kWh", "energy", "total_increasing"},
{"Current day income", "/realtime","day.income", 120, "", "monetary", ""},
{"Current month produced", "/realtime","month.produced", 120, "kWh", "energy", "total_increasing"},
{"Current month income", "/realtime","month.income", 120, "", "monetary", ""}
};
const HomeAssistantSensor RealtimePeakSensor PROGMEM = {"Current month peak %d", "/realtime", "peaks[%d]", 4000, "kWh", "energy", ""};
const uint8_t PriceSensorCount PROGMEM = 5;
const HomeAssistantSensor PriceSensors[PriceSensorCount] PROGMEM = {
{"Minimum price ahead", "/prices", "prices.min", 4000, "", "monetary", ""},
{"Maximum price ahead", "/prices", "prices.max", 4000, "", "monetary", ""},
{"Cheapest 1hr period ahead", "/prices", "prices.cheapest1hr",4000, "", "timestamp", ""},
{"Cheapest 3hr period ahead", "/prices", "prices.cheapest3hr",4000, "", "timestamp", ""},
{"Cheapest 6hr period ahead", "/prices", "prices.cheapest6hr",4000, "", "timestamp", ""}
};
const HomeAssistantSensor PriceSensor PROGMEM = {"Price in %02d %s", "/prices", "prices['%d']", 4000, "", "monetary", ""};
const uint8_t SystemSensorCount PROGMEM = 3;
const HomeAssistantSensor SystemSensors[SystemSensorCount] PROGMEM = {
{"Status", "/state", "rssi", 180, "dBm", "signal_strength", "measurement"},
{"Supply volt", "/state", "vcc", 180, "V", "voltage", "measurement"},
{"Uptime", "/state", "up", 180, "s", "duration", "measurement"}
};
const HomeAssistantSensor TemperatureSensor PROGMEM = {"Temperature sensor %s", "/temperatures", "temperatures['%s']", 900, "°C", "temperature", "measurement"};
#endif

View File

@@ -1,7 +0,0 @@
{
"tPI" : %.3f,
"tPO" : %.3f,
"tQI" : %.3f,
"tQO" : %.3f,
"rtc" : %lu
}

View File

@@ -1,31 +0,0 @@
{
"lv" : "%s",
"id" : "%s",
"type" : "%s",
"P" : %d,
"P1" : %d,
"P2" : %d,
"P3" : %d,
"Q" : %d,
"PO" : %d,
"PO1" : %d,
"PO2" : %d,
"PO3" : %d,
"QO" : %d,
"I1" : %.2f,
"I2" : %.2f,
"I3" : %.2f,
"U1" : %.2f,
"U2" : %.2f,
"U3" : %.2f,
"PF" : %.2f,
"PF1" : %.2f,
"PF2" : %.2f,
"PF3" : %.2f,
"tPI1" : %.3f,
"tPI2" : %.3f,
"tPI3" : %.3f,
"tPO1" : %.3f,
"tPO2" : %.3f,
"tPO3" : %.3f
}

View File

@@ -1,550 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "HomeAssistantMqttHandler.h"
#include "hexutils.h"
#include "Uptime.h"
#include "FirmwareVersion.h"
#include "json/ha1_json.h"
#include "json/ha2_json.h"
#include "json/ha3_json.h"
#include "json/ha4_json.h"
#include "json/hadiscover_json.h"
#include "json/realtime_json.h"
#include "FirmwareVersion.h"
#if defined(ESP32)
#include <esp_task_wdt.h>
#endif
bool HomeAssistantMqttHandler::publish(AmsData* data, AmsData* previousState, EnergyAccounting* ea, PriceService* ps) {
if(topic.isEmpty() || !mqtt.connected())
return false;
if(time(nullptr) < FirmwareVersion::BuildEpoch)
return false;
if(data->getListType() >= 3) { // publish energy counts
publishList3(data, ea);
mqtt.loop();
}
if(data->getListType() == 1) { // publish power counts
publishList1(data, ea);
mqtt.loop();
} else if(data->getListType() <= 3) { // publish power counts and volts/amps
publishList2(data, ea);
mqtt.loop();
} else if(data->getListType() == 4) { // publish power counts and volts/amps/phase power and PF
publishList4(data, ea);
mqtt.loop();
}
if(ea->isInitialized()) {
publishRealtime(data, ea, ps);
mqtt.loop();
}
loop();
return true;
}
bool HomeAssistantMqttHandler::publishList1(AmsData* data, EnergyAccounting* ea) {
publishList1Sensors();
snprintf_P(json, BufferSize, HA1_JSON, data->getActiveImportPower());
return mqtt.publish(topic + "/power", json);
}
bool HomeAssistantMqttHandler::publishList2(AmsData* data, EnergyAccounting* ea) {
publishList2Sensors();
if(data->getActiveExportPower() > 0) publishList2ExportSensors();
snprintf_P(json, BufferSize, HA3_JSON,
data->getListId().c_str(),
data->getMeterId().c_str(),
getMeterModel(data).c_str(),
data->getActiveImportPower(),
data->getReactiveImportPower(),
data->getActiveExportPower(),
data->getReactiveExportPower(),
data->getL1Current(),
data->getL2Current(),
data->getL3Current(),
data->getL1Voltage(),
data->getL2Voltage(),
data->getL3Voltage()
);
return mqtt.publish(topic + "/power", json);
}
bool HomeAssistantMqttHandler::publishList3(AmsData* data, EnergyAccounting* ea) {
publishList3Sensors();
if(data->getActiveExportCounter() > 0.0) publishList3ExportSensors();
snprintf_P(json, BufferSize, HA2_JSON,
data->getActiveImportCounter(),
data->getActiveExportCounter(),
data->getReactiveImportCounter(),
data->getReactiveExportCounter(),
data->getMeterTimestamp()
);
return mqtt.publish(topic + "/energy", json);
}
bool HomeAssistantMqttHandler::publishList4(AmsData* data, EnergyAccounting* ea) {
publishList4Sensors();
if(data->getL1ActiveExportPower() > 0 || data->getL2ActiveExportPower() > 0 || data->getL3ActiveExportPower() > 0) publishList4ExportSensors();
snprintf_P(json, BufferSize, HA4_JSON,
data->getListId().c_str(),
data->getMeterId().c_str(),
getMeterModel(data).c_str(),
data->getActiveImportPower(),
data->getL1ActiveImportPower(),
data->getL2ActiveImportPower(),
data->getL3ActiveImportPower(),
data->getReactiveImportPower(),
data->getActiveExportPower(),
data->getL1ActiveExportPower(),
data->getL2ActiveExportPower(),
data->getL3ActiveExportPower(),
data->getReactiveExportPower(),
data->getL1Current(),
data->getL2Current(),
data->getL3Current(),
data->getL1Voltage(),
data->getL2Voltage(),
data->getL3Voltage(),
data->getPowerFactor() == 0 ? 1 : data->getPowerFactor(),
data->getPowerFactor() == 0 ? 1 : data->getL1PowerFactor(),
data->getPowerFactor() == 0 ? 1 : data->getL2PowerFactor(),
data->getPowerFactor() == 0 ? 1 : data->getL3PowerFactor(),
data->getL1ActiveImportCounter(),
data->getL2ActiveImportCounter(),
data->getL3ActiveImportCounter(),
data->getL1ActiveExportCounter(),
data->getL2ActiveExportCounter(),
data->getL3ActiveExportCounter()
);
return mqtt.publish(topic + "/power", json);
}
String HomeAssistantMqttHandler::getMeterModel(AmsData* data) {
String meterModel = data->getMeterModel();
meterModel.replace("\\", "\\\\");
return meterModel;
}
bool HomeAssistantMqttHandler::publishRealtime(AmsData* data, EnergyAccounting* ea, PriceService* ps) {
publishRealtimeSensors(ea, ps);
if(ea->getProducedThisHour() > 0.0 || ea->getProducedToday() > 0.0 || ea->getProducedThisMonth() > 0.0) publishRealtimeExportSensors(ea, ps);
String peaks = "";
uint8_t peakCount = ea->getConfig()->hours;
if(peakCount > 5) peakCount = 5;
for(uint8_t i = 1; i <= peakCount; i++) {
if(!peaks.isEmpty()) peaks += ",";
peaks += String(ea->getPeak(i).value / 100.0, 2);
}
snprintf_P(json, BufferSize, REALTIME_JSON,
ea->getMonthMax(),
peaks.c_str(),
ea->getCurrentThreshold(),
ea->getUseThisHour(),
ea->getCostThisHour(),
ea->getProducedThisHour(),
ea->getIncomeThisHour(),
ea->getUseToday(),
ea->getCostToday(),
ea->getProducedToday(),
ea->getIncomeToday(),
ea->getUseThisMonth(),
ea->getCostThisMonth(),
ea->getProducedThisMonth(),
ea->getIncomeThisMonth()
);
return mqtt.publish(topic + "/realtime", json);
}
bool HomeAssistantMqttHandler::publishTemperatures(AmsConfiguration* config, HwTools* hw) {
int count = hw->getTempSensorCount();
if(count < 2) return false;
int size = 32 + (count * 26);
char buf[size];
snprintf_P(buf, 24, PSTR("{\"temperatures\":{"));
for(int i = 0; i < count; i++) {
TempSensorData* data = hw->getTempSensorData(i);
if(data != NULL) {
char* pos = buf+strlen(buf);
String id = toHex(data->address, 8);
snprintf_P(pos, 26, PSTR("\"%s\":%.2f,"),
id.c_str(),
data->lastRead
);
data->changed = false;
publishTemperatureSensor(i+1, id);
}
}
char* pos = buf+strlen(buf);
snprintf_P(count == 0 ? pos : pos-1, 8, PSTR("}}"));
bool ret = mqtt.publish(topic + "/temperatures", buf);
loop();
return ret;
}
bool HomeAssistantMqttHandler::publishPrices(PriceService* ps) {
if(topic.isEmpty() || !mqtt.connected())
return false;
if(ps->getValueForHour(PRICE_DIRECTION_IMPORT, 0) == PRICE_NO_VALUE)
return false;
publishPriceSensors(ps);
time_t now = time(nullptr);
float min1hr = 0.0, min3hr = 0.0, min6hr = 0.0;
int8_t min1hrIdx = -1, min3hrIdx = -1, min6hrIdx = -1;
float min = INT16_MAX, max = INT16_MIN;
float values[38];
for(int i = 0;i < 38; i++) values[i] = PRICE_NO_VALUE;
for(uint8_t i = 0; i < 38; i++) {
float val = ps->getValueForHour(PRICE_DIRECTION_IMPORT, now, i);
values[i] = val;
if(val == PRICE_NO_VALUE) break;
if(val < min) min = val;
if(val > max) max = val;
if(min1hrIdx == -1 || min1hr > val) {
min1hr = val;
min1hrIdx = i;
}
if(i >= 2) {
i -= 2;
float val1 = values[i++];
float val2 = values[i++];
float val3 = val;
if(val1 == PRICE_NO_VALUE || val2 == PRICE_NO_VALUE || val3 == PRICE_NO_VALUE) continue;
float val3hr = val1+val2+val3;
if(min3hrIdx == -1 || min3hr > val3hr) {
min3hr = val3hr;
min3hrIdx = i-2;
}
}
if(i >= 5) {
i -= 5;
float val1 = values[i++];
float val2 = values[i++];
float val3 = values[i++];
float val4 = values[i++];
float val5 = values[i++];
float val6 = val;
if(val1 == PRICE_NO_VALUE || val2 == PRICE_NO_VALUE || val3 == PRICE_NO_VALUE || val4 == PRICE_NO_VALUE || val5 == PRICE_NO_VALUE || val6 == PRICE_NO_VALUE) continue;
float val6hr = val1+val2+val3+val4+val5+val6;
if(min6hrIdx == -1 || min6hr > val6hr) {
min6hr = val6hr;
min6hrIdx = i-5;
}
}
}
char ts1hr[24];
memset(ts1hr, 0, 24);
if(min1hrIdx > -1) {
time_t ts = now + (SECS_PER_HOUR * min1hrIdx);
tmElements_t tm;
breakTime(ts, tm);
sprintf_P(ts1hr, PSTR("%04d-%02d-%02dT%02d:00:00Z"), tm.Year+1970, tm.Month, tm.Day, tm.Hour);
}
char ts3hr[24];
memset(ts3hr, 0, 24);
if(min3hrIdx > -1) {
time_t ts = now + (SECS_PER_HOUR * min3hrIdx);
tmElements_t tm;
breakTime(ts, tm);
sprintf_P(ts3hr, PSTR("%04d-%02d-%02dT%02d:00:00Z"), tm.Year+1970, tm.Month, tm.Day, tm.Hour);
}
char ts6hr[24];
memset(ts6hr, 0, 24);
if(min6hrIdx > -1) {
time_t ts = now + (SECS_PER_HOUR * min6hrIdx);
tmElements_t tm;
breakTime(ts, tm);
sprintf_P(ts6hr, PSTR("%04d-%02d-%02dT%02d:00:00Z"), tm.Year+1970, tm.Month, tm.Day, tm.Hour);
}
uint16_t pos = snprintf_P(json, BufferSize, PSTR("{\"id\":\"%s\",\"prices\":{"), WiFi.macAddress().c_str());
for(uint8_t i = 0;i < 38; i++) {
if(values[i] == PRICE_NO_VALUE) {
pos += snprintf_P(json+pos, BufferSize-pos, PSTR("\"%d\":null,"), i);
} else {
pos += snprintf_P(json+pos, BufferSize-pos, PSTR("\"%d\":%.4f,"), i, values[i]);
}
}
snprintf_P(json+pos, BufferSize-pos, PSTR("\"min\":%.4f,\"max\":%.4f,\"cheapest1hr\":\"%s\",\"cheapest3hr\":\"%s\",\"cheapest6hr\":\"%s\"}}"),
min == INT16_MAX ? 0.0 : min,
max == INT16_MIN ? 0.0 : max,
ts1hr,
ts3hr,
ts6hr
);
bool ret = mqtt.publish(topic + "/prices", json, true, 0);
loop();
return ret;
}
bool HomeAssistantMqttHandler::publishSystem(HwTools* hw, PriceService* ps, EnergyAccounting* ea) {
if(topic.isEmpty() || !mqtt.connected())
return false;
publishSystemSensors();
if(hw->getTemperature() > -50) publishTemperatureSensor(0, "");
snprintf_P(json, BufferSize, PSTR("{\"id\":\"%s\",\"name\":\"%s\",\"up\":%d,\"vcc\":%.3f,\"rssi\":%d,\"temp\":%.2f,\"version\":\"%s\"}"),
WiFi.macAddress().c_str(),
mqttConfig.clientId,
(uint32_t) (millis64()/1000),
hw->getVcc(),
hw->getWifiRssi(),
hw->getTemperature(),
FirmwareVersion::VersionString
);
bool ret = mqtt.publish(topic + "/state", json);
loop();
return ret;
}
void HomeAssistantMqttHandler::publishSensor(const HomeAssistantSensor sensor) {
String uid = String(sensor.path);
uid.replace(".", "");
uid.replace("[", "");
uid.replace("]", "");
uid.replace("'", "");
snprintf_P(json, BufferSize, HADISCOVER_JSON,
sensorNamePrefix.c_str(),
sensor.name,
mqttConfig.publishTopic, sensor.topic,
deviceUid.c_str(), uid.c_str(),
deviceUid.c_str(), uid.c_str(),
sensor.uom,
sensor.path,
sensor.ttl,
deviceUid.c_str(),
deviceName.c_str(),
deviceModel.c_str(),
FirmwareVersion::VersionString,
manufacturer.c_str(),
deviceUrl.c_str(),
strlen_P(sensor.devcl) > 0 ? ",\"dev_cla\":\"" : "",
strlen_P(sensor.devcl) > 0 ? (char *) FPSTR(sensor.devcl) : "",
strlen_P(sensor.devcl) > 0 ? "\"" : "",
strlen_P(sensor.stacl) > 0 ? ",\"stat_cla\":\"" : "",
strlen_P(sensor.stacl) > 0 ? (char *) FPSTR(sensor.stacl) : "",
strlen_P(sensor.stacl) > 0 ? "\"" : ""
);
mqtt.publish(discoveryTopic + deviceUid + "_" + uid.c_str() + "/config", json, true, 0);
loop();
}
void HomeAssistantMqttHandler::publishList1Sensors() {
if(l1Init) return;
for(uint8_t i = 0; i < List1SensorCount; i++) {
publishSensor(List1Sensors[i]);
}
l1Init = true;
}
void HomeAssistantMqttHandler::publishList2Sensors() {
publishList1Sensors();
if(l2Init) return;
for(uint8_t i = 0; i < List2SensorCount; i++) {
publishSensor(List2Sensors[i]);
}
l2Init = true;
}
void HomeAssistantMqttHandler::publishList2ExportSensors() {
if(l2eInit) return;
for(uint8_t i = 0; i < List2ExportSensorCount; i++) {
publishSensor(List2ExportSensors[i]);
}
l2eInit = true;
}
void HomeAssistantMqttHandler::publishList3Sensors() {
publishList2Sensors();
if(l3Init) return;
for(uint8_t i = 0; i < List3SensorCount; i++) {
publishSensor(List3Sensors[i]);
}
l3Init = true;
}
void HomeAssistantMqttHandler::publishList3ExportSensors() {
publishList2ExportSensors();
if(l3eInit) return;
for(uint8_t i = 0; i < List3ExportSensorCount; i++) {
publishSensor(List3ExportSensors[i]);
}
l3eInit = true;
}
void HomeAssistantMqttHandler::publishList4Sensors() {
publishList3Sensors();
if(l4Init) return;
for(uint8_t i = 0; i < List4SensorCount; i++) {
publishSensor(List4Sensors[i]);
}
l4Init = true;
}
void HomeAssistantMqttHandler::publishList4ExportSensors() {
publishList3ExportSensors();
if(l4eInit) return;
for(uint8_t i = 0; i < List4ExportSensorCount; i++) {
publishSensor(List4ExportSensors[i]);
}
l4eInit = true;
}
void HomeAssistantMqttHandler::publishRealtimeSensors(EnergyAccounting* ea, PriceService* ps) {
if(rtInit) return;
for(uint8_t i = 0; i < RealtimeSensorCount; i++) {
HomeAssistantSensor sensor = RealtimeSensors[i];
if(strncmp_P(sensor.devcl, PSTR("monetary"), 8) == 0) {
if(ps == NULL) continue;
sensor.uom = ps->getCurrency();
}
publishSensor(sensor);
}
uint8_t peakCount = ea->getConfig()->hours;
if(peakCount > 5) peakCount = 5;
for(uint8_t i = 0; i < peakCount; i++) {
char name[strlen(RealtimePeakSensor.name)];
snprintf(name, strlen(RealtimePeakSensor.name), RealtimePeakSensor.name, i+1);
char path[strlen(RealtimePeakSensor.path)];
snprintf(path, strlen(RealtimePeakSensor.path), RealtimePeakSensor.path, i);
HomeAssistantSensor sensor = {
name,
RealtimePeakSensor.topic,
path,
RealtimePeakSensor.ttl,
RealtimePeakSensor.uom,
RealtimePeakSensor.devcl,
RealtimePeakSensor.stacl
};
publishSensor(sensor);
}
rtInit = true;
}
void HomeAssistantMqttHandler::publishRealtimeExportSensors(EnergyAccounting* ea, PriceService* ps) {
if(rteInit) return;
for(uint8_t i = 0; i < RealtimeExportSensorCount; i++) {
HomeAssistantSensor sensor = RealtimeExportSensors[i];
if(strncmp_P(sensor.devcl, PSTR("monetary"), 8) == 0) {
if(ps == NULL) continue;
sensor.uom = ps->getCurrency();
}
publishSensor(sensor);
}
rteInit = true;
}
void HomeAssistantMqttHandler::publishTemperatureSensor(uint8_t index, String id) {
if(index > 32) return;
if(tInit[index]) return;
char name[strlen(TemperatureSensor.name)+id.length()];
snprintf(name, strlen(TemperatureSensor.name)+id.length(), TemperatureSensor.name, id.c_str());
char path[strlen(TemperatureSensor.path)+id.length()];
if(index == 0) {
memcpy_P(path, PSTR("temp\0"), 5);
} else {
snprintf(path, strlen(TemperatureSensor.path)+id.length(), TemperatureSensor.path, id.c_str());
}
HomeAssistantSensor sensor = {
name,
index == 0 ? SystemSensors[0].topic : TemperatureSensor.topic,
path,
TemperatureSensor.ttl,
TemperatureSensor.uom,
TemperatureSensor.devcl,
TemperatureSensor.stacl
};
publishSensor(sensor);
tInit[index] = true;
}
void HomeAssistantMqttHandler::publishPriceSensors(PriceService* ps) {
if(ps == NULL) return;
String uom = String(ps->getCurrency()) + "/kWh";
if(!pInit) {
for(uint8_t i = 0; i < PriceSensorCount; i++) {
HomeAssistantSensor sensor = PriceSensors[i];
if(strncmp_P(sensor.devcl, PSTR("monetary"), 8) == 0) {
sensor.uom = uom.c_str();
}
publishSensor(sensor);
}
pInit = true;
}
for(uint8_t i = 0; i < 38; i++) {
if(prInit[i]) continue;
float val = ps->getValueForHour(PRICE_DIRECTION_IMPORT, i);
if(val == PRICE_NO_VALUE) continue;
char name[strlen(PriceSensor.name)+2];
snprintf(name, strlen(PriceSensor.name)+2, PriceSensor.name, i, i == 1 ? "hour" : "hours");
char path[strlen(PriceSensor.path)+1];
snprintf(path, strlen(PriceSensor.path)+1, PriceSensor.path, i);
HomeAssistantSensor sensor = {
i == 0 ? "Price current hour" : name,
PriceSensor.topic,
path,
PriceSensor.ttl,
uom.c_str(),
PriceSensor.devcl,
i == 0 ? "total" : PriceSensor.stacl
};
publishSensor(sensor);
prInit[i] = true;
}
}
void HomeAssistantMqttHandler::publishSystemSensors() {
if(sInit) return;
for(uint8_t i = 0; i < SystemSensorCount; i++) {
publishSensor(SystemSensors[i]);
}
sInit = true;
}
uint8_t HomeAssistantMqttHandler::getFormat() {
return 4;
}
bool HomeAssistantMqttHandler::publishRaw(String data) {
return false;
}
void HomeAssistantMqttHandler::onMessage(String &topic, String &payload) {
if(topic.equals(statusTopic)) {
if(payload.equals("online")) {
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("Received online status from HA, resetting sensor status\n"));
l1Init = l2Init = l2eInit = l3Init = l3eInit = l4Init = l4eInit = rtInit = rteInit = pInit = sInit = false;
for(uint8_t i = 0; i < 32; i++) tInit[i] = false;
for(uint8_t i = 0; i < 38; i++) prInit[i] = false;
}
}
}

View File

@@ -1,37 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _JSONMQTTHANDLER_H
#define _JSONMQTTHANDLER_H
#include "AmsMqttHandler.h"
class JsonMqttHandler : public AmsMqttHandler {
public:
JsonMqttHandler(MqttConfig& mqttConfig, RemoteDebug* debugger, char* buf, HwTools* hw) : AmsMqttHandler(mqttConfig, debugger, buf) {
this->hw = hw;
};
bool publish(AmsData* data, AmsData* previousState, EnergyAccounting* ea, PriceService* ps);
bool publishTemperatures(AmsConfiguration*, HwTools*);
bool publishPrices(PriceService*);
bool publishSystem(HwTools* hw, PriceService* ps, EnergyAccounting* ea);
bool publishRaw(String data);
void onMessage(String &topic, String &payload);
uint8_t getFormat();
private:
HwTools* hw;
uint16_t appendJsonHeader(AmsData* data);
uint16_t appendJsonFooter(EnergyAccounting* ea, uint16_t pos);
bool publishList1(AmsData* data, EnergyAccounting* ea);
bool publishList2(AmsData* data, EnergyAccounting* ea);
bool publishList3(AmsData* data, EnergyAccounting* ea);
bool publishList4(AmsData* data, EnergyAccounting* ea);
String getMeterModel(AmsData* data);
};
#endif

View File

@@ -1,422 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "JsonMqttHandler.h"
#include "FirmwareVersion.h"
#include "hexutils.h"
#include "Uptime.h"
bool JsonMqttHandler::publish(AmsData* data, AmsData* previousState, EnergyAccounting* ea, PriceService* ps) {
if(strlen(mqttConfig.publishTopic) == 0) {
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf_P(PSTR("Unable to publish data, no publish topic\n"));
return false;
}
if(!mqtt.connected()) {
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf_P(PSTR("Unable to publish data, not connected\n"));
return false;
}
bool ret = false;
memset(json, 0, BufferSize);
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf_P(PSTR("Publishing list ID %d!\n"), data->getListType());
if(data->getListType() == 1) {
ret = publishList1(data, ea);
mqtt.loop();
} else if(data->getListType() == 2) {
ret = publishList2(data, ea);
mqtt.loop();
} else if(data->getListType() == 3) {
ret = publishList3(data, ea);
mqtt.loop();
} else if(data->getListType() == 4) {
ret = publishList4(data, ea);
mqtt.loop();
}
loop();
return ret;
}
uint16_t JsonMqttHandler::appendJsonHeader(AmsData* data) {
return snprintf_P(json, BufferSize, PSTR("{\"id\":\"%s\",\"name\":\"%s\",\"up\":%u,\"t\":%lu,\"vcc\":%.3f,\"rssi\":%d,\"temp\":%.2f,"),
WiFi.macAddress().c_str(),
mqttConfig.clientId,
(uint32_t) (millis64()/1000),
data->getPackageTimestamp(),
hw->getVcc(),
hw->getWifiRssi(),
hw->getTemperature()
);
}
uint16_t JsonMqttHandler::appendJsonFooter(EnergyAccounting* ea, uint16_t pos) {
char pf[4];
if(mqttConfig.payloadFormat == 6) {
strcpy_P(pf, PSTR("rt_"));
} else {
memset(pf, 0, 4);
}
return snprintf_P(json+pos, BufferSize-pos, PSTR("%s\"%sh\":%.2f,\"%sd\":%.1f,\"%st\":%d,\"%sx\":%.2f,\"%she\":%.2f,\"%sde\":%.1f%s"),
strlen(pf) == 0 ? "},\"realtime\":{" : ",",
pf,
ea->getUseThisHour(),
pf,
ea->getUseToday(),
pf,
ea->getCurrentThreshold(),
pf,
ea->getMonthMax(),
pf,
ea->getProducedThisHour(),
pf,
ea->getProducedToday(),
strlen(pf) == 0 ? "}" : ""
);
}
bool JsonMqttHandler::publishList1(AmsData* data, EnergyAccounting* ea) {
uint16_t pos = appendJsonHeader(data);
if(mqttConfig.payloadFormat != 6) {
pos += snprintf_P(json+pos, BufferSize-pos, PSTR("\"data\":{"));
}
pos += snprintf_P(json+pos, BufferSize-pos, PSTR("\"P\":%d"), data->getActiveImportPower());
pos += appendJsonFooter(ea, pos);
json[pos] = '}';
if(mqttConfig.payloadFormat == 5) {
char topic[192];
snprintf_P(topic, 192, PSTR("%s/list1"), mqttConfig.publishTopic);
return mqtt.publish(topic, json);
} else {
return mqtt.publish(mqttConfig.publishTopic, json);
}
}
bool JsonMqttHandler::publishList2(AmsData* data, EnergyAccounting* ea) {
uint16_t pos = appendJsonHeader(data);
if(mqttConfig.payloadFormat != 6) {
pos += snprintf_P(json+pos, BufferSize-pos, PSTR("\"data\":{"));
}
pos += snprintf_P(json+pos, BufferSize-pos, PSTR("\"lv\":\"%s\",\"meterId\":\"%s\",\"type\":\"%s\",\"P\":%d,\"Q\":%d,\"PO\":%d,\"QO\":%d,\"I1\":%.2f,\"I2\":%.2f,\"I3\":%.2f,\"U1\":%.2f,\"U2\":%.2f,\"U3\":%.2f"),
data->getListId().c_str(),
data->getMeterId().c_str(),
getMeterModel(data).c_str(),
data->getActiveImportPower(),
data->getReactiveImportPower(),
data->getActiveExportPower(),
data->getReactiveExportPower(),
data->getL1Current(),
data->getL2Current(),
data->getL3Current(),
data->getL1Voltage(),
data->getL2Voltage(),
data->getL3Voltage()
);
pos += appendJsonFooter(ea, pos);
json[pos] = '}';
if(mqttConfig.payloadFormat == 5) {
char topic[192];
snprintf_P(topic, 192, PSTR("%s/list2"), mqttConfig.publishTopic);
return mqtt.publish(topic, json);
} else {
return mqtt.publish(mqttConfig.publishTopic, json);
}
}
bool JsonMqttHandler::publishList3(AmsData* data, EnergyAccounting* ea) {
uint16_t pos = appendJsonHeader(data);
if(mqttConfig.payloadFormat != 6) {
pos += snprintf_P(json+pos, BufferSize-pos, PSTR("\"data\":{"));
}
pos += snprintf_P(json+pos, BufferSize-pos, PSTR("\"lv\":\"%s\",\"meterId\":\"%s\",\"type\":\"%s\",\"P\":%d,\"Q\":%d,\"PO\":%d,\"QO\":%d,\"I1\":%.2f,\"I2\":%.2f,\"I3\":%.2f,\"U1\":%.2f,\"U2\":%.2f,\"U3\":%.2f,\"tPI\":%.3f,\"tPO\":%.3f,\"tQI\":%.3f,\"tQO\":%.3f,\"rtc\":%lu"),
data->getListId().c_str(),
data->getMeterId().c_str(),
getMeterModel(data).c_str(),
data->getActiveImportPower(),
data->getReactiveImportPower(),
data->getActiveExportPower(),
data->getReactiveExportPower(),
data->getL1Current(),
data->getL2Current(),
data->getL3Current(),
data->getL1Voltage(),
data->getL2Voltage(),
data->getL3Voltage(),
data->getActiveImportCounter(),
data->getActiveExportCounter(),
data->getReactiveImportCounter(),
data->getReactiveExportCounter(),
data->getMeterTimestamp()
);
pos += appendJsonFooter(ea, pos);
json[pos] = '}';
if(mqttConfig.payloadFormat == 5) {
char topic[192];
snprintf_P(topic, 192, PSTR("%s/list3"), mqttConfig.publishTopic);
return mqtt.publish(topic, json);
} else {
return mqtt.publish(mqttConfig.publishTopic, json);
}
}
bool JsonMqttHandler::publishList4(AmsData* data, EnergyAccounting* ea) {
uint16_t pos = appendJsonHeader(data);
if(mqttConfig.payloadFormat != 6) {
pos += snprintf_P(json+pos, BufferSize-pos, PSTR("\"data\":{"));
}
pos += snprintf_P(json+pos, BufferSize-pos, PSTR("\"lv\":\"%s\",\"meterId\":\"%s\",\"type\":\"%s\",\"P\":%d,\"P1\":%d,\"P2\":%d,\"P3\":%d,\"Q\":%d,\"PO\":%d,\"PO1\":%d,\"PO2\":%d,\"PO3\":%d,\"QO\":%d,\"I1\":%.2f,\"I2\":%.2f,\"I3\":%.2f,\"U1\":%.2f,\"U2\":%.2f,\"U3\":%.2f,\"PF\":%.2f,\"PF1\":%.2f,\"PF2\":%.2f,\"PF3\":%.2f,\"tPI\":%.3f,\"tPO\":%.3f,\"tQI\":%.3f,\"tQO\":%.3f,\"tPI1\":%.3f,\"tPI2\":%.3f,\"tPI3\":%.3f,\"tPO1\":%.3f,\"tPO2\":%.3f,\"tPO3\":%.3f,\"rtc\":%lu"),
data->getListId().c_str(),
data->getMeterId().c_str(),
getMeterModel(data).c_str(),
data->getActiveImportPower(),
data->getL1ActiveImportPower(),
data->getL2ActiveImportPower(),
data->getL3ActiveImportPower(),
data->getReactiveImportPower(),
data->getActiveExportPower(),
data->getL1ActiveExportPower(),
data->getL2ActiveExportPower(),
data->getL3ActiveExportPower(),
data->getReactiveExportPower(),
data->getL1Current(),
data->getL2Current(),
data->getL3Current(),
data->getL1Voltage(),
data->getL2Voltage(),
data->getL3Voltage(),
data->getPowerFactor(),
data->getL1PowerFactor(),
data->getL2PowerFactor(),
data->getL3PowerFactor(),
data->getActiveImportCounter(),
data->getActiveExportCounter(),
data->getReactiveImportCounter(),
data->getReactiveExportCounter(),
data->getL1ActiveImportCounter(),
data->getL2ActiveImportCounter(),
data->getL3ActiveImportCounter(),
data->getL1ActiveExportCounter(),
data->getL2ActiveExportCounter(),
data->getL3ActiveExportCounter(),
data->getMeterTimestamp()
);
pos += appendJsonFooter(ea, pos);
json[pos] = '}';
if(mqttConfig.payloadFormat == 5) {
char topic[192];
snprintf_P(topic, 192, PSTR("%s/list4"), mqttConfig.publishTopic);
return mqtt.publish(topic, json);
} else {
return mqtt.publish(mqttConfig.publishTopic, json);
}
}
String JsonMqttHandler::getMeterModel(AmsData* data) {
String meterModel = data->getMeterModel();
meterModel.replace("\\", "\\\\");
return meterModel;
}
bool JsonMqttHandler::publishTemperatures(AmsConfiguration* config, HwTools* hw) {
int count = hw->getTempSensorCount();
if(count < 2) {
return false;
}
uint16_t pos = 0;
if(mqttConfig.payloadFormat == 6) {
json[pos++] = '{';
} else {
pos = snprintf_P(json, 24, PSTR("{\"temperatures\":{"));
}
for(int i = 0; i < count; i++) {
TempSensorData* data = hw->getTempSensorData(i);
if(data != NULL) {
pos += snprintf_P(json+pos, 26, PSTR("\"%s\":%.2f,"),
toHex(data->address, 8).c_str(),
data->lastRead
);
data->changed = false;
}
}
bool ret = false;
json[pos-1] = '}';
if(mqttConfig.payloadFormat != 6) {
json[pos] = '}';
}
if(mqttConfig.payloadFormat == 5) {
char topic[192];
snprintf_P(topic, 192, PSTR("%s/temperatures"), mqttConfig.publishTopic);
ret = mqtt.publish(topic, json);
} else {
ret = mqtt.publish(mqttConfig.publishTopic, json);
}
loop();
return ret;
}
bool JsonMqttHandler::publishPrices(PriceService* ps) {
if(strlen(mqttConfig.publishTopic) == 0 || !mqtt.connected())
return false;
if(ps->getValueForHour(PRICE_DIRECTION_IMPORT, 0) == PRICE_NO_VALUE)
return false;
time_t now = time(nullptr);
float min1hr = 0.0, min3hr = 0.0, min6hr = 0.0;
int8_t min1hrIdx = -1, min3hrIdx = -1, min6hrIdx = -1;
float min = INT16_MAX, max = INT16_MIN;
float values[38];
for(int i = 0;i < 38; i++) values[i] = PRICE_NO_VALUE;
for(uint8_t i = 0; i < 38; i++) {
float val = ps->getValueForHour(PRICE_DIRECTION_IMPORT, now, i);
values[i] = val;
if(val == PRICE_NO_VALUE) break;
if(val < min) min = val;
if(val > max) max = val;
if(min1hrIdx == -1 || min1hr > val) {
min1hr = val;
min1hrIdx = i;
}
if(i >= 2) {
i -= 2;
float val1 = values[i++];
float val2 = values[i++];
float val3 = val;
if(val1 == PRICE_NO_VALUE || val2 == PRICE_NO_VALUE || val3 == PRICE_NO_VALUE) continue;
float val3hr = val1+val2+val3;
if(min3hrIdx == -1 || min3hr > val3hr) {
min3hr = val3hr;
min3hrIdx = i-2;
}
}
if(i >= 5) {
i -= 5;
float val1 = values[i++];
float val2 = values[i++];
float val3 = values[i++];
float val4 = values[i++];
float val5 = values[i++];
float val6 = val;
if(val1 == PRICE_NO_VALUE || val2 == PRICE_NO_VALUE || val3 == PRICE_NO_VALUE || val4 == PRICE_NO_VALUE || val5 == PRICE_NO_VALUE || val6 == PRICE_NO_VALUE) continue;
float val6hr = val1+val2+val3+val4+val5+val6;
if(min6hrIdx == -1 || min6hr > val6hr) {
min6hr = val6hr;
min6hrIdx = i-5;
}
}
}
char ts1hr[24];
memset(ts1hr, 0, 24);
if(min1hrIdx > -1) {
time_t ts = now + (SECS_PER_HOUR * min1hrIdx);
tmElements_t tm;
breakTime(ts, tm);
sprintf_P(ts1hr, PSTR("%04d-%02d-%02dT%02d:00:00Z"), tm.Year+1970, tm.Month, tm.Day, tm.Hour);
}
char ts3hr[24];
memset(ts3hr, 0, 24);
if(min3hrIdx > -1) {
time_t ts = now + (SECS_PER_HOUR * min3hrIdx);
tmElements_t tm;
breakTime(ts, tm);
sprintf_P(ts3hr, PSTR("%04d-%02d-%02dT%02d:00:00Z"), tm.Year+1970, tm.Month, tm.Day, tm.Hour);
}
char ts6hr[24];
memset(ts6hr, 0, 24);
if(min6hrIdx > -1) {
time_t ts = now + (SECS_PER_HOUR * min6hrIdx);
tmElements_t tm;
breakTime(ts, tm);
sprintf_P(ts6hr, PSTR("%04d-%02d-%02dT%02d:00:00Z"), tm.Year+1970, tm.Month, tm.Day, tm.Hour);
}
char pf[4];
uint16_t pos = snprintf_P(json, BufferSize, PSTR("{\"id\":\"%s\","), WiFi.macAddress().c_str());
if(mqttConfig.payloadFormat != 6) {
memset(pf, 0, 4);
pos += snprintf_P(json+pos, BufferSize-pos, PSTR("\"prices\":{"));
} else {
strcpy_P(pf, PSTR("pr_"));
}
for(uint8_t i = 0;i < 38; i++) {
if(values[i] == PRICE_NO_VALUE) {
pos += snprintf_P(json+pos, BufferSize-pos, PSTR("\"%s%d\":null,"), pf, i);
} else {
pos += snprintf_P(json+pos, BufferSize-pos, PSTR("\"%s%d\":%.4f,"), pf, i, values[i]);
}
}
pos += snprintf_P(json+pos, BufferSize-pos, PSTR("\"%smin\":%.4f,\"%smax\":%.4f,\"%scheapest1hr\":\"%s\",\"%scheapest3hr\":\"%s\",\"%scheapest6hr\":\"%s\"}"),
pf,
min == INT16_MAX ? 0.0 : min,
pf,
max == INT16_MIN ? 0.0 : max,
pf,
ts1hr,
pf,
ts3hr,
pf,
ts6hr
);
if(mqttConfig.payloadFormat != 6) {
json[pos] = '}';
}
bool ret = false;
if(mqttConfig.payloadFormat == 5) {
char topic[192];
snprintf_P(topic, 192, PSTR("%s/prices"), mqttConfig.publishTopic);
ret = mqtt.publish(topic, json);
} else {
ret = mqtt.publish(mqttConfig.publishTopic, json);
}
loop();
return ret;
}
bool JsonMqttHandler::publishSystem(HwTools* hw, PriceService* ps, EnergyAccounting* ea) {
if(strlen(mqttConfig.publishTopic) == 0 || !mqtt.connected())
return false;
snprintf_P(json, BufferSize, PSTR("{\"id\":\"%s\",\"name\":\"%s\",\"up\":%d,\"vcc\":%.3f,\"rssi\":%d,\"temp\":%.2f,\"version\":\"%s\"}"),
WiFi.macAddress().c_str(),
mqttConfig.clientId,
(uint32_t) (millis64()/1000),
hw->getVcc(),
hw->getWifiRssi(),
hw->getTemperature(),
FirmwareVersion::VersionString
);
bool ret = false;
if(mqttConfig.payloadFormat == 5) {
char topic[192];
snprintf_P(topic, 192, PSTR("%s/system"), mqttConfig.publishTopic);
ret = mqtt.publish(topic, json);
} else {
ret = mqtt.publish(mqttConfig.publishTopic, json);
}
loop();
return ret;
}
uint8_t JsonMqttHandler::getFormat() {
return 0;
}
bool JsonMqttHandler::publishRaw(String data) {
return false;
}
void JsonMqttHandler::onMessage(String &topic, String &payload) {
}

View File

@@ -1,125 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _PRICESERVICE_H
#define _PRICESERVICE_H
#include <vector>
#include "TimeLib.h"
#include "Timezone.h"
#include "RemoteDebug.h"
#include "AmsConfiguration.h"
#include "EntsoeA44Parser.h"
#if defined(ESP8266)
#include <ESP8266HTTPClient.h>
#elif defined(ESP32) // ARDUINO_ARCH_ESP32
#include <HTTPClient.h>
#else
#warning "Unsupported board type"
#endif
#define SSL_BUF_SIZE 512
#define PRICE_DIRECTION_IMPORT 0x01
#define PRICE_DIRECTION_EXPORT 0x02
#define PRICE_DIRECTION_BOTH 0x03
#define PRICE_DAY_MO 0x01
#define PRICE_DAY_TU 0x02
#define PRICE_DAY_WE 0x04
#define PRICE_DAY_TH 0x08
#define PRICE_DAY_FR 0x10
#define PRICE_DAY_SA 0x12
#define PRICE_DAY_SU 0x14
#define PRICE_TYPE_FIXED 0x00
#define PRICE_TYPE_ADD 0x01
#define PRICE_TYPE_PCT 0x02
#define PRICE_TYPE_SUBTRACT 0x03
struct PriceConfig {
char name[32];
uint8_t direction;
uint8_t days;
uint32_t hours;
uint8_t type;
uint32_t value;
uint8_t start_month;
uint8_t start_dayofmonth;
uint8_t end_month;
uint8_t end_dayofmonth;
};
struct PricePart {
char name[32];
char description[32];
uint32_t value;
};
class PriceService {
public:
PriceService(RemoteDebug*);
void setup(PriceServiceConfig&);
bool loop();
char* getToken();
char* getCurrency();
char* getArea();
char* getSource();
float getValueForHour(uint8_t direction, int8_t hour);
float getValueForHour(uint8_t direction, time_t ts, int8_t hour);
float getEnergyPriceForHour(uint8_t direction, time_t ts, int8_t hour);
std::vector<PriceConfig>& getPriceConfig();
void setPriceConfig(uint8_t index, PriceConfig &priceConfig);
void cropPriceConfig(uint8_t size);
PricePart getPricePart(uint8_t index);
int16_t getLastError();
bool load();
bool save();
private:
RemoteDebug* debugger;
PriceServiceConfig* config = NULL;
HTTPClient* http = NULL;
uint8_t currentDay = 0, currentHour = 0;
uint8_t tomorrowFetchMinute = 15; // How many minutes over 13:00 should it fetch prices
uint8_t nextFetchDelayMinutes = 15;
uint64_t lastTodayFetch = 0;
uint64_t lastTomorrowFetch = 0;
uint64_t lastCurrencyFetch = 0;
PricesContainer* today = NULL;
PricesContainer* tomorrow = NULL;
std::vector<PriceConfig> priceConfig;
Timezone* tz = NULL;
static const uint16_t BufferSize = 256;
char* buf;
bool hub = false;
uint8_t* key = NULL;
uint8_t* auth = NULL;
float currencyMultiplier = 0;
int16_t lastError = 0;
PricesContainer* fetchPrices(time_t);
bool retrieve(const char* url, Stream* doc);
float getCurrencyMultiplier(const char* from, const char* to, time_t t);
void debugPrint(byte *buffer, int start, int length);
};
#endif

View File

@@ -1,18 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _PRICESCONTAINER_H
#define _PRICESCONTAINER_H
#define PRICE_NO_VALUE -127
struct PricesContainer {
char currency[4];
char measurementUnit[4];
int32_t points[25];
char source[4];
};
#endif

View File

@@ -1,591 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "PriceService.h"
#include <EEPROM.h>
#include "Uptime.h"
#include "TimeLib.h"
#include "DnbCurrParser.h"
#include "FirmwareVersion.h"
#include <LittleFS.h>
#include "AmsStorage.h"
#include "hexutils.h"
#include "GcmParser.h"
#if defined(ESP32)
#include <esp_task_wdt.h>
#endif
PriceService::PriceService(RemoteDebug* Debug) : priceConfig(std::vector<PriceConfig>()) {
this->buf = (char*) malloc(BufferSize);
debugger = Debug;
// Entso-E uses CET/CEST
TimeChangeRule CEST = {"CEST", Last, Sun, Mar, 2, 120};
TimeChangeRule CET = {"CET ", Last, Sun, Oct, 3, 60};
tz = new Timezone(CEST, CET);
tomorrowFetchMinute = 15 + random(45); // Random between 13:15 and 14:00
}
void PriceService::setup(PriceServiceConfig& config) {
if(this->config == NULL) {
this->config = new PriceServiceConfig();
}
memcpy(this->config, &config, sizeof(config));
lastTodayFetch = lastTomorrowFetch = lastCurrencyFetch = 0;
if(today != NULL) delete today;
if(tomorrow != NULL) delete tomorrow;
today = tomorrow = NULL;
if(http != NULL) {
delete http;
}
http = new HTTPClient();
http->setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
http->setReuse(false);
http->setTimeout(60000);
http->setUserAgent("ams2mqtt/" + String(FirmwareVersion::VersionString));
#if defined(AMS2MQTT_PRICE_KEY)
key = new uint8_t[16] AMS2MQTT_PRICE_KEY;
hub = true;
#else
hub = false;
#endif
#if defined(AMS2MQTT_PRICE_AUTHENTICATION)
auth = new uint8_t[16] AMS2MQTT_PRICE_AUTHENTICATION;
hub = hub && true;
#else
hub = false;
#endif
load();
}
char* PriceService::getToken() {
return this->config->entsoeToken;
}
char* PriceService::getCurrency() {
return this->config->currency;
}
char* PriceService::getArea() {
return this->config->area;
}
char* PriceService::getSource() {
if(this->today != NULL && this->tomorrow != NULL) {
if(strcmp(this->today->source, this->tomorrow->source) == 0) {
return this->today->source;
} else {
return "MIX";
}
} else if(today != NULL) {
return this->today->source;
} else if(tomorrow != NULL) {
return this->tomorrow->source;
}
return "";
}
float PriceService::getValueForHour(uint8_t direction, int8_t hour) {
time_t cur = time(nullptr);
return getValueForHour(direction, cur, hour);
}
float PriceService::getValueForHour(uint8_t direction, time_t ts, int8_t hour) {
float ret = getEnergyPriceForHour(direction, ts, hour);
if(ret == PRICE_NO_VALUE)
return ret;
tmElements_t tm;
breakTime(tz->toLocal(ts + (hour) * SECS_PER_HOUR), tm);
uint8_t day = 0x01 << (tm.Wday - 2);
uint32_t hrs = 0x01 << tm.Hour;
for (uint8_t i = 0; i < priceConfig.size(); i++) {
PriceConfig pc = priceConfig.at(i);
if(pc.type == PRICE_TYPE_FIXED) continue;
uint8_t start_month = pc.start_month == 0 || pc.start_month > 12 ? 1 : pc.start_month;
uint8_t start_dayofmonth = pc.start_dayofmonth == 0 || pc.start_dayofmonth > 31 ? 1 : pc.start_dayofmonth;
uint8_t end_month = pc.end_month == 0 || pc.end_month > 12 ? 12 : pc.end_month;
uint8_t end_dayofmonth = pc.end_dayofmonth == 0 || pc.end_dayofmonth > 31 ? 31 : pc.end_dayofmonth;
if((pc.direction & direction) == direction && (pc.days & day) == day && (pc.hours & hrs) == hrs && tm.Month >= start_month && tm.Day >= start_dayofmonth && tm.Month <= end_month && tm.Day <= end_dayofmonth) {
switch(pc.type) {
case PRICE_TYPE_ADD:
ret += pc.value / 10000.0;
break;
case PRICE_TYPE_SUBTRACT:
ret -= pc.value / 10000.0;
break;
case PRICE_TYPE_PCT:
ret += ((pc.value / 10000.0) * ret) / 100.0;
break;
}
}
}
return ret;
}
float PriceService::getEnergyPriceForHour(uint8_t direction, time_t ts, int8_t hour) {
tmElements_t tm;
breakTime(tz->toLocal(ts + (hour) * SECS_PER_HOUR), tm);
uint8_t day = 0x01 << (tm.Wday - 2);
uint32_t hrs = 0x01 << tm.Hour;
float value = PRICE_NO_VALUE;
for (uint8_t i = 0; i < priceConfig.size(); i++) {
PriceConfig pc = priceConfig.at(i);
if(pc.type != PRICE_TYPE_FIXED) continue;
uint8_t start_month = pc.start_month == 0 || pc.start_month > 12 ? 1 : pc.start_month;
uint8_t start_dayofmonth = pc.start_dayofmonth == 0 || pc.start_dayofmonth > 31 ? 1 : pc.start_dayofmonth;
uint8_t end_month = pc.end_month == 0 || pc.end_month > 12 ? 12 : pc.end_month;
uint8_t end_dayofmonth = pc.end_dayofmonth == 0 || pc.end_dayofmonth > 31 ? 31 : pc.end_dayofmonth;
if((pc.direction & direction) == direction && (pc.days & day) == day && (pc.hours & hrs) == hrs && tm.Month >= start_month && tm.Day >= start_dayofmonth && tm.Month <= end_month && tm.Day <= end_dayofmonth) {
if(value == PRICE_NO_VALUE) {
value = pc.value / 10000.0;
} else {
value += pc.value / 10000.0;
}
}
}
if(value != PRICE_NO_VALUE) return value;
int8_t pos = hour;
breakTime(tz->toLocal(ts), tm);
while(tm.Hour > 0) {
ts -= 3600;
breakTime(tz->toLocal(ts), tm);
pos++;
}
uint8_t hoursToday = 0;
uint8_t todayDate = tm.Day;
while(tm.Day == todayDate) {
ts += 3600;
breakTime(tz->toLocal(ts), tm);
hoursToday++;
}
if(pos > 49)
return PRICE_NO_VALUE;
float multiplier = 1.0;
if(pos >= hoursToday) {
if(tomorrow == NULL)
return PRICE_NO_VALUE;
if(tomorrow->points[pos-hoursToday] == PRICE_NO_VALUE)
return PRICE_NO_VALUE;
value = tomorrow->points[pos-hoursToday] / 10000.0;
if(strcmp(tomorrow->measurementUnit, "KWH") == 0) {
// Multiplier is 1
} else if(strcmp(tomorrow->measurementUnit, "MWH") == 0) {
multiplier *= 0.001;
} else {
return PRICE_NO_VALUE;
}
float mult = getCurrencyMultiplier(tomorrow->currency, config->currency, time(nullptr));
if(mult == 0) return PRICE_NO_VALUE;
multiplier *= mult;
} else if(pos >= 0) {
if(today == NULL)
return PRICE_NO_VALUE;
if(today->points[pos] == PRICE_NO_VALUE)
return PRICE_NO_VALUE;
value = today->points[pos] / 10000.0;
if(strcmp(today->measurementUnit, "KWH") == 0) {
// Multiplier is 1
} else if(strcmp(today->measurementUnit, "MWH") == 0) {
multiplier *= 0.001;
} else {
return PRICE_NO_VALUE;
}
float mult = getCurrencyMultiplier(today->currency, config->currency, time(nullptr));
if(mult == 0) return PRICE_NO_VALUE;
multiplier *= mult;
}
return value * multiplier;
}
bool PriceService::loop() {
uint64_t now = millis64();
if(now < 10000) return false; // Grace period
time_t t = time(nullptr);
if(t < FirmwareVersion::BuildEpoch) return false;
#ifndef AMS2MQTT_PRICE_KEY
if(strlen(getToken()) == 0) {
return false;
}
#endif
if(!config->enabled)
return false;
if(strlen(config->area) == 0)
return false;
if(strlen(config->currency) == 0)
return false;
tmElements_t tm;
breakTime(tz->toLocal(t), tm);
if(currentDay == 0) {
currentDay = tm.Day;
currentHour = tm.Hour;
}
if(currentDay != tm.Day) {
if(today != NULL) delete today;
if(tomorrow != NULL) {
today = tomorrow;
tomorrow = NULL;
}
currentDay = tm.Day;
currentHour = tm.Hour;
return today != NULL; // Only trigger MQTT publish if we have todays prices.
} else if(currentHour != tm.Hour) {
currentHour = tm.Hour;
return today != NULL; // Only trigger MQTT publish if we have todays prices.
}
bool readyToFetchForTomorrow = tomorrow == NULL && (tm.Hour > 13 || (tm.Hour == 13 && tm.Minute >= tomorrowFetchMinute)) && (lastTomorrowFetch == 0 || now - lastTomorrowFetch > (nextFetchDelayMinutes*60000));
if(today == NULL && (lastTodayFetch == 0 || now - lastTodayFetch > (nextFetchDelayMinutes*60000))) {
try {
lastTodayFetch = now;
today = fetchPrices(t);
} catch(const std::exception& e) {
if(lastError == 0) {
lastError = 900;
nextFetchDelayMinutes = 60;
}
today = NULL;
}
return today != NULL && !readyToFetchForTomorrow; // Only trigger MQTT publish if we have todays prices and we are not immediately ready to fetch price for tomorrow.
}
// Prices for next day are published at 13:00 CE(S)T, but to avoid heavy server traffic at that time, we will
// fetch with one hour (with some random delay) and retry every 15 minutes
if(readyToFetchForTomorrow) {
try {
lastTomorrowFetch = now;
tomorrow = fetchPrices(t+SECS_PER_DAY);
} catch(const std::exception& e) {
if(lastError == 0) {
lastError = 900;
nextFetchDelayMinutes = 60;
}
tomorrow = NULL;
}
return tomorrow != NULL;
}
return false;
}
bool PriceService::retrieve(const char* url, Stream* doc) {
#if defined(ESP32)
if(http->begin(url)) {
#if defined(ESP32)
esp_task_wdt_reset();
#elif defined(ESP8266)
ESP.wdtFeed();
#endif
int status = http->GET();
#if defined(ESP32)
esp_task_wdt_reset();
#elif defined(ESP8266)
ESP.wdtFeed();
#endif
if(status == HTTP_CODE_OK) {
http->writeToStream(doc);
http->end();
lastError = 0;
nextFetchDelayMinutes = 1;
return true;
} else {
lastError = status;
if(status == 429) {
nextFetchDelayMinutes = 15;
} else if(status == 404) {
nextFetchDelayMinutes = 10;
} else {
nextFetchDelayMinutes = 2;
}
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("(PriceService) Communication error, returned status: %d\n"), status);
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf(http->errorToString(status).c_str());
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf(http->getString().c_str());
http->end();
return false;
}
} else {
return false;
}
#endif
return false;
}
float PriceService::getCurrencyMultiplier(const char* from, const char* to, time_t t) {
if(strcmp(from, to) == 0)
return 1.00;
uint64_t now = millis64();
if(now > lastCurrencyFetch && (lastCurrencyFetch == 0 || (now - lastCurrencyFetch) > 60000)) {
lastCurrencyFetch = now;
DnbCurrParser p;
#if defined(ESP32)
esp_task_wdt_reset();
#elif defined(ESP8266)
ESP.wdtFeed();
#endif
float currencyMultiplier = 0;
snprintf_P(buf, BufferSize, PSTR("https://data.norges-bank.no/api/data/EXR/B.%s.NOK.SP?lastNObservations=1"), from);
if(retrieve(buf, &p)) {
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf_P(PSTR("(PriceService) got exchange rate %.4f\n"), p.getValue());
currencyMultiplier = p.getValue();
if(strncmp(to, "NOK", 3) != 0) {
snprintf_P(buf, BufferSize, PSTR("https://data.norges-bank.no/api/data/EXR/B.%s.NOK.SP?lastNObservations=1"), to);
if(retrieve(buf, &p)) {
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf_P(PSTR("(PriceService) got exchange rate %.4f\n"), p.getValue());
if(p.getValue() > 0.0) {
currencyMultiplier /= p.getValue();
} else {
currencyMultiplier = 0;
}
} else {
currencyMultiplier = 0;
}
}
}
if(currencyMultiplier != 0) {
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf_P(PSTR("(PriceService) Resulting currency multiplier: %.4f\n"), currencyMultiplier);
tmElements_t tm;
breakTime(t, tm);
lastCurrencyFetch = now + (SECS_PER_DAY * 1000) - (((((tm.Hour * 60) + tm.Minute) * 60) + tm.Second) * 1000) + (3600000 * 6) + (tomorrowFetchMinute * 60);
this->currencyMultiplier = currencyMultiplier;
} else {
if(debugger->isActive(RemoteDebug::WARNING)) debugger->printf_P(PSTR("(PriceService) Multiplier ended in success, but without value\n"));
lastCurrencyFetch = now + (SECS_PER_HOUR * 1000);
if(this->currencyMultiplier == 1) return 0;
}
}
return currencyMultiplier;
}
PricesContainer* PriceService::fetchPrices(time_t t) {
if(strlen(getToken()) > 0) {
tmElements_t tm;
breakTime(tz->toLocal(t), tm);
time_t e1 = t - (tm.Hour * 3600) - (tm.Minute * 60) - tm.Second; // Local midnight
time_t e2 = e1 + SECS_PER_DAY;
tmElements_t d1, d2;
breakTime(e1, d1);
breakTime(e2, d2);
snprintf_P(buf, BufferSize, PSTR("https://web-api.tp.entsoe.eu/api?securityToken=%s&documentType=A44&periodStart=%04d%02d%02d%02d%02d&periodEnd=%04d%02d%02d%02d%02d&in_Domain=%s&out_Domain=%s"),
getToken(),
d1.Year+1970, d1.Month, d1.Day, d1.Hour, 00,
d2.Year+1970, d2.Month, d2.Day, d2.Hour, 00,
config->area, config->area);
#if defined(ESP32)
esp_task_wdt_reset();
#elif defined(ESP8266)
ESP.wdtFeed();
#endif
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("(PriceService) Fetching prices for %02d.%02d.%04d\n"), tm.Day, tm.Month, tm.Year+1970);
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf_P(PSTR("(PriceService) url: %s\n"), buf);
EntsoeA44Parser a44;
if(retrieve(buf, &a44) && a44.getPoint(0) != PRICE_NO_VALUE) {
PricesContainer* ret = new PricesContainer();
a44.get(ret);
return ret;
} else {
return NULL;
}
} else if(hub) {
tmElements_t tm;
breakTime(tz->toLocal(t), tm);
String data;
snprintf_P(buf, BufferSize, PSTR("http://hub.amsleser.no/hub/price/%s/%d/%d/%d?currency=%s"),
config->area,
tm.Year+1970,
tm.Month,
tm.Day,
config->currency
);
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("(PriceService) Fetching prices for %02d.%02d.%04d\n"), tm.Day, tm.Month, tm.Year+1970);
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf_P(PSTR("(PriceService) url: %s\n"), buf);
#if defined(ESP8266)
WiFiClient client;
client.setTimeout(5000);
if(http->begin(client, buf)) {
#elif defined(ESP32)
if(http->begin(buf)) {
#endif
int status = http->GET();
#if defined(ESP32)
esp_task_wdt_reset();
#elif defined(ESP8266)
ESP.wdtFeed();
#endif
if(status == HTTP_CODE_OK) {
data = http->getString();
http->end();
uint8_t* content = (uint8_t*) (data.c_str());
DataParserContext ctx = {0,0,0,0};
ctx.length = data.length();
GCMParser gcm(key, auth);
int8_t gcmRet = gcm.parse(content, ctx);
if(gcmRet > 0) {
PricesContainer* ret = new PricesContainer();
for(uint8_t i = 0; i < 25; i++) {
ret->points[i] = PRICE_NO_VALUE;
}
memcpy(ret, content+gcmRet, sizeof(*ret));
for(uint8_t i = 0; i < 25; i++) {
ret->points[i] = ntohl(ret->points[i]);
}
lastError = 0;
nextFetchDelayMinutes = 1;
return ret;
} else {
lastError = gcmRet;
nextFetchDelayMinutes = 60;
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("(PriceService) Error code while decrypting prices: %d\n"), gcmRet);
}
} else {
lastError = status;
if(status == 429) {
nextFetchDelayMinutes = 60;
} else if(status == 404) {
nextFetchDelayMinutes = 15;
} else {
nextFetchDelayMinutes = 5;
}
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("(PriceService) Communication error, returned status: %d\n"), status);
if(debugger->isActive(RemoteDebug::ERROR)) {
debugger->printf(http->errorToString(status).c_str());
debugger->println();
}
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf(http->getString().c_str());
http->end();
}
}
}
return NULL;
}
void PriceService::debugPrint(byte *buffer, int start, int length) {
for (int i = start; i < start + length; i++) {
if (buffer[i] < 0x10)
debugger->print(F("0"));
debugger->print(buffer[i], HEX);
debugger->print(F(" "));
if ((i - start + 1) % 16 == 0)
debugger->println(F(""));
else if ((i - start + 1) % 4 == 0)
debugger->print(F(" "));
yield(); // Let other get some resources too
}
debugger->println(F(""));
}
int16_t PriceService::getLastError() {
return lastError;
}
std::vector<PriceConfig>& PriceService::getPriceConfig() {
return this->priceConfig;
}
void PriceService::setPriceConfig(uint8_t index, PriceConfig &priceConfig) {
stripNonAscii((uint8_t*) priceConfig.name, 32);
if(this->priceConfig.capacity() != index+1)
this->priceConfig.resize(index+1);
if(this->priceConfig.size() > index)
this->priceConfig[index] = priceConfig;
else
this->priceConfig.push_back(priceConfig);
}
void PriceService::cropPriceConfig(uint8_t size) {
this->priceConfig.resize(size);
this->priceConfig.shrink_to_fit();
}
bool PriceService::save() {
if(!LittleFS.begin()) {
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("(PriceService) Unable to load LittleFS\n"));
return false;
}
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("(PriceService) Saving price config\n"));
PriceConfig pc;
File file = LittleFS.open(FILE_PRICE_CONF, "w");
uint8_t count = priceConfig.size();
uint16_t bytes = 1 + (count * sizeof(pc));
char buf[bytes];
buf[0] = count;
for(uint8_t i = 0; i < count; i++) {
pc = priceConfig.at(i);
memcpy(buf + 1 + (i * sizeof(pc)), &pc, sizeof(pc));
}
for(unsigned long i = 0; i < bytes; i++) {
file.write(buf[i]);
}
file.close();
return true;
}
bool PriceService::load() {
if(!LittleFS.begin()) {
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf_P(PSTR("(PriceService) Unable to load LittleFS\n"));
return false;
}
if(!LittleFS.exists(FILE_PRICE_CONF)) {
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf_P(PSTR("(PriceService) No price config file\n"));
return false;
}
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf_P(PSTR("(PriceService) Loading price config\n"));
this->priceConfig.clear();
PriceConfig pc;
File file = LittleFS.open(FILE_PRICE_CONF, "r");
uint8_t count = file.read();
for(uint8_t i = 0; i < count; i++) {
file.readBytes((char*) &pc, sizeof(pc));
this->priceConfig.push_back(pc);
}
file.close();
return true;
}

View File

@@ -1,38 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _RAWMQTTHANDLER_H
#define _RAWMQTTHANDLER_H
#include "AmsMqttHandler.h"
class RawMqttHandler : public AmsMqttHandler {
public:
RawMqttHandler(MqttConfig& mqttConfig, RemoteDebug* debugger, char* buf) : AmsMqttHandler(mqttConfig, debugger, buf) {
full = mqttConfig.payloadFormat == 2;
topic = String(mqttConfig.publishTopic);
};
bool publish(AmsData* data, AmsData* previousState, EnergyAccounting* ea, PriceService* ps);
bool publishTemperatures(AmsConfiguration*, HwTools*);
bool publishPrices(PriceService*);
bool publishSystem(HwTools* hw, PriceService* ps, EnergyAccounting* ea);
bool publishRaw(String data);
void onMessage(String &topic, String &payload);
uint8_t getFormat();
private:
bool full;
String topic;
bool publishList1(AmsData* data, AmsData* meterState);
bool publishList2(AmsData* data, AmsData* meterState);
bool publishList3(AmsData* data, AmsData* meterState);
bool publishList4(AmsData* data, AmsData* meterState);
bool publishRealtime(EnergyAccounting* ea);
};
#endif

View File

@@ -1,356 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "RawMqttHandler.h"
#include "hexutils.h"
#include "Uptime.h"
bool RawMqttHandler::publish(AmsData* data, AmsData* meterState, EnergyAccounting* ea, PriceService* ps) {
if(topic.isEmpty() || !mqtt.connected())
return false;
if(data->getPackageTimestamp() > 0) {
mqtt.publish(topic + "/meter/dlms/timestamp", String(data->getPackageTimestamp()));
}
switch(data->getListType()) {
case 4:
publishList4(data, meterState);
loop();
case 3:
publishList3(data, meterState);
loop();
case 2:
publishList2(data, meterState);
loop();
case 1:
publishList1(data, meterState);
loop();
}
if(ea->isInitialized()) {
publishRealtime(ea);
loop();
}
return true;
}
bool RawMqttHandler::publishList1(AmsData* data, AmsData* meterState) {
if(full || meterState->getActiveImportPower() != data->getActiveImportPower()) {
mqtt.publish(topic + "/meter/import/active", String(data->getActiveImportPower()));
}
return true;
}
bool RawMqttHandler::publishList2(AmsData* data, AmsData* meterState) {
// Only send data if changed. ID and Type is sent on the 10s interval only if changed
if(full || meterState->getMeterId() != data->getMeterId()) {
mqtt.publish(topic + "/meter/id", data->getMeterId());
}
if(full || meterState->getMeterModel() != data->getMeterModel()) {
mqtt.publish(topic + "/meter/type", data->getMeterModel());
}
loop();
if(full || meterState->getL1Current() != data->getL1Current()) {
mqtt.publish(topic + "/meter/l1/current", String(data->getL1Current(), 2));
}
if(full || meterState->getL1Voltage() != data->getL1Voltage()) {
mqtt.publish(topic + "/meter/l1/voltage", String(data->getL1Voltage(), 2));
}
loop();
if(full || meterState->getL2Current() != data->getL2Current()) {
mqtt.publish(topic + "/meter/l2/current", String(data->getL2Current(), 2));
}
if(full || meterState->getL2Voltage() != data->getL2Voltage()) {
mqtt.publish(topic + "/meter/l2/voltage", String(data->getL2Voltage(), 2));
}
loop();
if(full || meterState->getL3Current() != data->getL3Current()) {
mqtt.publish(topic + "/meter/l3/current", String(data->getL3Current(), 2));
}
if(full || meterState->getL3Voltage() != data->getL3Voltage()) {
mqtt.publish(topic + "/meter/l3/voltage", String(data->getL3Voltage(), 2));
}
loop();
if(full || meterState->getReactiveExportPower() != data->getReactiveExportPower()) {
mqtt.publish(topic + "/meter/export/reactive", String(data->getReactiveExportPower()));
}
if(full || meterState->getActiveExportPower() != data->getActiveExportPower()) {
mqtt.publish(topic + "/meter/export/active", String(data->getActiveExportPower()));
}
if(full || meterState->getReactiveImportPower() != data->getReactiveImportPower()) {
mqtt.publish(topic + "/meter/import/reactive", String(data->getReactiveImportPower()));
}
return true;
}
bool RawMqttHandler::publishList3(AmsData* data, AmsData* meterState) {
// ID and type belongs to List 2, but I see no need to send that every 10s
mqtt.publish(topic + "/meter/id", data->getMeterId(), true, 0);
mqtt.publish(topic + "/meter/type", data->getMeterModel(), true, 0);
mqtt.publish(topic + "/meter/clock", String(data->getMeterTimestamp()));
mqtt.publish(topic + "/meter/import/reactive/accumulated", String(data->getReactiveImportCounter(), 3), true, 0);
mqtt.publish(topic + "/meter/import/active/accumulated", String(data->getActiveImportCounter(), 3), true, 0);
mqtt.publish(topic + "/meter/export/reactive/accumulated", String(data->getReactiveExportCounter(), 3), true, 0);
mqtt.publish(topic + "/meter/export/active/accumulated", String(data->getActiveExportCounter(), 3), true, 0);
return true;
}
bool RawMqttHandler::publishList4(AmsData* data, AmsData* meterState) {
if(full || meterState->getL1ActiveImportPower() != data->getL1ActiveImportPower()) {
mqtt.publish(topic + "/meter/import/l1", String(data->getL1ActiveImportPower()));
mqtt.loop();
}
if(full || meterState->getL2ActiveImportPower() != data->getL2ActiveImportPower()) {
mqtt.publish(topic + "/meter/import/l2", String(data->getL2ActiveImportPower()));
mqtt.loop();
}
if(full || meterState->getL3ActiveImportPower() != data->getL3ActiveImportPower()) {
mqtt.publish(topic + "/meter/import/l3", String(data->getL3ActiveImportPower()));
mqtt.loop();
}
if(full || meterState->getL1ActiveExportPower() != data->getL1ActiveExportPower()) {
mqtt.publish(topic + "/meter/export/l1", String(data->getL1ActiveExportPower()));
mqtt.loop();
}
if(full || meterState->getL2ActiveExportPower() != data->getL2ActiveExportPower()) {
mqtt.publish(topic + "/meter/export/l2", String(data->getL2ActiveExportPower()));
mqtt.loop();
}
if(full || meterState->getL3ActiveExportPower() != data->getL3ActiveExportPower()) {
mqtt.publish(topic + "/meter/export/l3", String(data->getL3ActiveExportPower()));
mqtt.loop();
}
if(full || meterState->getL1ActiveImportCounter() != data->getL1ActiveImportCounter()) {
mqtt.publish(topic + "/meter/import/l1/accumulated", String(data->getL1ActiveImportCounter(), 2));
mqtt.loop();
}
if(full || meterState->getL2ActiveImportCounter() != data->getL2ActiveImportCounter()) {
mqtt.publish(topic + "/meter/import/l2/accumulated", String(data->getL2ActiveImportCounter(), 2));
mqtt.loop();
}
if(full || meterState->getL3ActiveImportCounter() != data->getL3ActiveImportCounter()) {
mqtt.publish(topic + "/meter/import/l3/accumulated", String(data->getL3ActiveImportCounter(), 2));
mqtt.loop();
}
if(full || meterState->getL1ActiveExportCounter() != data->getL1ActiveExportCounter()) {
mqtt.publish(topic + "/meter/export/l1/accumulated", String(data->getL1ActiveExportCounter(), 2));
mqtt.loop();
}
if(full || meterState->getL2ActiveExportCounter() != data->getL2ActiveExportCounter()) {
mqtt.publish(topic + "/meter/export/l2/accumulated", String(data->getL2ActiveExportCounter(), 2));
mqtt.loop();
}
if(full || meterState->getL3ActiveExportCounter() != data->getL3ActiveExportCounter()) {
mqtt.publish(topic + "/meter/export/l3/accumulated", String(data->getL3ActiveExportCounter(), 2));
mqtt.loop();
}
if(full || meterState->getPowerFactor() != data->getPowerFactor()) {
mqtt.publish(topic + "/meter/powerfactor", String(data->getPowerFactor(), 2));
mqtt.loop();
}
if(full || meterState->getL1PowerFactor() != data->getL1PowerFactor()) {
mqtt.publish(topic + "/meter/l1/powerfactor", String(data->getL1PowerFactor(), 2));
mqtt.loop();
}
if(full || meterState->getL2PowerFactor() != data->getL2PowerFactor()) {
mqtt.publish(topic + "/meter/l2/powerfactor", String(data->getL2PowerFactor(), 2));
mqtt.loop();
}
if(full || meterState->getL3PowerFactor() != data->getL3PowerFactor()) {
mqtt.publish(topic + "/meter/l3/powerfactor", String(data->getL3PowerFactor(), 2));
mqtt.loop();
}
return true;
}
bool RawMqttHandler::publishRealtime(EnergyAccounting* ea) {
mqtt.publish(topic + "/realtime/import/hour", String(ea->getUseThisHour(), 3));
mqtt.loop();
mqtt.publish(topic + "/realtime/import/day", String(ea->getUseToday(), 2));
mqtt.loop();
mqtt.publish(topic + "/realtime/import/month", String(ea->getUseThisMonth(), 1));
mqtt.loop();
uint8_t peakCount = ea->getConfig()->hours;
if(peakCount > 5) peakCount = 5;
for(uint8_t i = 1; i <= peakCount; i++) {
mqtt.publish(topic + "/realtime/import/peak/" + String(i, 10), String(ea->getPeak(i).value / 100.0, 10), true, 0);
mqtt.loop();
}
mqtt.publish(topic + "/realtime/import/threshold", String(ea->getCurrentThreshold(), 10), true, 0);
mqtt.loop();
mqtt.publish(topic + "/realtime/import/monthmax", String(ea->getMonthMax(), 3), true, 0);
mqtt.loop();
mqtt.publish(topic + "/realtime/export/hour", String(ea->getProducedThisHour(), 3));
mqtt.loop();
mqtt.publish(topic + "/realtime/export/day", String(ea->getProducedToday(), 2));
mqtt.loop();
mqtt.publish(topic + "/realtime/export/month", String(ea->getProducedThisMonth(), 1));
mqtt.loop();
return true;
}
bool RawMqttHandler::publishTemperatures(AmsConfiguration* config, HwTools* hw) {
uint8_t c = hw->getTempSensorCount();
for(int i = 0; i < c; i++) {
TempSensorData* data = hw->getTempSensorData(i);
if(data != NULL && data->lastValidRead > -85) {
if(data->changed || full) {
mqtt.publish(topic + "/temperature/" + toHex(data->address), String(data->lastValidRead, 2));
mqtt.loop();
data->changed = false;
}
}
}
return c > 0;
}
bool RawMqttHandler::publishPrices(PriceService* ps) {
if(topic.isEmpty() || !mqtt.connected())
return false;
if(ps->getValueForHour(PRICE_DIRECTION_IMPORT, 0) == PRICE_NO_VALUE)
return false;
time_t now = time(nullptr);
float min1hr = 0.0, min3hr = 0.0, min6hr = 0.0;
int8_t min1hrIdx = -1, min3hrIdx = -1, min6hrIdx = -1;
float min = INT16_MAX, max = INT16_MIN;
float values[34];
for(int i = 0;i < 34; i++) values[i] = PRICE_NO_VALUE;
for(uint8_t i = 0; i < 34; i++) {
float val = ps->getValueForHour(PRICE_DIRECTION_IMPORT, now, i);
values[i] = val;
if(i > 23) continue;
if(val == PRICE_NO_VALUE) break;
if(val < min) min = val;
if(val > max) max = val;
if(min1hrIdx == -1 || min1hr > val) {
min1hr = val;
min1hrIdx = i;
}
if(i >= 2) {
i -= 2;
float val1 = values[i++];
float val2 = values[i++];
float val3 = val;
if(val1 == PRICE_NO_VALUE || val2 == PRICE_NO_VALUE || val3 == PRICE_NO_VALUE) continue;
float val3hr = val1+val2+val3;
if(min3hrIdx == -1 || min3hr > val3hr) {
min3hr = val3hr;
min3hrIdx = i-2;
}
}
if(i >= 5) {
i -= 5;
float val1 = values[i++];
float val2 = values[i++];
float val3 = values[i++];
float val4 = values[i++];
float val5 = values[i++];
float val6 = val;
if(val1 == PRICE_NO_VALUE || val2 == PRICE_NO_VALUE || val3 == PRICE_NO_VALUE || val4 == PRICE_NO_VALUE || val5 == PRICE_NO_VALUE || val6 == PRICE_NO_VALUE) continue;
float val6hr = val1+val2+val3+val4+val5+val6;
if(min6hrIdx == -1 || min6hr > val6hr) {
min6hr = val6hr;
min6hrIdx = i-5;
}
}
}
char ts1hr[24];
if(min1hrIdx > -1) {
time_t ts = now + (SECS_PER_HOUR * min1hrIdx);
tmElements_t tm;
breakTime(ts, tm);
sprintf(ts1hr, "%04d-%02d-%02dT%02d:00:00Z", tm.Year+1970, tm.Month, tm.Day, tm.Hour);
}
char ts3hr[24];
if(min3hrIdx > -1) {
time_t ts = now + (SECS_PER_HOUR * min3hrIdx);
tmElements_t tm;
breakTime(ts, tm);
sprintf(ts3hr, "%04d-%02d-%02dT%02d:00:00Z", tm.Year+1970, tm.Month, tm.Day, tm.Hour);
}
char ts6hr[24];
if(min6hrIdx > -1) {
time_t ts = now + (SECS_PER_HOUR * min6hrIdx);
tmElements_t tm;
breakTime(ts, tm);
sprintf(ts6hr, "%04d-%02d-%02dT%02d:00:00Z", tm.Year+1970, tm.Month, tm.Day, tm.Hour);
}
for(int i = 0; i < 34; i++) {
float val = values[i];
if(val == PRICE_NO_VALUE) {
mqtt.publish(topic + "/price/" + String(i), "", true, 0);
mqtt.loop();
} else {
mqtt.publish(topic + "/price/" + String(i), String(val, 4), true, 0);
mqtt.loop();
}
}
if(min != INT16_MAX) {
mqtt.publish(topic + "/price/min", String(min, 4), true, 0);
mqtt.loop();
}
if(max != INT16_MIN) {
mqtt.publish(topic + "/price/max", String(max, 4), true, 0);
mqtt.loop();
}
if(min1hrIdx != -1) {
mqtt.publish(topic + "/price/cheapest/1hr", String(ts1hr), true, 0);
mqtt.loop();
}
if(min3hrIdx != -1) {
mqtt.publish(topic + "/price/cheapest/3hr", String(ts3hr), true, 0);
mqtt.loop();
}
if(min6hrIdx != -1) {
mqtt.publish(topic + "/price/cheapest/6hr", String(ts6hr), true, 0);
mqtt.loop();
}
return true;
}
bool RawMqttHandler::publishSystem(HwTools* hw, PriceService* ps, EnergyAccounting* ea) {
if(topic.isEmpty() || !mqtt.connected())
return false;
mqtt.publish(topic + "/id", WiFi.macAddress(), true, 0);
mqtt.loop();
mqtt.publish(topic + "/uptime", String((uint32_t) (millis64()/1000)));
mqtt.loop();
float vcc = hw->getVcc();
if(vcc > 0) {
mqtt.publish(topic + "/vcc", String(vcc, 2));
mqtt.loop();
}
mqtt.publish(topic + "/mem", String(ESP.getFreeHeap()));
mqtt.loop();
mqtt.publish(topic + "/rssi", String(hw->getWifiRssi()));
mqtt.loop();
if(hw->getTemperature() > -85) {
mqtt.publish(topic + "/temperature", String(hw->getTemperature(), 2));
mqtt.loop();
}
return true;
}
uint8_t RawMqttHandler::getFormat() {
return full ? 3 : 2;
}
bool RawMqttHandler::publishRaw(String data) {
return false;
}
void RawMqttHandler::onMessage(String &topic, String &payload) {
}

View File

@@ -1,31 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#ifndef _REALTIMEPLOT_H
#define _REALTIMEPLOT_H
#include <stdint.h>
#include "AmsData.h"
#define REALTIME_SAMPLE 10000
#define REALTIME_SIZE 360
class RealtimePlot {
public:
RealtimePlot();
void update(AmsData& data);
int32_t getValue(uint16_t req);
int16_t getSize();
private:
int8_t* values;
uint8_t* scaling;
unsigned long lastMillis = 0;
double lastReading = 0;
uint16_t lastPos = 0;
};
#endif

View File

@@ -1,82 +0,0 @@
/**
* @copyright Utilitech AS 2023
* License: Fair Source
*
*/
#include "RealtimePlot.h"
#include <stdlib.h>
RealtimePlot::RealtimePlot() {
values = (int8_t*) malloc(REALTIME_SIZE);
scaling = (uint8_t*) malloc(REALTIME_SIZE);
memset(values, 0, REALTIME_SIZE);
memset(scaling, 0, REALTIME_SIZE);
}
void RealtimePlot::update(AmsData& data) {
unsigned long now = millis();
uint16_t pos = (now / REALTIME_SAMPLE) % REALTIME_SIZE;
if(lastMillis == 0) {
lastMillis = now;
lastReading = data.getActiveImportCounter() - data.getActiveExportCounter();
lastPos = pos;
return;
}
if(pos == lastPos && data.isCounterEstimated()) return;
unsigned long ms = now - lastMillis;
int32_t val; // A bit hacky this one, but just to avoid spikes at end of hour. Will mostly be correct
if(data.isCounterEstimated()) {
val = ((data.getActiveImportCounter() - data.getActiveExportCounter() - lastReading) * 1000) / (((float) ms) / 3600000.0);
} else {
val = data.getActiveImportPower() - data.getActiveExportPower();
}
uint8_t scale = 0;
int32_t update = val / pow(10, scale);
while(update > INT8_MAX || update < INT8_MIN) {
update = val / pow(10, ++scale);
}
if(pos < lastPos) {
for(uint16_t i = lastPos+1; i < REALTIME_SIZE; i++) {
values[i] = update;
scaling[i] = scale;
}
for(uint16_t i = 0; i <= pos; i++) {
values[i] = update;
scaling[i] = scale;
}
} else {
for(uint16_t i = lastPos+1; i <= pos; i++) {
values[i] = update;
scaling[i] = scale;
}
}
lastMillis = now;
lastReading = data.getActiveImportCounter() - data.getActiveExportCounter();
lastPos = pos;
}
int32_t RealtimePlot::getValue(uint16_t req) {
if(req > REALTIME_SIZE) return 0;
unsigned long now = millis();
if(req * REALTIME_SAMPLE > now) return 0;
unsigned long reqTime = now - (req * REALTIME_SAMPLE);
uint16_t pos = (now / REALTIME_SAMPLE) % REALTIME_SIZE;
uint16_t getPos;
if(reqTime > lastMillis) {
getPos = lastPos;
} else if(req > pos) {
getPos = REALTIME_SIZE + pos - req;
} else {
getPos = pos - req;
}
return values[getPos] * pow(10, scaling[getPos]);
}
int16_t RealtimePlot::getSize() {
return REALTIME_SIZE;
}

View File

@@ -1,24 +0,0 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
*.local
vite.config.local.js
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@@ -1,19 +0,0 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
<title>Amsleser</title>
<g transform="translate(-29.5,-83)">
<circle r="4.8016944" cy="123.56455" cx="55.064552"
style="fill:none;stroke:#045c7c;stroke-width:3;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<path d="m 41.298717,103.9049 a 24,24 0 0 1 27.531669,0"
style="fill:none;stroke:#045c7c;stroke-width:3.3;stroke-linecap:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<path d="m 35.562952,95.713384 a 34,34 0 0 1 39.003199,-2e-6"
style="fill:none;stroke:#045c7c;stroke-width:3.3;stroke-linecap:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<path d="m 47.034482,112.09642 a 14,14 0 0 1 16.06014,0"
style="fill:none;stroke:#045c7c;stroke-width:3.3;stroke-linecap:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<circle r="3" cy="105.99158" cx="38.181862"
style="fill:none;stroke:#045c7c;stroke-width:2.4;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<circle r="3" cy="97.959579" cx="77.491386"
style="fill:none;stroke:#045c7c;stroke-width:2.4;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.4 KiB

File diff suppressed because one or more lines are too long

View File

@@ -1,17 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<base href="/"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="/favicon.svg">
<link rel="mask-icon" href="/favicon.svg" color="#000000">
<title>AMS reader</title>
<script type="module" crossorigin src="/index.js"></script>
<link rel="stylesheet" href="/index.css">
</head>
<body class="bg-gray-100 dark:bg-gray-900">
<div id="app"></div>
</body>
</html>

File diff suppressed because one or more lines are too long

View File

@@ -1,15 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<base href="/"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="/favicon.svg">
<link rel="mask-icon" href="/favicon.svg" color="#000000">
<title>AMS reader</title>
</head>
<body class="bg-gray-100 dark:bg-gray-900">
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

View File

@@ -1,34 +0,0 @@
{
"compilerOptions": {
"moduleResolution": "Node",
"target": "ESNext",
"module": "ESNext",
/**
* svelte-preprocess cannot figure out whether you have
* a value or a type, so tell TypeScript to enforce using
* `import type` instead of `import` for Types.
*/
"importsNotUsedAsValues": "error",
"isolatedModules": true,
"resolveJsonModule": true,
/**
* To have warnings / errors of the Svelte compiler at the
* correct position, enable source maps by default.
*/
"sourceMap": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
/**
* Typecheck JS in `.svelte` and `.js` files by default.
* Disable this if you'd like to use dynamic types.
*/
"checkJs": true
},
/**
* Use global.d.ts instead of compilerOptions.types
* to avoid limiting type declarations.
*/
"include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"]
}

View File

@@ -1,19 +0,0 @@
// HTTPS required for this to work
// Remember: <link rel="manifest" href="manifest.json" />
{
"short_name": "amsreader",
"name": "AMS reader",
"icons": [
{
"src": "/favicon.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "any"
}
],
"start_url": "/",
"background_color": "#f3f4f6",
"display": "standalone",
"scope": "/",
"theme_color": "#7c3aed"
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,29 +0,0 @@
{
"name": "svelte-gui",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"local": "vite --config vite.config.local.js",
"build": "vite build",
"preview": "vite preview"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^2.1.0",
"@tailwindcss/forms": "^0.5.3",
"autoprefixer": "^10.4.14",
"http-proxy-middleware": "^2.0.6",
"postcss": "^8.4.31",
"postcss-load-config": "^4.0.1",
"svelte": "^3.58.0",
"svelte-navigator": "^3.2.2",
"svelte-preprocess": "^5.0.3",
"svelte-qrcode": "^1.0.0",
"tailwindcss": "^3.3.1",
"vite": "^4.3.1"
},
"dependencies": {
"cssnano": "^5.1.15"
}
}

View File

@@ -1,15 +0,0 @@
const tailwindcss = require("tailwindcss");
const autoprefixer = require("autoprefixer");
const cssnano = require("cssnano");
const config = {
plugins: [
//Some plugins, like tailwindcss/nesting, need to run before Tailwind,
tailwindcss(),
//But others, like autoprefixer, need to run after,
autoprefixer,
cssnano()
],
};
module.exports = config;

View File

@@ -1,11 +0,0 @@
self.addEventListener('install', (event) => {
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
return self.clients.claim();
});
self.addEventListener('fetch', function(event) {
event.respondWith(fetch(event.request));
});

View File

@@ -1,104 +0,0 @@
<script>
import { Router, Route, navigate } from "svelte-navigator";
import { getSysinfo, sysinfoStore, dataStore } from './lib/DataStores.js';
import { translationsStore, getTranslations } from "./lib/TranslationService.js";
import Favicon from './assets/favicon.svg'; // Need this for the build
import Header from './lib/Header.svelte';
import Dashboard from './lib/Dashboard.svelte';
import ConfigurationPanel from './lib/ConfigurationPanel.svelte';
import StatusPage from './lib/StatusPage.svelte';
import VendorPanel from './lib/VendorPanel.svelte';
import SetupPanel from './lib/SetupPanel.svelte';
import Mask from './lib/Mask.svelte';
import FileUploadComponent from "./lib/FileUploadComponent.svelte";
import ConsentComponent from "./lib/ConsentComponent.svelte";
import PriceConfig from "./lib/PriceConfig.svelte";
let basepath = document.getElementsByTagName('base')[0].getAttribute("href");
if(!basepath) basepath = "/";
let translations = {};
translationsStore.subscribe(update => {
translations = update;
});
let sysinfo = {};
sysinfoStore.subscribe(update => {
sysinfo = update;
if(sysinfo.vndcfg === false) {
navigate(basepath + "vendor");
} else if(sysinfo.usrcfg === false) {
navigate(basepath + "setup");
} else if(sysinfo.fwconsent === 0) {
navigate(basepath + "consent");
}
if(sysinfo.ui.k === 1) {
document.documentElement.classList.add('dark')
} else if (sysinfo.ui.k === 0) {
document.documentElement.classList.remove('dark')
} else {
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.classList.add('dark')
} else {
document.documentElement.classList.remove('dark')
}
}
if(sysinfo.ui.lang && sysinfo.ui.lang != translations?.language?.code) {
getTranslations(sysinfo.ui.lang);
}
});
getSysinfo();
let data = {};
dataStore.subscribe(update => {
data = update;
});
</script>
<div class="container mx-auto m-3">
<Router basepath={basepath}>
<Header data={data} basepath={basepath}/>
<Route path="/">
<Dashboard data={data} sysinfo={sysinfo}/>
</Route>
<Route path="/configuration">
<ConfigurationPanel sysinfo={sysinfo} basepath={basepath} data={data}/>
</Route>
<Route path="/priceconfig">
<PriceConfig basepath={basepath}/>
</Route>
<Route path="/status">
<StatusPage sysinfo={sysinfo} data={data}/>
</Route>
<Route path="/mqtt-ca">
<FileUploadComponent title="CA" action="/mqtt-ca"/>
</Route>
<Route path="/mqtt-cert">
<FileUploadComponent title="certificate" action="/mqtt-cert"/>
</Route>
<Route path="/mqtt-key">
<FileUploadComponent title="private key" action="/mqtt-key"/>
</Route>
<Route path="/consent">
<ConsentComponent sysinfo={sysinfo} basepath={basepath}/>
</Route>
<Route path="/setup">
<SetupPanel sysinfo={sysinfo}/>
</Route>
<Route path="/vendor">
<VendorPanel sysinfo={sysinfo} basepath={basepath}/>
</Route>
</Router>
{#if sysinfo.upgrading}
<Mask active=true message="Device is upgrading, please wait"/>
{:else if sysinfo.booting}
{#if sysinfo.trying}
<Mask active=true message="Device is booting, please wait. Trying to reach it on {sysinfo.trying}"/>
{:else}
<Mask active=true message="Device is booting, please wait"/>
{/if}
{/if}
</div>

View File

@@ -1,185 +0,0 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
.hdr {
@apply bg-violet-600 p-1 rounded-md mx-2 dark:bg-violet-900
}
.logo {
width: 2rem;
height: 2rem;
}
.cnt {
@apply m-2 p-2 rounded dark:bg-gray-800 bg-white dark:text-white shadow-lg dark:shadow-gray-900 dark:drop-shadow-md;
min-height: 268px;
}
.gwf {
@apply 2xl:col-span-6 xl:col-span-5 lg:col-span-4 md:col-span-3 sm:col-span-2 h-64
}
.in-pre {
@apply flex items-center bg-gray-100 dark:bg-gray-600 rounded-l-md border border-r-0 dark:border-gray-800 border-gray-300 px-3 whitespace-nowrap text-sm
}
.in-post {
@apply flex items-center bg-gray-100 dark:bg-gray-600 rounded-r-md border border-l-0 dark:border-gray-800 border-gray-300 px-3 whitespace-nowrap text-sm
}
.in-txt {
@apply h-10 shadow-sm border-gray-300 dark:border-gray-800 disabled:bg-gray-200 dark:disabled:bg-gray-700 disabled:text-white
disabled:cursor-not-allowed dark:text-white dark:bg-gray-700 dark:shadow-lg dark:border dark:focus:ring-4 dark:drop-shadow-lg
}
.in-f {
@apply in-txt rounded-l-md dark:placeholder:text-gray-400 dark:default:text-white disabled:text-white default:text-white
}
.in-m {
@apply in-txt border-l-0
}
.in-l {
@apply in-txt border-l-0 rounded-r-md dark:placeholder-white
}
.in-s {
@apply in-txt rounded-md w-full dark:text-white placeholder:text-gray-400
}
.tr {
@apply text-right
}
.bd-green {
@apply my-auto bg-green-600 text-green-100 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded
}
.bd-yellow {
@apply my-auto bg-yellow-600 text-yellow-100 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded
}
.bd-red {
@apply my-auto bg-red-600 text-red-100 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded
}
.bd-blue {
@apply my-auto bg-blue-600 text-blue-100 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded
}
.bd-gray {
@apply my-auto bg-gray-600 text-gray-100 text-xs font-semibold mr-2 px-2.5 py-0.5 rounded
}
.bd-on {
@apply my-auto bg-green-600 text-green-100 text-xs font-semibold mr-1 px-1 py-0.5 rounded
}
.bd-off {
@apply my-auto bg-gray-600 text-gray-100 text-xs font-semibold mr-1 px-1 py-0.5 rounded
}
.btn-pri {
@apply py-2 px-4 rounded bg-blue-600 text-white mr-3
}
.btn-red {
@apply py-2 px-4 rounded bg-red-600 text-white ml-2
}
.btn-yellow {
@apply py-2 px-4 rounded bg-yellow-600 text-white ml-2
}
.btn-pri-sm {
@apply text-xs py-1 px-2 rounded bg-blue-600 text-white mr-3
}
.btn-yellow-sm {
@apply text-xs py-1 px-2 rounded bg-yellow-600 text-white mr-3
}
.pl-root {
position: relative;
}
.pl-ov {
position: absolute;
top: 27%;
left: 25%;
width: 50%;
text-align: center;
}
.pl-val {
font-size: 1.7rem;
}
.pl-unt {
font-size: 1.0rem;
color: grey;
@apply dark:text-gray-200
}
.pl-sub {
padding-top: 10px;
font-size: 1.0rem;
}
.pl-snt {
font-size: 0.7rem;
color: grey;
@apply dark:text-gray-200
}
.pl-lab {
font-size: 1.0rem;
}
.chart {
width: 100%;
height: 100%;
margin: 0 auto;
}
svg {
position: relative;
width: 100%;
}
.tick {
font-family: Helvetica, Arial;
font-size: 0.85em;
font-weight: 200;
@apply dark:fill-white text-white
}
.tick line {
stroke: #e2e2e2;
stroke-dasharray: 2;
}
.tick text {
fill: #999;
text-anchor: start;
@apply dark:fill-white
}
.tick.tick-0 line {
stroke-dasharray: 0;
}
.tick.tick-green line {
stroke: #23ac05 !important;
}
.tick.tick-green text {
fill: #23ac05 !important;
}
.tick.tick-orange line {
stroke: #b19601 !important;
}
.tick.tick-orange text {
fill: #b19601 !important;
}
.x-axis .tick text {
text-anchor: middle;
}
.bars rect {
stroke: rgb(0,0,0);
stroke-opacity: 0.25;
opacity: 0.9;
}
.bars text {
font-family: Helvetica, Arial;
font-size: 0.85em;
display: block;
text-align: center;
}

View File

@@ -1,19 +0,0 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
<title>Amsleser</title>
<g transform="translate(-29.5,-83)">
<circle r="4.8016944" cy="123.56455" cx="55.064552"
style="fill:none;stroke:#045c7c;stroke-width:3;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<path d="m 41.298717,103.9049 a 24,24 0 0 1 27.531669,0"
style="fill:none;stroke:#045c7c;stroke-width:3.3;stroke-linecap:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<path d="m 35.562952,95.713384 a 34,34 0 0 1 39.003199,-2e-6"
style="fill:none;stroke:#045c7c;stroke-width:3.3;stroke-linecap:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<path d="m 47.034482,112.09642 a 14,14 0 0 1 16.06014,0"
style="fill:none;stroke:#045c7c;stroke-width:3.3;stroke-linecap:round;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<circle r="3" cy="105.99158" cx="38.181862"
style="fill:none;stroke:#045c7c;stroke-width:2.4;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
<circle r="3" cy="97.959579" cx="77.491386"
style="fill:none;stroke:#045c7c;stroke-width:2.4;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -1,97 +0,0 @@
<script>
import { fmtnum, capitalize, formatUnit } from "./Helpers";
import { translationsStore } from "./TranslationService";
export let sysinfo;
export let data;
export let currency;
export let hasExport;
let translations = {};
translationsStore.subscribe(update => {
translations = update;
});
let rih,rid,rim,ril, reh,red,rem,rel;
let hasCost = false;
let cols = 3
$: {
hasCost = data && data.h && (Math.abs(data.h.c) > 0.01 || Math.abs(data.d.c) > 0.01 || Math.abs(data.m.c) > 0.01 || Math.abs(data.h.i) > 0.01 || Math.abs(data.d.i) > 0.01 || Math.abs(data.m.i) > 0.01);
cols = hasCost ? 3 : 2;
rih = formatUnit(data?.h?.u*1000, "Wh");
rid = formatUnit(data?.d?.u*1000, "Wh");
rim = formatUnit(data?.m?.u*1000, "Wh");
ril = formatUnit(sysinfo?.last_month?.c*1000, "Wh");
reh = formatUnit(data?.h?.p*1000, "Wh");
red = formatUnit(data?.d?.p*1000, "Wh");
rem = formatUnit(data?.m?.p*1000, "Wh");
rel = formatUnit(sysinfo?.last_month?.p*1000, "Wh");
}
</script>
<div class="mx-2 text-sm">
<strong>{translations.realtime?.title ?? "Real time calculations"}</strong>
<br/><br/>
{#if data}
{#if hasExport}
<strong>{translations.common?.import ?? "Import"}</strong>
<div class="grid grid-cols-{cols} mb-3">
<div>{capitalize(translations.common?.hour ?? "Hour")}</div>
<div class="text-right">{rih[0]} {rih[1]}</div>
{#if hasCost}<div class="text-right">{fmtnum(data.h.c,2)} {currency}</div>{/if}
<div>{capitalize(translations.common?.day ?? "Day")}</div>
<div class="text-right">{rid[0]} {rid[1]}</div>
{#if hasCost}<div class="text-right">{fmtnum(data.d.c,1)} {currency}</div>{/if}
<div>{capitalize(translations.common?.month ?? "Month")}</div>
<div class="text-right">{rim[0]} {rim[1]}</div>
{#if hasCost}<div class="text-right">{fmtnum(data.m.c)} {currency}</div>{/if}
<div>{translations.realtime?.last_mo ?? "Last mo."}</div>
<div class="text-right">{ril[0]} {ril[1]}</div>
{#if hasCost}<div class="text-right">{fmtnum(sysinfo.last_month.c)} {currency}</div>{/if}
</div>
<strong>{translations.common?.export ?? "Export"}</strong>
<div class="grid grid-cols-{cols}">
<div>{capitalize(translations.common?.hour ?? "Hour")}</div>
<div class="text-right">{reh[0]} {reh[1]}</div>
{#if hasCost}<div class="text-right">{fmtnum(data.h.i,2)} {currency}</div>{/if}
<div>{capitalize(translations.common?.day ?? "Day")}</div>
<div class="text-right">{red[0]} {red[1]}</div>
{#if hasCost}<div class="text-right">{fmtnum(data.d.i,1)} {currency}</div>{/if}
<div>{capitalize(translations.common?.month ?? "Month")}</div>
<div class="text-right">{rem[0]} {rem[1]}</div>
{#if hasCost}<div class="text-right">{fmtnum(data.m.i)} {currency}</div>{/if}
<div>{translations.realtime?.last_mo ?? "Last mo."}</div>
<div class="text-right">{rel[0]} {rel[1]}</div>
{#if hasCost}<div class="text-right">{fmtnum(sysinfo.last_month.i)} {currency}</div>{/if}
</div>
{:else}
<strong>{translations.realtime?.consumption ?? "Consumption"}</strong>
<div class="grid grid-cols-2 mb-3">
<div>{capitalize(translations.common?.hour ?? "Hour")}</div>
<div class="text-right">{rih[0]} {rih[1]}</div>
<div>{capitalize(translations.common?.day ?? "Day")}</div>
<div class="text-right">{rid[0]} {rid[1]}</div>
<div>{capitalize(translations.common?.month ?? "Month")}</div>
<div class="text-right">{rim[0]} {rim[1]}</div>
<div>{translations.realtime?.last_month ?? "Last month"}</div>
<div class="text-right">{ril[0]} {ril[1]}</div>
</div>
{#if hasCost}
<strong>{translations.realtime?.cost ?? "Cost"}</strong>
<div class="grid grid-cols-2">
<div>{capitalize(translations.common?.hour ?? "Hour")}</div>
<div class="text-right">{fmtnum(data.h.c,2)} {currency}</div>
<div>{capitalize(translations.common?.day ?? "Day")}</div>
<div class="text-right">{fmtnum(data.d.c,1)} {currency}</div>
<div>{capitalize(translations.common?.month ?? "Month")}</div>
<div class="text-right">{fmtnum(data.m.c)} {currency}</div>
<div>{translations.realtime?.last_month ?? "Last month"}</div>
<div class="text-right">{fmtnum(sysinfo.last_month.c)} {currency}</div>
</div>
{/if}
{/if}
{/if}
</div>

View File

@@ -1,6 +0,0 @@
<script>
export let color;
export let title;
export let text;
</script>
<span title={title} class="bd-{color}">{text}</span>

View File

@@ -1,124 +0,0 @@
<script>
export let config;
let width;
let height;
let barWidth;
let xScale;
let yScale;
let heightAvailable;
let labelOffset;
let vertSwitch = 30;
let titleHeight = 0;
$: {
heightAvailable = height-titleHeight;
let innerWidth = width - (config.padding.left + config.padding.right);
barWidth = innerWidth / config.points.length;
labelOffset = barWidth < vertSwitch ? 30 : 15;
let yPerUnit = (heightAvailable-config.padding.top-config.padding.bottom)/(config.y.max-config.y.min);
xScale = function(i) {
return (i*barWidth)+config.padding.left;
};
yScale = function(i) {
let ret = 0;
if(i > config.y.max)
ret = config.padding.bottom;
else if(i < config.y.min)
ret = heightAvailable-config.padding.bottom;
else
ret = heightAvailable-config.padding.bottom-((i-config.y.min)*yPerUnit);
return ret > heightAvailable || ret < 0.0 ? 0.0 : ret;
};
};
</script>
<div class="chart" bind:clientWidth={width} bind:clientHeight={height}>
{#if config.x.ticks && config.points && heightAvailable}
{#if config.title}
<div class="text-sm font-bold" bind:clientHeight={titleHeight}>{config.title}</div>
{/if}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {heightAvailable}">
<!-- y axis -->
<g class="axis y-axis">
{#each config.y.ticks as tick}
{#if !isNaN(yScale(tick.value))}
<g class="tick tick-{tick.value} tick-{tick.color}" transform="translate(0, {yScale(tick.value)})">
<line x2="100%"></line>
<text y="-4" x={tick.align == 'right' ? '85%' : ''}>{tick.label}</text>
</g>
{/if}
{/each}
</g>
<!-- x axis -->
<g class="axis x-axis">
{#each config.x.ticks as point, i}
{#if !isNaN(xScale(i))}
<g class="tick" transform="translate({xScale(i)},{heightAvailable})">
{#if barWidth > 20 || i%2 == 0}
<text x="{barWidth/2}" y="-4">{point.label}</text>
{/if}
</g>
{/if}
{/each}
</g>
<g class='bars'>
{#each config.points as point, i}
{#if !isNaN(xScale(i)) && !isNaN(yScale(point.value))}
<g>
{#if point.value !== undefined}
<rect
x="{xScale(i) + 2}"
y="{yScale(point.value)}"
width="{barWidth - 4}"
height="{yScale(config.y.min) - yScale(Math.min(config.y.min, 0) + point.value)}"
fill="{point.color}"
/>
{#if barWidth > 15}
<text
width="{barWidth - 4}"
dominant-baseline="middle"
text-anchor="{barWidth < vertSwitch || point.labelAngle ? 'left' : 'middle'}"
fill="{yScale(point.value) > yScale(0)-labelOffset && !config.dark ? point.color : 'white'}"
transform="translate({xScale(i) + barWidth/2} {yScale(point.value) > yScale(0) - labelOffset ? yScale(point.value) - labelOffset : yScale(point.value) + 10}) rotate({point.labelAngle ? point.labelAngle : barWidth < vertSwitch ? 90 : 0})"
>{point.label}</text>
{#if point.title}
<title>{point.title}</title>
{/if}
{/if}
{/if}
</g>
<g>
{#if point.value2 > 0.0001}
<rect
x="{xScale(i) + 2}"
y="{yScale(0)}"
width="{barWidth - 4}"
height="{yScale(config.y.min) - yScale(config.y.min + point.value2)}"
fill="{point.color2 ? point.color2 : point.color}"
/>
{#if barWidth > 15}
<text
width="{barWidth - 4}"
dominant-baseline="middle"
text-anchor="{'middle'}"
fill="{yScale(-point.value2) < yScale(0) + 15 && !config.dark ? point.color2 ? point.color2 : point.color : 'white'}"
transform="translate({xScale(i) + (barWidth/2)} {yScale(-point.value2) < yScale(0) + 15 ? yScale(-point.value2) + 15 : yScale(-point.value2) - 14}) rotate({barWidth < vertSwitch ? 90 : 0})"
>{point.label2}</text>
{#if point.title2}
<title>{point.title2}</title>
{/if}
{/if}
{/if}
</g>
{/if}
{/each}
</g>
</svg>
{/if}
</div>

View File

@@ -1,65 +0,0 @@
<script>
import {boardtype} from './Helpers.js'
export let chip;
</script>
<option value={-1}></option>
{#if chip == 'esp8266'}
<optgroup label="amsleser.no">
<option value={7}>{boardtype(chip, 7)}</option>
<option value={5}>{boardtype(chip, 5)}</option>
<option value={4}>{boardtype(chip, 4)}</option>
<option value={3}>{boardtype(chip, 3)}</option>
</optgroup>
<optgroup label="Custom hardware">
<option value={2}>{boardtype(chip, 2)}</option>
<option value={1}>{boardtype(chip, 1)}</option>
<option value={0}>{boardtype(chip, 0)}</option>
</optgroup>
<optgroup label="Generic hardware">
<option value={101}>{boardtype(chip, 101)}</option>
<option value={100}>{boardtype(chip, 100)}</option>
</optgroup>
{/if}
{#if chip == 'esp32'}
<optgroup label="Generic hardware">
<option value={201}>{boardtype(chip, 201)}</option>
<option value={202}>{boardtype(chip, 202)}</option>
<option value={203}>{boardtype(chip, 203)}</option>
<option value={241}>{boardtype(chip, 241)}</option>
<option value={242}>{boardtype(chip, 242)}</option>
<option value={243}>{boardtype(chip, 243)}</option>
<option value={200}>{boardtype(chip, 200)}</option>
</optgroup>
{/if}
{#if chip == 'esp32s2'}
<optgroup label="amsleser.no">
<option value={7}>{boardtype(chip, 7)}</option>
<option value={6}>{boardtype(chip, 6)}</option>
<option value={5}>{boardtype(chip, 5)}</option>
</optgroup>
<optgroup label="Generic hardware">
<option value={51}>{boardtype(chip, 51)}</option>
<option value={50}>{boardtype(chip, 50)}</option>
</optgroup>
{/if}
{#if chip == 'esp32c3'}
<optgroup label="Custom hardware">
<option value={8}>{boardtype(chip, 8)}</option>
</optgroup>
<optgroup label="Generic hardware">
<option value={71}>{boardtype(chip, 71)}</option>
<option value={70}>{boardtype(chip, 70)}</option>
</optgroup>
{/if}
{#if chip == 'esp32solo'}
<optgroup label="Generic hardware">
<option value={200}>{boardtype(chip, 200)}</option>
</optgroup>
{/if}
{#if chip == 'esp32s3'}
<optgroup label="Generic hardware">
<option value={80}>{boardtype(chip, 80)}</option>
</optgroup>
{/if}

View File

@@ -1,26 +0,0 @@
<script>
import { zeropad, addHours } from './Helpers.js';
import { translationsStore } from './TranslationService.js';
let translations = {};
translationsStore.subscribe(update => {
translations = update;
});
export let timestamp;
export let fullTimeColor;
export let offset;
let clockOk;
$:{
clockOk = Math.abs(new Date().getTime()-timestamp.getTime()) < 300000;
if(!isNaN(offset))
addHours(timestamp, offset - ((24 + timestamp.getHours() - timestamp.getUTCHours())%24));
}
</script>
{#if clockOk }
{`${zeropad(timestamp.getDate())}. ${translations.months ? translations.months?.[timestamp.getMonth()] : zeropad(timestamp.getMonth())} ${zeropad(timestamp.getHours())}:${zeropad(timestamp.getMinutes())}`}
{:else}
<span class="{fullTimeColor}">{`${zeropad(timestamp.getDate())}.${zeropad(timestamp.getMonth()+1)}.${timestamp.getFullYear()} ${zeropad(timestamp.getHours())}:${zeropad(timestamp.getMinutes())}`}</span>
{/if}

View File

@@ -1,868 +0,0 @@
<script>
import { getConfiguration, configurationStore } from './ConfigurationStore'
import { fetchWithTimeout, sysinfoStore } from './DataStores.js';
import { translationsStore } from './TranslationService';
import { wiki } from './Helpers.js';
import UartSelectOptions from './UartSelectOptions.svelte';
import Mask from './Mask.svelte'
import Badge from './Badge.svelte';
import CountrySelectOptions from './CountrySelectOptions.svelte';
import { Link, navigate } from 'svelte-navigator';
import SubnetOptions from './SubnetOptions.svelte';
import QrCode from 'svelte-qrcode';
export let basepath = "/";
export let sysinfo = {};
export let data;
let translations = {};
translationsStore.subscribe(update => {
translations = update;
});
let uiElements = [{
name: 'Import gauge',
key: 'i'
},{
name: 'Export gauge',
key: 'e'
},{
name: 'Voltage',
key: 'v'
},{
name: 'Amperage',
key: 'a'
},{
name: 'Per phase',
key: 'h'
},{
name: 'Power factor',
key: 'f'
},{
name: 'Reactive',
key: 'r'
},{
name: 'Realtime',
key: 'c'
},{
name: 'Peaks',
key: 't'
},{
name: 'Realtime plot',
key: 'l'
},{
name: 'Price',
key: 'p'
},{
name: 'Day plot',
key: 'd'
},{
name: 'Month plot',
key: 'm'
},{
name: 'Temperature plot',
key: 's'
},{
name: 'Dark mode',
key: 'k'
}];
let loading = true;
let saving = false;
let configuration;
let languages = [];
configurationStore.subscribe(update => {
if(update.version) {
configuration = update;
loading = false;
languages = [{ code: 'en', name: 'English'}];
if(configuration?.u?.lang && configuration.u.lang != 'en') {
languages.push({ code: configuration.u.lang, name: translations.language?.name ?? "Unknown"})
}
languages.push({ code: 'hub', name: 'Load from server'})
}
});
getConfiguration();
let isFactoryReset = false;
let isFactoryResetComplete = false;
async function factoryReset() {
if(confirm("Factory reset?")) {
isFactoryReset = true;
const data = new URLSearchParams();
data.append("perform", "true");
const response = await fetch('reset', {
method: 'POST',
body: data
});
let res = (await response.json());
isFactoryReset = false;
isFactoryResetComplete = res.success;
}
}
async function handleSubmit(e) {
saving = true;
const formData = new FormData(e.target);
const data = new URLSearchParams();
for (let field of formData) {
const [key, value] = field
data.append(key, value)
}
const response = await fetch('save', {
method: 'POST',
body: data
});
let res = (await response.json())
sysinfoStore.update(s => {
s.hostname = formData.get('gh');
s.usrcfg = res.success;
s.booting = res.reboot;
if(formData.get('nm') == 'static') {
s.net.ip = formData.get('ni');
s.net.mask = formData.get('nu');
s.net.gw = formData.get('ng');
s.net.dns1 = formData.get('nd');
}
s.ui = configuration.u;
return s;
});
saving = false;
navigate(basepath);
}
async function reboot() {
const response = await fetch('reboot', {
method: 'POST'
});
let res = (await response.json())
}
const askReboot = function() {
if(confirm('Reboot?')) {
sysinfoStore.update(s => {
s.booting = true;
return s;
});
reboot();
}
}
async function askDeleteCa() {
if(confirm('Are you sure you want to delete CA?')) {
const response = await fetch('mqtt-ca', {
method: 'POST'
});
let res = (await response.text())
configurationStore.update(c => {
c.q.s.c = false;
return c;
});
}
}
async function askDeleteCert() {
if(confirm('Are you sure you want to delete cert?')) {
const response = await fetch('mqtt-cert', {
method: 'POST'
});
let res = (await response.text())
configurationStore.update(c => {
c.q.s.r = false;
return c;
});
}
}
async function askDeleteKey() {
if(confirm('Are you sure you want to delete key?')) {
const response = await fetch('mqtt-key', {
method: 'POST'
});
let res = (await response.text())
configurationStore.update(c => {
c.q.s.k = false;
return c;
});
}
}
const updateMqttPort = function() {
if(configuration.q.s.e) {
if(configuration.q.p == 1883) configuration.q.p = 8883;
} else {
if(configuration.q.p == 8883) configuration.q.p = 1883;
}
}
async function languageChanged() {
if(configuration.u.lang == 'hub') {
const response = await fetchWithTimeout("http://hub.amsleser.no/hub/language/list.json");
languages = (await response.json())
configuration.u.lang = translations.language.code;
}
}
let gpioMax = 44;
$: {
gpioMax = sysinfo.chip == 'esp8266' ? 16 : sysinfo.chip == 'esp32s2' ? 44 : 39;
}
</script>
<form on:submit|preventDefault={handleSubmit} autocomplete="off">
<div class="grid xl:grid-cols-4 lg:grid-cols-2 md:grid-cols-2">
{#if configuration?.g}
<div class="cnt">
<strong class="text-sm">{translations.conf?.general?.title ?? "General"}</strong>
<a href="{wiki('General-configuration')}" target="_blank" class="float-right">&#9432;</a>
<input type="hidden" name="g" value="true"/>
<div class="my-1">
<div class="flex">
<div>
{translations.conf?.general?.hostname ?? "Hostname"}<br/>
<input name="gh" bind:value={configuration.g.h} type="text" class="in-f w-full" pattern="[A-Za-z0-9-]+"/>
</div>
<div>
{translations.conf?.general?.timezone ?? "Time zone"}<br/>
<select name="gt" bind:value={configuration.g.t} class="in-l w-full">
<CountrySelectOptions/>
</select>
</div>
</div>
</div>
<input type="hidden" name="p" value="true"/>
<div class="my-1">
<div class="flex">
<div class="w-full">
{translations.conf?.price?.region ?? "Price region"}<br/>
<select name="pr" bind:value={configuration.p.r} class="in-f w-full">
<optgroup label="Norway">
{#if !configuration.p.t}
<option value="NO1S">NO1 with support</option>
<option value="NO2S">NO2 with support</option>
<option value="NO3S">NO3 with support</option>
<option value="NO4S">NO4 with support</option>
<option value="NO5S">NO5 with support</option>
{/if}
<option value="10YNO-1--------2">NO1</option>
<option value="10YNO-2--------T">NO2</option>
<option value="10YNO-3--------J">NO3</option>
<option value="10YNO-4--------9">NO4</option>
<option value="10Y1001A1001A48H">NO5</option>
</optgroup>
<optgroup label="Sweden">
<option value="10Y1001A1001A44P">SE1</option>
<option value="10Y1001A1001A45N">SE2</option>
<option value="10Y1001A1001A46L">SE3</option>
<option value="10Y1001A1001A47J">SE4</option>
</optgroup>
<optgroup label="Denmark">
<option value="10YDK-1--------W">DK1</option>
<option value="10YDK-2--------M">DK2</option>
</optgroup>
<option value="10YAT-APG------L">Austria</option>
<option value="10YBE----------2">Belgium</option>
<option value="10YCZ-CEPS-----N">Czech Republic</option>
<option value="10Y1001A1001A39I">Estonia</option>
<option value="10YFI-1--------U">Finland</option>
<option value="10YFR-RTE------C">France</option>
<option value="10Y1001A1001A83F">Germany</option>
<option value="10YGB----------A">Great Britain</option>
<option value="10YLV-1001A00074">Latvia</option>
<option value="10YLT-1001A0008Q">Lithuania</option>
<option value="10YNL----------L">Netherland</option>
<option value="10YPL-AREA-----S">Poland</option>
<option value="10YCH-SWISSGRIDZ">Switzerland</option>
</select>
</div>
<div>
{translations.conf?.price?.currency ?? "Currency"}<br/>
<select name="pc" bind:value={configuration.p.c} class="in-l">
{#each ["NOK","SEK","DKK","EUR","CHF"] as c}
<option value={c}>{c}</option>
{/each}
</select>
</div>
</div>
</div>
<div class="my-1">
<Link to="/priceconfig" class="text-blue-600 hover:text-blue-800">{translations.conf?.price?.conf ?? "Configure"}</Link>
</div>
<div class="my-1">
<label><input type="checkbox" name="pe" value="true" bind:checked={configuration.p.e} class="rounded mb-1"/> {translations.conf?.price?.enabled ?? "Enabled"}</label>
{#if configuration.p.e && sysinfo.chip != 'esp8266'}
<br/><input name="pt" bind:value={configuration.p.t} type="text" class="in-s" placeholder={translations.conf?.price?.api_key_placeholder ?? ""}/>
{/if}
</div>
<div class="my-1">
{translations.conf?.general?.security?.title ?? "Security"}<br/>
<select name="gs" bind:value={configuration.g.s} class="in-s">
<option value={0}>{translations.conf?.general?.security?.none ?? "None"}</option>
<option value={1}>{translations.conf?.general?.security?.conf ?? "Conf"}</option>
<option value={2}>{translations.conf?.general?.security?.all ?? "All"}</option>
</select>
</div>
{#if configuration.g.s > 0}
<div class="my-1">
{translations.conf?.general?.security?.username ?? "Username"}<br/>
<input name="gu" bind:value={configuration.g.u} type="text" class="in-s" maxlength="36"/>
</div>
<div class="my-1">
{translations.conf?.general?.security?.password ?? "Password"}<br/>
<input name="gp" bind:value={configuration.g.p} type="password" class="in-s" maxlength="36"/>
</div>
{/if}
<div class="my-1">
{translations.conf?.general?.context ?? "Context"}<br/>
<input name="gc" bind:value={configuration.g.c} type="text" pattern="[A-Za-z0-9]+" placeholder={translations.conf?.general?.context_placeholder ?? "/"} class="in-s" maxlength="36"/>
</div>
</div>
{/if}
{#if configuration?.m}
<div class="cnt">
<strong class="text-sm">{translations.conf?.meter?.title ?? "Meter"}</strong>
<a href="{wiki('Meter-configuration')}" target="_blank" class="float-right">&#9432;</a>
<input type="hidden" name="m" value="true"/>
<input type="hidden" name="mo" value="1"/>
<div class="my-1">
{translations.conf?.meter?.comm?.title ?? "Communication"}<br/>
<select name="ma" bind:value={configuration.m.a} class="in-s">
<option value={0}>{translations.conf?.meter?.comm?.passive ?? "Passive"}</option>
<option value={2}>{translations.conf?.meter?.comm?.pulse ?? "Pulse"}</option>
</select>
</div>
{#if configuration.m.a === 2}
<div class="my-1">
<span>{translations.conf?.meter?.pulses ?? "Pulses per kWh"}</span>
<input name="mb" bind:value={configuration.m.b} class="in-s tr" type="number" min={1} max={3600}/>
</div>
{:else}
<div class="my-1">
<span class="float-right">{translations.conf?.meter?.buffer ?? "Buffer size"}</span>
<span>{translations.conf?.meter?.serial ?? "Serial conf."}</span>
<label class="mt-2 ml-3 whitespace-nowrap"><input name="mi" value="true" bind:checked={configuration.m.i} type="checkbox" class="rounded mb-1"/> {translations.conf?.meter?.inverted ?? "inverted"}</label>
<div class="flex w-full">
<select name="mb" bind:value={configuration.m.b} class="in-f tr w-1/2">
<option value={0} disabled={configuration.m.b != 0}>Autodetect</option>
{#each [3,12,24,48,96,192,384,576,1152] as b}
<option value={b*100}>{b*100}</option>
{/each}
</select>
<select name="mp" bind:value={configuration.m.p} class="in-m" disabled={configuration.m.b == 0}>
<option value={0} disabled={configuration.m.b != 0}>-</option>
<option value={2}>7N1</option>
<option value={3}>8N1</option>
<option value={7}>8N2</option>
<option value={10}>7E1</option>
<option value={11}>8E1</option>
</select>
<input name="ms" type="number" bind:value={configuration.m.s} min={64} max={sysinfo.chip == 'esp8266' ? configuration.i.h.p == 3 || configuration.i.h.p == 113 ? 512 : 256 : 4096} step={64} class="in-l tr w-1/2">
</div>
</div>
{/if}
<div class="my-1">
{translations.common?.voltage ?? "Voltage"}<br/>
<select name="md" bind:value={configuration.m.d} class="in-s">
<option value={2}>400V (TN)</option>
<option value={1}>230V (IT/TT)</option>
</select>
</div>
<div class="my-1 flex">
<div class="mx-1">
{translations.conf?.meter?.fuse ?? "Main fuse"}<br/>
<label class="flex">
<input name="mf" bind:value={configuration.m.f} type="number" min="5" max="65535" class="in-f tr w-full"/>
<span class="in-post">A</span>
</label>
</div>
<div class="mx-1">
{translations.conf?.meter?.prod ?? "Production"}<br/>
<label class="flex">
<input name="mr" bind:value={configuration.m.r} type="number" min="0" max="65535" class="in-f tr w-full"/>
<span class="in-post">kWp</span>
</label>
</div>
</div>
<div class="my-1">
</div>
<div class="my-1">
<label><input type="checkbox" name="me" value="true" bind:checked={configuration.m.e.e} class="rounded mb-1"/> {translations.conf?.meter?.encrypted ?? "Encrypted"}</label>
{#if configuration.m.e.e}
<br/><input name="mek" bind:value={configuration.m.e.k} type="text" class="in-s"/>
{/if}
</div>
{#if configuration.m.e.e}
<div class="my-1">
{translations.conf?.meter?.authkey ?? "Authentication key"}<br/>
<input name="mea" bind:value={configuration.m.e.a} type="text" class="in-s"/>
</div>
{/if}
<label><input type="checkbox" name="mm" value="true" bind:checked={configuration.m.m.e} class="rounded mb-1"/> {translations.conf?.meter?.multipliers?.title ?? "Multipliers"}</label>
{#if configuration.m.m.e}
<div class="flex my-1">
<div class="w-1/4">
{translations.conf?.meter?.multipliers?.watt ?? "Watt"}<br/>
<input name="mmw" bind:value={configuration.m.m.w} type="number" min="0.00" max="1000" step="0.001" class="in-f tr w-full"/>
</div>
<div class="w-1/4">
{translations.conf?.meter?.multipliers?.volt ?? "Volt"}<br/>
<input name="mmv" bind:value={configuration.m.m.v} type="number" min="0.00" max="1000" step="0.001" class="in-m tr w-full"/>
</div>
<div class="w-1/4">
{translations.conf?.meter?.multipliers?.amp ?? "Amp"}<br/>
<input name="mma" bind:value={configuration.m.m.a} type="number" min="0.00" max="1000" step="0.001" class="in-m tr w-full"/>
</div>
<div class="w-1/4">
{translations.conf?.meter?.multipliers?.kwh ?? "kWh"}<br/>
<input name="mmc" bind:value={configuration.m.m.c} type="number" min="0.00" max="1000" step="0.001" class="in-l tr w-full"/>
</div>
</div>
{/if}
</div>
{/if}
{#if configuration?.w}
<div class="cnt">
<strong class="text-sm">{translations.conf?.connection?.title ?? "Connection"}</strong>
<a href="{wiki('WiFi-configuration')}" target="_blank" class="float-right">&#9432;</a>
<input type="hidden" name="w" value="true"/>
<div class="my-1">
<select name="nc" class="in-s" bind:value={configuration.n.c}>
<option value={1}>{translations.conf?.connection?.wifi ?? "WiFi"}</option>
<option value={2}>{translations.conf?.connection?.ap ?? "AP"}</option>
{#if sysinfo.if && sysinfo.if.eth}
<option value={3}>{translations.conf?.connection?.eth ?? "Ethernet"}</option>
{/if}
</select>
</div>
{#if configuration.n.c == 1 || configuration.n.c == 2}
<div class="my-1">
{translations.conf?.connection?.ssid ?? "SSID"}<br/>
<input name="ws" bind:value={configuration.w.s} type="text" class="in-s"/>
</div>
<div class="my-1">
{translations.conf?.connection?.psk ?? "Password"}<br/>
<input name="wp" bind:value={configuration.w.p} type="password" class="in-s"/>
</div>
<div class="my-1 flex">
<div class="w-1/2">
{translations.conf?.connection?.ps?.title ?? "Power saving"}<br/>
<select name="wz" bind:value={configuration.w.z} class="in-s">
<option value={255}>{translations.conf?.connection?.ps?.default ?? "Default"}</option>
<option value={0}>{translations.conf?.connection?.ps?.off ?? "Off"}</option>
<option value={1}>{translations.conf?.connection?.ps?.min ?? "Min"}</option>
<option value={2}>{translations.conf?.connection?.ps?.max ?? "Max"}</option>
</select>
</div>
<div class="ml-2 w-1/2">
{translations.conf?.connection?.pwr ?? "Power"}<br/>
<div class="flex">
<input name="ww" bind:value={configuration.w.w} type="number" min="0" max="20.5" step="0.5" class="in-f tr w-full"/>
<span class="in-post">dBm</span>
</div>
</div>
</div>
<div class="my-3">
<label><input type="checkbox" name="wb" value="true" bind:checked={configuration.w.b} class="rounded mb-1"/> {translations.conf?.connection?.tick_11b ?? "802.11b"}</label>
</div>
{/if}
</div>
{/if}
{#if configuration?.n}
<div class="cnt">
<strong class="text-sm">{translations.conf?.network?.title ?? "Network"}</strong>
<a href="{wiki('Network-configuration')}" target="_blank" class="float-right">&#9432;</a>
<div class="my-1">
{translations.conf?.network?.ip ?? "IP"}<br/>
<div class="flex">
<select name="nm" bind:value={configuration.n.m} class="in-f">
<option value="dhcp">{translations.conf?.network?.dhcp ?? "DHCP"}</option>
<option value="static">{translations.conf?.network?.static ?? "Static"}</option>
</select>
<input name="ni" bind:value={configuration.n.i} type="text" class="in-m w-full" disabled={configuration.n.m == 'dhcp'} required={configuration.n.m == 'static'}/>
<select name="ns" bind:value={configuration.n.s} class="in-l" disabled={configuration.n.m == 'dhcp'} required={configuration.n.m == 'static'}>
<SubnetOptions/>
</select>
</div>
</div>
{#if configuration.n.m == 'static'}
<div class="my-1">
{translations.conf?.network?.gw ?? "Gateway"}<br/>
<input name="ng" bind:value={configuration.n.g} type="text" class="in-s"/>
</div>
<div class="my-1">
{translations.conf?.network?.dns ?? "DNS"}<br/>
<div class="flex">
<input name="nd1" bind:value={configuration.n.d1} type="text" class="in-f w-full"/>
<input name="nd2" bind:value={configuration.n.d2} type="text" class="in-l w-full"/>
</div>
</div>
{/if}
<div class="my-1">
<label><input name="nx" value="true" bind:checked={configuration.n.x} type="checkbox" class="rounded mb-1"/> IPv6</label>
</div>
<div class="my-1">
<label><input name="nd" value="true" bind:checked={configuration.n.d} type="checkbox" class="rounded mb-1"/> {translations.conf?.network?.tick_mdns ?? "mDNS"}</label>
</div>
<input type="hidden" name="ntp" value="true"/>
<div class="my-1">
{translations.conf?.network?.ntp ?? "NTP"} <label class="ml-4"><input name="ntpd" value="true" bind:checked={configuration.n.h} type="checkbox" class="rounded mb-1"/> {translations.conf?.network?.tick_ntp_dhcp ?? "from DHCP"}</label><br/>
<div class="flex">
<input name="ntph" bind:value={configuration.n.n1} type="text" class="in-s"/>
</div>
</div>
</div>
{/if}
{#if configuration?.q}
<div class="cnt">
<strong class="text-sm">{translations.conf?.mqtt?.title ?? "MQTT"}</strong>
<a href="{wiki('MQTT-configuration')}" target="_blank" class="float-right">&#9432;</a>
<input type="hidden" name="q" value="true"/>
<div class="my-1">
{translations.conf?.mqtt?.server ?? "Server"}
{#if sysinfo.chip != 'esp8266'}
<label class="float-right mr-3"><input type="checkbox" name="qs" value="true" bind:checked={configuration.q.s.e} class="rounded mb-1" on:change={updateMqttPort}/> SSL</label>
{/if}
<br/>
<div class="flex">
<input name="qh" bind:value={configuration.q.h} type="text" class="in-f w-2/3"/>
<input name="qp" bind:value={configuration.q.p} type="number" min="1024" max="65535" class="in-l tr w-1/3"/>
</div>
</div>
{#if configuration.q.s.e}
<div class="my-1 flex">
<span class="flex pr-2">
{#if configuration.q.s.c}
<span class="bd-on"><Link to="/mqtt-ca">{translations.conf?.mqtt?.ca_ok ?? "CA OK"}</Link></span>
<span class="bd-off" on:click={askDeleteCa} on:keypress={askDeleteCa}>&#128465;</span>
{:else}
<Link to="/mqtt-ca"><Badge color="blue" text={translations.conf?.mqtt?.btn_ca_upload ?? "Upload CA"} title={translations.conf?.mqtt?.title_ca ?? ""}/></Link>
{/if}
</span>
<span class="flex pr-2">
{#if configuration.q.s.r}
<span class="bd-on"><Link to="/mqtt-cert">{translations.conf?.mqtt?.crt_ok ?? "Cert OK"}</Link></span>
<span class="bd-off" on:click={askDeleteCert} on:keypress={askDeleteCert}>&#128465;</span>
{:else}
<Link to="/mqtt-cert"><Badge color="blue" text={translations.conf?.mqtt?.btn_crt_upload ?? "Upload cert"} title={translations.conf?.mqtt?.title_crt ?? ""}/></Link>
{/if}
</span>
<span class="flex pr-2">
{#if configuration.q.s.k}
<span class="bd-on"><Link to="/mqtt-key">{translations.conf?.mqtt?.key_ok ?? "Key OK"}</Link></span>
<span class="bd-off" on:click={askDeleteKey} on:keypress={askDeleteKey}>&#128465;</span>
{:else}
<Link to="/mqtt-key"><Badge color="blue" text={translations.conf?.mqtt?.btn_key_upload ?? "Upload key"} title={translations.conf?.mqtt?.title_key ?? ""}/></Link>
{/if}
</span>
</div>
{/if}
<div class="my-1">
{translations.conf?.mqtt?.user ?? "Username"}<br/>
<input name="qu" bind:value={configuration.q.u} type="text" class="in-s"/>
</div>
<div class="my-1">
{translations.conf?.mqtt?.pass ?? "Password"}<br/>
<input name="qa" bind:value={configuration.q.a} type="password" class="in-s"/>
</div>
<div class="my-1 flex">
<div>
{translations.conf?.mqtt?.id ?? "Client ID"}<br/>
<input name="qc" bind:value={configuration.q.c} type="text" class="in-f w-full"/>
</div>
<div>
{translations.conf?.mqtt?.payload ?? "Payload"}<br/>
<select name="qm" bind:value={configuration.q.m} class="in-l">
<option value={1}>Raw (minimal)</option>
<option value={2}>Raw (full)</option>
<option value={3}>{translations.conf?.mqtt?.domoticz?.title ?? "Domoticz"}</option>
<option value={4}>{translations.conf?.mqtt?.ha?.title ?? "Home-Assistant"}</option>
<option value={0}>JSON (classic)</option>
<option value={5}>JSON (multi topic)</option>
<option value={6}>JSON (flat)</option>
<option value={255}>HEX dump</option>
</select>
</div>
</div>
<div class="my-1">
{translations.conf?.mqtt?.publish ?? "Publish topic"}<br/>
<input name="qb" bind:value={configuration.q.b} type="text" class="in-s"/>
</div>
</div>
{/if}
{#if configuration?.q?.m == 3}
<div class="cnt">
<strong class="text-sm">{translations.conf?.mqtt?.domoticz?.title ?? "Domoticz"}</strong>
<a href="{wiki('MQTT-configuration#domoticz')}" target="_blank" class="float-right">&#9432;</a>
<input type="hidden" name="o" value="true"/>
<div class="my-1 flex">
<div class="w-1/2">
{translations.conf?.mqtt?.domoticz?.eidx ?? "Electricity IDX"}<br/>
<input name="oe" bind:value={configuration.o.e} type="text" class="in-f tr w-full"/>
</div>
<div class="w-1/2">
{translations.conf?.mqtt?.domoticz?.cidx ?? "Current IDX"}<br/>
<input name="oc" bind:value={configuration.o.c} type="text" class="in-l tr w-full"/>
</div>
</div>
<div class="my-1">
{translations.conf?.mqtt?.domoticz?.vidx ?? "Voltage IDX"}: L1, L2 & L3
<div class="flex">
<input name="ou1" bind:value={configuration.o.u1} type="text" class="in-f tr w-1/3"/>
<input name="ou2" bind:value={configuration.o.u2} type="text" class="in-m tr w-1/3"/>
<input name="ou3" bind:value={configuration.o.u3} type="text" class="in-l tr w-1/3"/>
</div>
</div>
</div>
{/if}
{#if configuration?.q?.m == 4}
<div class="cnt">
<strong class="text-sm">{translations.conf?.mqtt?.ha?.title ?? "Home-Assistant"}</strong>
<a href="{wiki('MQTT-configuration#home-assistant')}" target="_blank" class="float-right">&#9432;</a>
<input type="hidden" name="h" value="true"/>
<div class="my-1">
{translations.conf?.mqtt?.ha?.discovery ?? "Discovery topic prefix"}<br/>
<input name="ht" bind:value={configuration.h.t} type="text" class="in-s" placeholder="homeassistant"/>
</div>
<div class="my-1">
{translations.conf?.mqtt?.ha?.hostname ?? "Hostname for URL"}<br/>
<input name="hh" bind:value={configuration.h.h} type="text" class="in-s" placeholder="{configuration.g.h}.local"/>
</div>
<div class="my-1">
{translations.conf?.mqtt?.ha?.tag ?? "Name tag"}<br/>
<input name="hn" bind:value={configuration.h.n} type="text" class="in-s"/>
</div>
</div>
{/if}
{#if configuration?.c?.es != null}
<div class="cnt">
<strong class="text-sm">{translations.conf?.cloud?.title ?? "Cloud connections"}</strong>
<a href="{wiki('Cloud')}" target="_blank" class="float-right">&#9432;</a>
<input type="hidden" name="c" value="true"/>
<div class="my-1">
<label><input type="checkbox" name="ce" value="true" bind:checked={configuration.c.e} class="rounded mb-1"/> {translations.conf?.cloud?.ams ?? "AMS reader cloud"}</label>
</div>
<div class="my-1">
<label><input type="checkbox" class="rounded mb-1" name="ces" value="true" bind:checked={configuration.c.es}/> {translations.conf?.cloud?.es ?? "Energy Speedometer"}</label>
{#if configuration.c.es}
<div class="pl-5">MAC: {sysinfo.mac}</div>
<div class="pl-5">Meter ID: {sysinfo.meter.id ? sysinfo.meter.id : "missing, required"}</div>
{#if sysinfo.mac && sysinfo.meter.id}
<div class="pl-2">
<QrCode value='{'{'}"mac":"{sysinfo.mac}","meter":"{sysinfo.meter.id}"{'}'}'/>
</div>
{/if}
{/if}
</div>
</div>
{/if}
{#if configuration?.p?.r?.startsWith("NO") || configuration?.p?.r?.startsWith("10YNO") || configuration?.p?.r?.startsWith('10Y1001A1001A4')}
<div class="cnt">
<strong class="text-sm">{translations.conf?.thresholds?.title ?? "Thresholds"}</strong>
<a href="{wiki('Threshold-configuration')}" target="_blank" class="float-right">&#9432;</a>
<input type="hidden" name="t" value="true"/>
<div class="flex flex-wrap my-1">
{#each {length: 9} as _, i}
<label class="flex w-40 m-1">
<span class="in-pre">{i+1}</span>
<input name="t{i}" bind:value={configuration.t.t[i]} type="number" min="0" max="65535" class="in-txt w-full"/>
<span class="in-post">kWh</span>
</label>
{/each}
</div>
<label class="flex m-1">
<span class="in-pre">{translations.conf?.thresholds?.avg ?? "Average of"}</span>
<input name="th" bind:value={configuration.t.h} type="number" min="0" max="255" class="in-txt tr w-full"/>
<span class="in-post">{translations.common?.hours ?? "hours"}</span>
</label>
</div>
{/if}
{#if configuration?.u}
<div class="cnt">
<strong class="text-sm">{translations.conf?.ui?.title ?? "User interface"}</strong>
<a href="{wiki('User-interface')}" target="_blank" class="float-right">&#9432;</a>
<input type="hidden" name="u" value="true"/>
<div class="flex flex-wrap">
{#each uiElements as el}
<div class="w-1/2">
{translations.conf?.ui?.[el.key] ?? el.name}<br/>
<select name="u{el.key}" bind:value={configuration.u[el.key]} class="in-s">
<option value={0}>{translations.conf?.ui?.disabled ?? "Disabled"}</option>
<option value={1}>{translations.conf?.ui?.enabled ?? "Enabled"}</option>
<option value={2}>{translations.conf?.ui?.auto ?? "Auto"}</option>
</select>
</div>
{/each}
<div class="w-1/2">
{translations.conf?.ui?.lang ?? "Language"}
<select name="ulang" class="in-s" bind:value={configuration.u.lang} on:change={languageChanged}>
{#each languages as lang}
<option value={lang.code}>{lang.name}</option>
{/each}
</select>
</div>
</div>
</div>
{/if}
{#if configuration?.i?.h && (sysinfo?.board > 20 || sysinfo?.chip == 'esp8266' || configuration?.i?.d?.d > 0)}
<div class="cnt">
<strong class="text-sm">{translations.conf?.hw?.title ?? "Hardware"}</strong>
<a href="{wiki('GPIO-configuration')}" target="_blank" class="float-right">&#9432;</a>
{#if sysinfo.board > 20}
<input type="hidden" name="i" value="true"/>
<div class="flex flex-wrap">
<div class="w-1/3">
{translations.conf?.hw?.han?.rx ?? "HAN RX"}<br/>
<select name="ihp" bind:value={configuration.i.h.p} class="in-f w-full">
<UartSelectOptions chip={sysinfo.chip}/>
</select>
</div>
<div class="w-1/3">
{translations.conf?.hw?.han?.tx ?? "HAN TX"}<br/>
<select name="iht" bind:value={configuration.i.h.t} class="in-l w-full">
<UartSelectOptions chip={sysinfo.chip}/>
</select>
</div>
<div class="w-1/3">
<label class="ml-2"><input name="ihu" value="true" bind:checked={configuration.i.h.u} type="checkbox" class="rounded mb-1"/> {translations.conf?.hw?.han?.pullup ?? "pullup"}</label>
</div>
</div>
<div class="flex flex-wrap">
<div class="w-1/3">
{translations.conf?.hw?.ap_btn ?? "AP button"}<br/>
<input name="ia" bind:value={configuration.i.a} type="number" min="0" max={gpioMax} class="in-f tr w-full"/>
</div>
<div class="w-1/3">
{translations.conf?.hw?.led?.title ?? "LED"}<br/>
<div class="flex">
<input name="ilp" bind:value={configuration.i.l.p} type="number" min="0" max={gpioMax} class="in-l tr w-full"/>
</div>
</div>
<div class="w-1/3">
<label class="ml-4"><input name="ili" value="true" bind:checked={configuration.i.l.i} type="checkbox" class="rounded mb-1"/> {translations.conf?.hw?.led?.inverted ?? "inverted"}</label>
</div>
<div class="w-full">
{translations.conf?.hw?.led?.rgb ?? "RGB"}<label class="ml-4"><input name="iri" value="true" bind:checked={configuration.i.r.i} type="checkbox" class="rounded mb-1"/> {translations.conf?.hw?.led?.inverted ?? "inverted"}</label><br/>
<div class="flex">
<input name="irr" bind:value={configuration.i.r.r} type="number" min="0" max={gpioMax} class="in-f tr w-1/3"/>
<input name="irg" bind:value={configuration.i.r.g} type="number" min="0" max={gpioMax} class="in-m tr w-1/3"/>
<input name="irb" bind:value={configuration.i.r.b} type="number" min="0" max={gpioMax} class="in-l tr w-1/3"/>
</div>
</div>
<div class="w-full">
<div class="my-1 pr-1 w-1/3">
{translations.conf?.hw?.led?.disable ?? "LED dis. GPIO"}
<input name="idd" bind:value={configuration.i.d.d} type="number" min="0" max={gpioMax} class="in-s tr"/>
</div>
</div>
<div class="my-1 w-1/3">
{translations.conf?.hw?.temp ?? "Temperature"}<br/>
<input name="itd" bind:value={configuration.i.t.d} type="number" min="0" max={gpioMax} class="in-f tr w-full"/>
</div>
<div class="my-1 pr-1 w-1/3">
{translations.conf?.hw?.temp_analog ?? "Analog temp"}<br/>
<input name="ita" bind:value={configuration.i.t.a} type="number" min="0" max={gpioMax} class="in-l tr w-full"/>
</div>
{#if sysinfo.chip != 'esp8266'}
<div class="my-1 pl-1 w-1/3">
{translations.conf?.hw?.vcc?.title ?? "Vcc"}<br/>
<input name="ivp" bind:value={configuration.i.v.p} type="number" min="0" max={gpioMax} class="in-s tr w-full"/>
</div>
{/if}
{#if configuration?.i?.v?.p > 0}
<div class="my-1">
{translations.conf?.hw?.vcc?.divider ?? "Voltage divider"}<br/>
<div class="flex">
<input name="ivdv" bind:value={configuration.i.v.d.v} type="number" min="0" max="65535" class="in-f tr w-full" placeholder={translations.conf?.hw?.vcc?.div_vcc ?? "VCC"}/>
<input name="ivdg" bind:value={configuration.i.v.d.g} type="number" min="0" max="65535" class="in-l tr w-full" placeholder={translations.conf?.hw?.vcc?.div_gnd ?? "GND"}/>
</div>
</div>
{/if}
</div>
{/if}
{#if configuration?.i?.d?.d > 0}
<div class="my-1 w-full">
{translations.conf?.hw?.led?.behaviour?.title ?? "LED behaviour"}
<select name="idb" bind:value={configuration.i.d.b} class="in-s">
<option value={0}>{translations.conf?.hw?.led?.behaviour?.enabled ?? "Enabled"}</option>
<option value={1}>{translations.conf?.hw?.led?.behaviour?.disabled ?? "Disabled"}</option>
</select>
</div>
{/if}
{#if sysinfo.chip == 'esp8266'}
<input type="hidden" name="iv" value="true"/>
<div class="my-1 flex flex-wrap">
<div class="w-1/3">
{translations.conf?.hw?.vcc?.offset ?? "Vcc offset"}<br/>
<input name="ivo" bind:value={configuration.i.v.o} type="number" min="0.0" max="3.5" step="0.01" class="in-f tr w-full"/>
</div>
<div class="w-1/3 pr-1">
{translations.conf?.hw?.vcc?.multiplier ?? "Multiplier"}<br/>
<input name="ivm" bind:value={configuration.i.v.m} type="number" min="0.1" max="10" step="0.01" class="in-l tr w-full"/>
</div>
{#if sysinfo.board == 2 || sysinfo.board == 100}
<div class="w-1/3 pl-1">
{translations.conf?.hw?.vcc?.boot ?? "Boot limit"}<br/>
<input name="ivb" bind:value={configuration.i.v.b} type="number" min="2.5" max="3.5" step="0.1" class="in-s tr w-full"/>
</div>
{/if}
</div>
{/if}
</div>
{/if}
{#if configuration?.d}
<div class="cnt">
<strong class="text-sm">{translations.conf?.debug?.title ?? "Debugging"}</strong>
<a href="https://amsleser.no/blog/post/24-telnet-debug" target="_blank" class="float-right">&#9432;</a>
<input type="hidden" name="d" value="true"/>
<div class="mt-3">
<label><input type="checkbox" name="ds" value="true" bind:checked={configuration.d.s} class="rounded mb-1"/> {translations.conf?.debug?.enable ?? "Enable debugging"}</label>
</div>
{#if configuration?.d?.s}
<div class="bd-red">{translations.conf?.debug?.danger ?? "Disable when done"}</div>
<div class="my-1">
<label><input type="checkbox" name="dt" value="true" bind:checked={configuration.d.t} class="rounded mb-1"/> {translations.conf?.debug?.telnet ?? "Enable telnet"}</label>
</div>
{#if configuration.d.t}
<div class="bd-red">{translations.conf?.debug?.telnet_danger ?? "Disable when done"}</div>
{/if}
<div class="my-1">
<select name="dl" bind:value={configuration.d.l} class="in-s">
<option value={1}>Verbose</option>
<option value={2}>Debug</option>
<option value={3}>Info</option>
<option value={4}>Warning</option>
</select>
</div>
{/if}
</div>
{/if}
</div>
<div class="grid grid-cols-3 mt-3">
{#if data?.a}
<div>
<button type="button" on:click={factoryReset} class="btn-red">{translations.conf?.btn_reset ?? "Factory reset"}</button>
</div>
<div class="text-center">
<button type="button" on:click={askReboot} class="btn-yellow">{translations.btn?.reboot ?? "Reboot"}</button>
</div>
{/if}
{#if configuration}
<div class="text-right">
<button type="submit" class="btn-pri">{translations.btn?.save ?? "Save"}</button>
</div>
{/if}
</div>
</form>
<Mask active={loading} message={translations.conf?.mask?.loading ?? "Loading"}/>
<Mask active={saving} message={translations.conf?.mask?.saving ?? "Saving"}/>
<Mask active={isFactoryReset} message={translations.conf?.mask?.reset ?? "Factory reset"}/>
<Mask active={isFactoryResetComplete} message={translations.conf?.mask?.reset_done ?? "Done"}/>

View File

@@ -1,19 +0,0 @@
import { writable } from 'svelte/store';
let configuration = {};
export const configurationStore = writable(configuration);
export async function getConfiguration() {
const response = await fetch("configuration.json");
configuration = (await response.json())
configurationStore.set(configuration);
};
let priceConfig = {};
export const priceConfigStore = writable(priceConfig);
export async function getPriceConfig() {
const response = await fetch("priceconfig.json");
priceConfig = (await response.json())
priceConfigStore.set(priceConfig);
}

View File

@@ -1,63 +0,0 @@
<script>
import { sysinfoStore } from './DataStores.js';
import { translationsStore } from './TranslationService.js';
import Mask from './Mask.svelte'
import { navigate } from 'svelte-navigator';
import { wiki } from './Helpers';
export let basepath = "/";
export let sysinfo = {};
let translations = {};
translationsStore.subscribe(update => {
translations = update;
});
let loadingOrSaving = false;
async function handleSubmit(e) {
loadingOrSaving = true;
const formData = new FormData(e.target)
const data = new URLSearchParams()
for (let field of formData) {
const [key, value] = field
data.append(key, value)
}
const response = await fetch('save', {
method: 'POST',
body: data
});
let res = (await response.json())
loadingOrSaving = false;
sysinfoStore.update(s => {
s.fwconsent = formData['sf'] === true ? 1 : formData['sf'] === false ? 2 : 0;
s.booting = res.reboot;
return s;
});
navigate(basepath);
}
</script>
<div class="grid xl:grid-cols-3 lg:grid-cols-2">
<div class="cnt">
<form on:submit|preventDefault={handleSubmit} autocomplete="off">
<div>
{translations.consent?.title ?? "Consents"}
</div>
<hr/>
<div class="my-3">
{translations.consent?.one_click ?? "One-click"}<br/>
<a href="{wiki('Data-collection-on-one-click-firmware-upgrade')}" target="_blank" class="text-blue-600 hover:text-blue-800">{translations.consent?.read_more ?? "Read more"}</a><br/>
<label><input type="radio" name="sf" value={1} checked={sysinfo.fwconsent === 1} class="rounded m-2" required/> {translations.consent?.yes ?? "Yes"}</label>
<label><input type="radio" name="sf" value={2} checked={sysinfo.fwconsent === 2} class="rounded m-2" required/> {translations.consent?.no ?? "No"}</label><br/>
</div>
<div class="my-3">
<button type="submit" class="btn-pri">{translations.btn?.save ?? "Save"}</button>
</div>
</form>
</div>
</div>
<Mask active={loadingOrSaving} message={translations.consent?.mask_saving ?? "Saving"}/>

View File

@@ -1,10 +0,0 @@
<script>
let europe = ["Amsterdam","Athens","Belfast","Berlin","Bratislava","Brussels","Bucharest","Budapest","Copenhagen","Dublin",
"Helsinki","Lisbon","Ljubljana","London","Luxembourg","Madrid","Malta","Nicosia","Oslo","Paris","Prague","Riga","Rome",
"Sofia","Stockholm","Tallinn","Vienna","Vilnius","Warsaw","Zagreb","Zurich"];
</script>
<option>GMT</option>
{#each europe as c}
<option>Europe/{c}</option>
{/each}

View File

@@ -1,173 +0,0 @@
<script>
import { pricesStore, dayPlotStore, monthPlotStore, temperaturesStore } from './DataStores.js';
import { ampcol, exportcol, metertype, uiVisibility, formatUnit } from './Helpers.js';
import { translationsStore } from './TranslationService.js';
import PowerGauge from './PowerGauge.svelte';
import VoltPlot from './VoltPlot.svelte';
import ReactiveData from './ReactiveData.svelte';
import AccountingData from './AccountingData.svelte';
import PricePlot from './PricePlot.svelte';
import DayPlot from './DayPlot.svelte';
import MonthPlot from './MonthPlot.svelte';
import TemperaturePlot from './TemperaturePlot.svelte';
import TariffPeakChart from './TariffPeakChart.svelte';
import RealtimePlot from './RealtimePlot.svelte';
import PerPhasePlot from './PerPhasePlot.svelte';
export let data = {}
export let sysinfo = {}
let prices = {}
let dayPlot = {}
let monthPlot = {}
let temperatures = {};
pricesStore.subscribe(update => {
prices = update;
});
dayPlotStore.subscribe(update => {
dayPlot = update;
});
monthPlotStore.subscribe(update => {
monthPlot = update;
});
temperaturesStore.subscribe(update => {
temperatures = update;
});
let translations = {};
translationsStore.subscribe(update => {
translations = update;
});
let it,et,threePhase;
$: {
it = formatUnit(data?.ic * 1000, "Wh");
et = formatUnit(data?.ec * 1000, "Wh");
threePhase = data?.l1?.u > 100 && data?.l2?.u > 100 && data?.l3?.u > 100;
}
</script>
<div class="grid 2xl:grid-cols-6 xl:grid-cols-5 lg:grid-cols-4 md:grid-cols-3 sm:grid-cols-2">
{#if uiVisibility(sysinfo.ui.i, data.i)}
<div class="cnt">
<div class="grid grid-cols-2">
<div class="col-span-2">
<PowerGauge val={data.i ? data.i : 0} max={data.im ? data.im : 15000} unit="W" label={translations.common?.import ?? "Import"} sub={data.p} subunit={data.pc} colorFn={ampcol}/>
</div>
<div>{data.mt ? metertype(data.mt) : '-'}</div>
<div class="text-right">{it[0]} {it[1]}</div>
</div>
</div>
{/if}
{#if uiVisibility(sysinfo.ui.e, data.om || data.e > 0)}
<div class="cnt">
<div class="grid grid-cols-2">
<div class="col-span-2">
<PowerGauge val={data.e ? data.e : 0} max={data.om ? data.om * 1000 : 10000} unit="W" label={translations.common?.export ?? "Export"} colorFn={exportcol}/>
</div>
<div></div>
<div class="text-right">{et[0]} {et[1]}</div>
</div>
</div>
{/if}
{#if uiVisibility(sysinfo.ui.v, data.l1 && (data.l1.u > 100 || data.l2.u > 100 || data.l3.u > 100))}
<div class="cnt">
{#if data.l1}
<VoltPlot title={translations.common?.voltage ?? "Volt"} u1={data.l1.u} u2={data.l2.u} u3={data.l3.u} ds={data.ds}/>
{/if}
</div>
{/if}
{#if uiVisibility(sysinfo.ui.a, data.l1 && (data.l1.i > 0.01 || data.l2.i > 0.01 || data.l3.i > 0.01))}
<div class="cnt">
{#if data.l1}
<PerPhasePlot title={translations.common?.amperage ?? "Amp"} unit="A" importColorFn={ampcol} exportColorFn={exportcol}
maxImport={data.mf}
maxExport={data.om ? threePhase ? data.om / 0.4 / Math.sqrt(3) : data.om / 0.23 : 0}
l1={data.l1 && data.l1.u > 100}
l2={data.l2 && data.l2.u > 100}
l3={data.l3 && data.l3.u > 100}
l2x={data.l2.e}
l1i={Math.max(data.l1.i,0)}
l2i={Math.max(data.l2.i,0)}
l3i={Math.max(data.l3.i,0)}
l1e={Math.max(data.l1.i*-1,0)}
l2e={Math.max(data.l2.i*-1,0)}
l3e={Math.max(data.l3.i*-1,0)}
/>
{/if}
</div>
{/if}
{#if uiVisibility(sysinfo.ui.h, data.l1 && (data.l1.p > 0.01 || data.l2.p > 0.01 || data.l3.p > 0.01 || data.l1.q > 0.01 || data.l2.q > 0.01 || data.l3.q > 0.01))}
<div class="cnt">
{#if data.l1}
<PerPhasePlot title={translations.dashboard?.phase ?? "Phase"} unit="W" importColorFn={ampcol} exportColorFn={exportcol}
maxImport={(data.mf ? data.mf : 32) * 230}
maxExport={data.om ? threePhase ? (data.om * 1000) / Math.sqrt(3) : data.om * 1000 : 0}
l1={data.l1 && data.l1.u > 100}
l2={data.l2 && data.l2.u > 100}
l3={data.l3 && data.l3.u > 100}
l1i={data.l1.p}
l2i={data.l2.p}
l3i={data.l3.p}
l1e={data.l1.q}
l2e={data.l2.q}
l3e={data.l3.q}
/>
{/if}
</div>
{/if}
{#if uiVisibility(sysinfo.ui.f, data.l1 && (data.l1.f > 0.01 || data.l2.f > 0.01 || data.l3.f > 0.01))}
<div class="cnt">
{#if data.l1}
<PerPhasePlot title={translations.dashboard?.pf ?? "Pf"} importColorFn={exportcol} exportColorFn={exportcol}
maxImport={1.0}
l1={data.l1 && data.l1.u > 100}
l2={data.l2 && data.l2.u > 100}
l3={data.l3 && data.l3.u > 100}
l1i={data.l1.f}
l2i={data.l2.f}
l3i={data.l3.f}
/>
{/if}
</div>
{/if}
{#if uiVisibility(sysinfo.ui.r, data.ri > 0 || data.re > 0 || data.ric > 0 || data.rec > 0)}
<div class="cnt">
<ReactiveData importInstant={data.ri} exportInstant={data.re} importTotal={data.ric} exportTotal={data.rec}/>
</div>
{/if}
{#if uiVisibility(sysinfo.ui.c, data.ea)}
<div class="cnt">
<AccountingData sysinfo={sysinfo} data={data.ea} currency={data.pc} hasExport={data.om > 0 || data.e > 0}/>
</div>
{/if}
{#if uiVisibility(sysinfo.ui.t, data.pr && (data.pr.startsWith("NO") || data.pr.startsWith("10YNO") || data.pr.startsWith('10Y1001A1001A4')))}
<div class="cnt h-64">
<TariffPeakChart title={translations.dashboard?.tariffpeak ?? "Tariff peaks"}/>
</div>
{/if}
{#if uiVisibility(sysinfo.ui.l, data.hm == 1)}
<div class="cnt gwf">
<RealtimePlot title={translations.dashboard?.realtime ?? "Real time"}/>
</div>
{/if}
{#if uiVisibility(sysinfo.ui.p, data.pe && !Number.isNaN(data.p))}
<div class="cnt gwf">
<PricePlot title={translations.dashboard?.price ?? "Price"} json={prices} sysinfo={sysinfo}/>
</div>
{/if}
{#if uiVisibility(sysinfo.ui.d, dayPlot)}
<div class="cnt gwf">
<DayPlot title={translations.dashboard?.day ?? "24 hours"} json={dayPlot} sysinfo={sysinfo}/>
</div>
{/if}
{#if uiVisibility(sysinfo.ui.m, monthPlot)}
<div class="cnt gwf">
<MonthPlot title={translations.dashboard?.month ?? "{0} days"} json={monthPlot} sysinfo={sysinfo}/>
</div>
{/if}
{#if uiVisibility(sysinfo.ui.s, data.t && data.t != -127 && temperatures.c > 1)}
<div class="cnt gwf">
<TemperaturePlot title={translations.dashboard?.temperature ?? "Temperature"} json={temperatures} />
</div>
{/if}
</div>

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