Compare commits

..

97 Commits

Author SHA1 Message Date
Gunnar Skjold
8457db50f6 Merge branch 'master' into dev-v1.2 2020-03-30 20:12:13 +02:00
Gunnar Skjold
279c5f8321 Fixed actions script 2020-03-30 07:28:02 +02:00
Gunnar Skjold
889b9153fa Increased limit for ArduinoJson positive exponentiation 2020-03-30 07:05:34 +02:00
Gunnar Skjold
0de1d0bb6f Changed accumulated values for Kaifa 2020-03-30 07:02:42 +02:00
Gunnar Skjold
bf13965a9e Various changes during testing 2020-03-26 20:55:23 +01:00
Gunnar Skjold
7b52efd332 Fix missing release version on files 2020-03-25 20:37:15 +01:00
Gunnar Skjold
c936f605d6 Fixes #45 2020-03-25 20:21:39 +01:00
Gunnar Skjold
9d0ceb9ca8 Fixes problem with release 2020-03-25 20:07:23 +01:00
Gunnar Skjold
b33273e3cc Fixes #47 2020-03-25 20:06:42 +01:00
Gunnar Skjold
d9b45d037b Some changes during testing 2020-03-24 21:19:09 +01:00
Gunnar Skjold
8c75a9530e Default config for ESP32 2020-03-24 20:26:13 +01:00
Gunnar Skjold
73d00f786a Added remote debugging 2020-03-24 20:17:44 +01:00
Gunnar Skjold
ab016fff93 Merge pull request #54 from Allram/master
Increased MQTT buffer to work with Aidon 6525 meters
2020-03-24 20:11:00 +01:00
Vegard Fladby
a215aa7766 Increased MQTT buffer to work with Aidon 6525 meters 2020-03-24 19:49:40 +01:00
Gunnar Skjold
d747c84a14 Added DNS to static IP config. Added hostname to config. Added mDNS 2020-03-22 15:08:17 +01:00
Gunnar Skjold
26634f96b0 Added firmware upload from UI 2020-03-22 11:54:27 +01:00
Gunnar Skjold
97669cf4ad When using raw payload with MQTT, only update if changed 2020-03-10 18:57:25 +01:00
Gunnar Skjold
e12980db11 Added option to send data as raw values to MQTT 2020-03-10 18:43:18 +01:00
Gunnar Skjold
732639814b Reduce resolution of "up" in JSON from millis to seconds 2020-03-10 17:46:18 +01:00
Gunnar Skjold
c07c2e66d6 Fixed uptime rollover in UI 2020-03-08 19:47:47 +01:00
Gunnar Skjold
9b70802450 Fixed conversion of date and time from meter to account for CET/CEST 2020-03-08 18:37:10 +01:00
Gunnar Skjold
30d73c3a6e Updated documentation 2020-03-01 13:24:06 +01:00
Gunnar Skjold
bd905c3595 Merge pull request #44 from gskjold/dev-v1.1.0
Dev v1.1.0
2020-03-01 12:56:12 +01:00
Gunnar Skjold
1a2e70b1fb Merge pull request #42 from ArnieO/dev-v1.1.0
Dev v1.1.0 Optional ESP8266 Vcc calibration factor in *.ini file
2020-03-01 12:53:56 +01:00
Gunnar Skjold
d6da7b2715 Merge branch 'dev-v1.1.0' of github.com:gskjold/AmsToMqttBridge into dev-v1.1.0 2020-03-01 09:41:18 +01:00
Gunnar Skjold
059a430f9a Fixed problem with AP mode with INVALID_BUTTON_PIN set 2020-03-01 09:39:58 +01:00
Gunnar Skjold
8ade50c2a6 Initialize all meter data to 0. Removed calculations for i2 2020-02-26 09:06:29 +01:00
Gunnar Skjold
5b94d8ff61 Added calculated value for L2 current when missing from Aidon 2020-02-25 14:08:04 +01:00
ArnieO
232b9c279d Optional Vcc calibration factor defined in *.ino 2020-02-24 20:05:34 +01:00
ArnieO
9b6a6af6ec Merge remote-tracking branch 'upstream/dev-v1.1.0' into dev-v1.1.0 2020-02-24 13:32:26 +01:00
Gunnar Skjold
9671e1eba3 Fixed bug where UI showed stalled HAN when exporting power. Also, maybe fixed issue with Vcc precision in UI? 2020-02-24 12:01:51 +01:00
Gunnar Skjold
78e531a7e9 Changed term for production and consumption when local production is defined 2020-02-24 07:47:39 +01:00
Gunnar Skjold
478d63505d Allow compiling when RGB is not defined 2020-02-24 07:47:12 +01:00
Gunnar Skjold
d8dfaaa730 Version hardening 2020-02-24 07:46:48 +01:00
Gunnar Skjold
f311b70b37 Merge branch 'master' into dev-v1.1.0 2020-02-24 07:17:48 +01:00
Gunnar Skjold
52bc2b14c9 Some changes after testing 2020-02-23 20:31:10 +01:00
ArnieO
2ddfc16d6a Updated comment for rgbled() function 2020-02-23 17:12:26 +01:00
Gunnar Skjold
51ab4a7f07 Reducing precision on temperature and vcc in json to reduce length 2020-02-23 11:34:25 +01:00
Gunnar Skjold
e90a30bfde Implemented blinking for red LED on error 2020-02-22 17:23:56 +01:00
Gunnar Skjold
a63e6962d3 Merge pull request #38 from ArnieO/dev-v1.1.0
Added code for optional RGB LED
2020-02-22 16:42:19 +01:00
Gunnar Skjold
951ccf7de5 Merge branch 'dev-v1.1.0' into dev-v1.1.0 2020-02-22 16:42:04 +01:00
Gunnar Skjold
001e3376df Merge pull request #39 from gskjold/dev-v1.1.0-mqttraw
Merged code preparations for other MQTT payload formats
2020-02-22 16:37:29 +01:00
Gunnar Skjold
9e4bf93f0a Some changes to reduce dlms read errors 2020-02-22 12:29:04 +01:00
ArnieO
e5ac823f69 Changed mqtt buffer to 384, JSON buffer to <512> 2020-02-21 23:29:01 +01:00
Gunnar Skjold
73fd228e2f Merge branch 'dev-v1.1.0' into dev-v1.1.0-mqttraw 2020-02-21 20:58:17 +01:00
Gunnar Skjold
fdac8f88af Minor optimization 2020-02-21 20:52:55 +01:00
Gunnar Skjold
9c8552869c Preparations for selectable MQTT payload format 2020-02-21 20:51:55 +01:00
ArnieO
be75b013c0 Added code for RGB LED 2020-02-21 19:13:44 +01:00
ArnieO
79274e490d Added code for RGB LED 2020-02-21 18:53:05 +01:00
ArnieO
47293eebe4 Added code for RGB LED 2020-02-21 18:38:28 +01:00
Gunnar Skjold
90b62638ed Dependency hardening 2020-02-20 20:36:12 +01:00
Gunnar Skjold
78e766156d Minimizing calls to web server 2020-02-18 21:33:41 +01:00
Gunnar Skjold
4b32af69a7 Fixed typo 2020-02-18 07:37:42 +01:00
Gunnar Skjold
916b5550d9 Fixed typo 2020-02-18 07:25:10 +01:00
Gunnar Skjold
48016240f9 Some cleanup after testing with ESP32 2020-02-17 20:06:52 +01:00
Gunnar Skjold
518b408205 Minor changes to fix build 2020-02-17 17:23:18 +01:00
Gunnar Skjold
73a0359597 Minor changes to fix build 2020-02-17 17:21:34 +01:00
Gunnar Skjold
bbe82f9cdc Added a small delay that helped smooth the voltage on a HAN powered device. No more sudden reboots 2020-02-16 21:45:58 +01:00
Gunnar Skjold
4786735d4c Support older config versions. Fixed css for AP mode. Some cleanup and changes to preserve power 2020-02-16 20:09:29 +01:00
Gunnar Skjold
227eb7b6ff Now using external base64 lib. Also updated some previously commited errors 2020-02-16 16:03:01 +01:00
Gunnar Skjold
00edd94033 Fixed some bugs from late night coding 2020-02-16 15:46:01 +01:00
Gunnar Skjold
ccd818e1ab Merge branch 'master' into dev-v1.1.0 2020-02-16 15:28:47 +01:00
Gunnar Skjold
fc42fb22d8 Merge pull request #33 from gskjold/dev-v1.0.1
Dev v1.0.1
2020-02-16 14:49:36 +01:00
Gunnar Skjold
f6066fbbf3 Cleanup and fix bugs found during testing 2020-02-15 22:13:04 +01:00
Gunnar Skjold
9c09740a41 Production graph and fixed vcc value 2020-02-15 21:04:18 +01:00
Gunnar Skjold
4e24e2949a Updated featheresp32 config to use Serial2 for Mbus 2020-02-15 18:01:10 +01:00
Gunnar Skjold
eff00f1fe0 Only show temp if sensor is attached. Added common functions to get temp and vcc 2020-02-14 21:48:03 +01:00
Gunnar Skjold
f484f3eb0e Merge branch 'dev-v1.0.1' into dev-v1.1.0 2020-02-14 20:19:15 +01:00
Gunnar Skjold
b2174dd521 If debug mode and HW_ROARFRED, use software serial to set upp RX for HAN with 2400 and TX for debugging with 115200 2020-02-14 20:14:30 +01:00
Gunnar Skjold
fe79a96827 Added change to allow auto modem sleep 2020-02-14 19:52:15 +01:00
Gunnar Skjold
517a40b0a6 Finalized new configuration menu and moved AP button trigger from setup to loop 2020-02-14 19:49:25 +01:00
Gunnar Skjold
75f3c8c592 Merge branch 'dev-v1.0.1' into dev-v1.1.0 2020-02-14 16:07:54 +01:00
Gunnar Skjold
554cc7c023 Added date and time from meter as rtc in json 2020-02-14 16:03:52 +01:00
Gunnar Skjold
6d0c722c98 Using kwh and kvarh as standard for accumulated numbers from kamstrup 2020-02-14 12:25:40 +01:00
Gunnar Skjold
d2f93c07bd Not sure if this does anything, but increased json and mqtt limits to see if Kamstrup list 3 is received 2020-02-13 20:50:13 +01:00
Gunnar Skjold
d63516fd49 Deleted autosave 2020-02-13 20:41:08 +01:00
Gunnar Skjold
c114b777c7 Minor changes to UI 2020-02-13 20:40:33 +01:00
Gunnar Skjold
a06729b535 Bugfix for previous commit 2020-02-12 20:11:55 +01:00
Gunnar Skjold
0ea21991ea Continued work with v1.1.0
- Merge branch 'low_power' into dev-v1.1.0
- Corrected accumulated import/export from Aidon
- Added VCC and RSSI to MQTT messages

Changes in UI:
- New top navbar
- Show VCC and WiFi information
- Show MQTT error messages
- Show ESP, HAN, WiFi and MQTT status badge
- Show accumulated Import/export
2020-02-12 19:55:06 +01:00
Gunnar Skjold
1994f16b82 Merge branch 'dev-v1.0.1' into dev-v1.1.0 2020-02-12 16:41:04 +01:00
Gunnar Skjold
b6efae656f Expose export power in JSON 2020-02-12 16:40:51 +01:00
Gunnar Skjold
fa0f93cefe Switched to reactive import for Q 2020-02-12 13:25:36 +01:00
Gunnar Skjold
058dc658c1 Switched to reactive import for Q 2020-02-12 13:16:49 +01:00
Gunnar Skjold
f6df84bf9a Auto detect meter type 2020-02-11 18:40:38 +01:00
Gunnar Skjold
4b9cb27e58 Disable web security if AP mode is triggered 2020-02-11 17:32:18 +01:00
Gunnar Skjold
5f14517258 Minor changes after testing MQTT reconnect 2020-02-11 17:25:52 +01:00
Gunnar Skjold
ad820fff01 Allow other services to get resources while trying to connect to mqtt 2020-02-11 11:04:37 +01:00
Gunnar Skjold
6d3d4adc7e Merge branch 'master' into low_power 2020-02-09 13:45:27 +01:00
Gunnar Skjold
27cb5dd833 Trying a large sleep when cap is not charged 2020-02-06 19:15:06 +01:00
Gunnar Skjold
7e6ac860fd Merge branch 'master' into low_power 2020-02-06 19:02:14 +01:00
Gunnar Skjold
70ed0b538a Merge branch 'master' into low_power 2020-01-29 21:00:10 +01:00
Gunnar Skjold
0a317450f6 Merge branch 'master' into low_power 2020-01-29 20:51:28 +01:00
Gunnar Skjold
a6751c787c Merge branch 'issue-9' into low_power 2020-01-29 20:39:07 +01:00
Gunnar Skjold
aed56b0b56 Merge branch 'issue-9' into low_power 2020-01-28 21:19:01 +01:00
Gunnar Skjold
550b216ba6 Merge branch 'issue-9' into low_power 2020-01-28 21:12:00 +01:00
Gunnar Skjold
aef78962fb Some modifications to reduce power consumption i AP mode 2020-01-23 18:47:02 +01:00
Gunnar Skjold
8ee713b616 Included some code from @dakarym to support the self powered board for testing 2020-01-22 15:26:07 +01:00
65 changed files with 6099 additions and 2034 deletions

View File

@@ -14,11 +14,16 @@ jobs:
steps:
- name: Check out code from repo
uses: actions/checkout@v1
- name: Get release version from tag
- name: Get release version for filenames
id: release_tag
env:
GITHUB_REF: ${{ github.ref }}
run: echo ::set-output name=tag::$(echo ${GITHUB_REF:11})
- name: Get release version for code
id: release_tag
env:
GITHUB_REF: ${{ github.ref }}
run: echo ::set-env name=GITHUB_TAG::$(echo ${GITHUB_REF##*/})
- name: Cache Python dependencies
uses: actions/cache@v1
with:
@@ -52,7 +57,7 @@ jobs:
draft: false
prerelease: false
- name: Upload hw1esp12e binary to release
uses: actions/upload-release-asset@v1.0.1
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
@@ -61,7 +66,7 @@ jobs:
asset_name: ams2mqtt-hw1esp12e-${{ steps.release_tag.outputs.tag }}.bin
asset_content_type: application/octet-stream
- name: Upload esp12e binary to release
uses: actions/upload-release-asset@v1.0.1
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
@@ -70,7 +75,7 @@ jobs:
asset_name: ams2mqtt-esp12e-${{ steps.release_tag.outputs.tag }}.bin
asset_content_type: application/octet-stream
- name: Upload d1mini binary to release
uses: actions/upload-release-asset@v1.0.1
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
@@ -79,7 +84,7 @@ jobs:
asset_name: ams2mqtt-d1mini-${{ steps.release_tag.outputs.tag }}.bin
asset_content_type: application/octet-stream
- name: Upload esp32 binary to release
uses: actions/upload-release-asset@v1.0.1
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
@@ -88,7 +93,7 @@ jobs:
asset_name: ams2mqtt-esp32-${{ steps.release_tag.outputs.tag }}.bin
asset_content_type: application/octet-stream
- name: Upload lolind32 binary to release
uses: actions/upload-release-asset@v1.0.1
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
@@ -97,7 +102,7 @@ jobs:
asset_name: ams2mqtt-lolind32-${{ steps.release_tag.outputs.tag }}.bin
asset_content_type: application/octet-stream
- name: Upload featheresp32 binary to release
uses: actions/upload-release-asset@v1.0.1
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:

View File

@@ -7,6 +7,9 @@ There is also a web interface available on runtime, showing meter data in real t
<img src="webui.jpg" width="480">
## Hardware options
Look in [hardware section](/hardware) for more details about supported hardware
## Release binaries
In the [Release section](https://github.com/gskjold/AmsToMqttBridge/releases) of this repository, you will find precompiled binaries for some common boards.

Binary file not shown.

View File

@@ -19,15 +19,17 @@ You can also use a ESP based development board and combine this with a M-Bus mod
[Wemos D1 mini](https://docs.wemos.cc/en/latest/d1/d1_mini.html)
- M-Bus connected to GPIO5 (D1)
- Jump GPIO4 (D2) to GND to force AP mode during boot
- Dallas temp sensor connected to GPIO14 (D5)
### ESP32 based boards
[Wemos D32](https://docs.wemos.cc/en/latest/d32/d32.html)
- M-Bus connected to GPIO21
- M-Bus connected to GPIO16
- Jump GPIO4 to GND to force AP mode during boot
- Dallas temp sensor connected to GPIO14
[Adafruit HUZZAH32](https://www.adafruit.com/product/3405)
- M-Bus connected to RX
- M-Bus connected to GPIO16
Combine one of above board with an M-Bus module. Connect 3.3v and GND together between the boards and connect the TX pin from the M-Bus board to the dedicated M-Bus pin on the ESP board.

View File

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

View File

@@ -0,0 +1,356 @@
EESchema-LIBRARY Version 2.4
#encoding utf-8
#
# BSS84-transistors
#
DEF BSS84-transistors Q 0 0 Y N 1 F N
F0 "Q" 200 75 50 H V L CNN
F1 "BSS84-transistors" 200 0 50 H V L CNN
F2 "TO_SOT_Packages_SMD:SOT-23" 200 -75 50 H I L CIN
F3 "" 0 0 50 H I L CNN
$FPLIST
SOT?23*
$ENDFPLIST
DRAW
C 65 0 111 0 1 10 N
C 100 -70 11 0 1 0 F
C 100 70 11 0 1 0 F
P 2 0 1 0 0 0 10 0 N
P 2 0 1 0 30 -70 100 -70 N
P 2 0 1 10 30 -50 30 -90 N
P 2 0 1 0 30 0 100 0 N
P 2 0 1 10 30 20 30 -20 N
P 2 0 1 0 30 70 100 70 N
P 2 0 1 10 30 90 30 50 N
P 2 0 1 0 100 -70 100 -100 N
P 2 0 1 0 100 -70 100 0 N
P 2 0 1 0 100 100 100 70 N
P 3 0 1 10 10 75 10 -75 10 -75 N
P 4 0 1 0 90 0 50 -15 50 15 90 0 F
P 4 0 1 0 100 -70 130 -70 130 70 100 70 N
P 4 0 1 0 110 -20 115 -15 145 -15 150 -10 N
P 4 0 1 0 130 -15 115 10 145 10 130 -15 N
X G 1 -200 0 200 R 50 50 1 1 I
X S 2 100 -200 100 U 50 50 1 1 P
X D 3 100 200 100 D 50 50 1 1 P
ENDDRAW
ENDDEF
#
# CP-device
#
DEF CP-device C 0 10 N Y 1 F N
F0 "C" 25 100 50 H V L CNN
F1 "CP-device" 25 -100 50 H V L CNN
F2 "" 38 -150 50 H I C CNN
F3 "" 0 0 50 H I C CNN
$FPLIST
CP_*
$ENDFPLIST
DRAW
S -90 20 -90 40 0 1 0 N
S -90 20 90 20 0 1 0 N
S 90 -20 -90 -40 0 1 0 F
S 90 40 -90 40 0 1 0 N
S 90 40 90 20 0 1 0 N
P 2 0 1 0 -70 90 -30 90 N
P 2 0 1 0 -50 110 -50 70 N
X ~ 1 0 150 110 D 50 50 1 1 P
X ~ 2 0 -150 110 U 50 50 1 1 P
ENDDRAW
ENDDEF
#
# CP_Small-device
#
DEF CP_Small-device C 0 10 N N 1 F N
F0 "C" 10 70 50 H V L CNN
F1 "CP_Small-device" 10 -80 50 H V L CNN
F2 "" 0 0 50 H I C CNN
F3 "" 0 0 50 H I C CNN
$FPLIST
CP_*
$ENDFPLIST
DRAW
S -60 -12 60 -27 0 1 0 F
S -60 27 60 12 0 1 0 N
P 2 0 1 0 -50 60 -30 60 N
P 2 0 1 0 -40 50 -40 70 N
X ~ 1 0 100 73 D 50 50 1 1 P
X ~ 2 0 -100 73 U 50 50 1 1 P
ENDDRAW
ENDDEF
#
# C_Small-device
#
DEF C_Small-device C 0 10 N N 1 F N
F0 "C" 10 70 50 H V L CNN
F1 "C_Small-device" 10 -80 50 H V L CNN
F2 "" 0 0 50 H I C CNN
F3 "" 0 0 50 H I C CNN
$FPLIST
C_*
$ENDFPLIST
DRAW
P 2 0 1 13 -60 -20 60 -20 N
P 2 0 1 12 -60 20 60 20 N
X ~ 1 0 100 80 D 50 50 1 1 P
X ~ 2 0 -100 80 U 50 50 1 1 P
ENDDRAW
ENDDEF
#
# DS18B20-maxim
#
DEF DS18B20-maxim U 0 40 Y Y 1 F N
F0 "U" -150 250 50 H V C CNN
F1 "DS18B20-maxim" 0 -250 50 H V C CNN
F2 "" -150 250 50 H I C CNN
F3 "" -150 250 50 H I C CNN
$FPLIST
TO-92_*
$ENDFPLIST
DRAW
S -200 200 200 -200 0 1 0 N
X GND 1 -300 -100 100 R 50 50 1 1 W
X DQ 2 -300 0 100 R 50 50 1 1 B
X VDD 3 -300 100 100 R 50 50 1 1 W
ENDDRAW
ENDDEF
#
# ESP-12E-ESP8266
#
DEF ESP-12E-ESP8266 U 0 40 Y Y 1 F N
F0 "U" 0 -100 50 H V C CNN
F1 "ESP-12E-ESP8266" 0 100 50 H V C CNN
F2 "" 0 0 50 H I C CNN
F3 "" 0 0 50 H I C CNN
$FPLIST
ESP-12E
ESP-12E_SMD
$ENDFPLIST
DRAW
S -600 -600 600 600 1 0 0 N
X REST 1 -900 300 300 R 50 50 1 1 I
X GPIO15 10 900 -300 300 L 50 50 1 1 B
X GPIO2 11 900 -200 300 L 50 50 1 1 B
X GPIO0 12 900 -100 300 L 50 50 1 1 B
X GPIO4 13 900 0 300 L 50 50 1 1 B
X GPIO5 14 900 100 300 L 50 50 1 1 B
X RXD 15 900 200 300 L 50 50 1 1 I
X TXD 16 900 300 300 L 50 50 1 1 O
X CS0 17 -250 -900 300 U 50 50 1 1 B
X MISO 18 -150 -900 300 U 50 50 1 1 B
X GPIO9 19 -50 -900 300 U 50 50 1 1 B
X ADC 2 -900 200 300 R 50 50 1 1 P
X GPIO10 20 50 -900 300 U 50 50 1 1 B
X MOSI 21 150 -900 300 U 50 50 1 1 B
X SCLK 22 250 -900 300 U 50 50 1 1 B
X CH_PD 3 -900 100 300 R 50 50 1 1 I
X GPIO16 4 -900 0 300 R 50 50 1 1 B
X GPIO14 5 -900 -100 300 R 50 50 1 1 B
X GPIO12 6 -900 -200 300 R 50 50 1 1 B
X GPIO13 7 -900 -300 300 R 50 50 1 1 B
X VCC 8 -900 -400 300 R 50 50 1 1 W
X GND 9 900 -400 300 L 50 50 1 1 W
ENDDRAW
ENDDEF
#
# FTDI_PROG_HDR-ESPProgHeader
#
DEF FTDI_PROG_HDR-ESPProgHeader J 0 40 Y N 1 F N
F0 "J" 0 300 50 H V C CNN
F1 "FTDI_PROG_HDR-ESPProgHeader" 0 -400 50 H V C CNN
F2 "" 0 0 50 H I C CNN
F3 "" 0 0 50 H I C CNN
$FPLIST
Connector*:*_??x*mm*
Connector*:*1x??x*mm*
Pin?Header?Straight?1X*
Pin?Header?Angled?1X*
Socket?Strip?Straight?1X*
Socket?Strip?Angled?1X*
$ENDFPLIST
DRAW
S -50 -295 0 -305 1 1 6 N
S -50 -195 0 -205 1 1 6 N
S -50 -95 0 -105 1 1 6 N
S -50 5 0 -5 1 1 6 N
S -50 105 0 95 1 1 6 N
S -50 205 0 195 1 1 6 N
S -50 250 50 -350 1 1 10 f
X Pin_1 1 -200 200 150 R 50 50 1 1 N
X Pin_2 2 -200 100 150 R 50 50 1 1 P
X Pin_3 3 -200 0 150 R 50 50 1 1 P
X Pin_4 4 -200 -100 150 R 50 50 1 1 N
X Pin_5 5 -200 -200 150 R 50 50 1 1 N
X Pin_6 6 -200 -300 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
DRAW
A 0 -26 125 1426 373 0 1 0 N -98 50 99 50
C -100 0 35 0 1 0 N
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
#
# LM1117-3.3-regul
#
DEF LM1117-3.3-regul U 0 10 Y Y 1 F N
F0 "U" -150 125 50 H V C CNN
F1 "LM1117-3.3-regul" 0 125 50 H V L CNN
F2 "" 0 0 50 H I C CNN
F3 "" 0 0 50 H I C CNN
$FPLIST
SOT?223*
TO?263*
TO?252*
TO?220*
$ENDFPLIST
DRAW
S -200 -200 200 75 0 1 10 f
X GND 1 0 -300 100 U 50 50 1 1 W
X VO 2 300 0 100 L 50 50 1 1 w
X VI 3 -300 0 100 R 50 50 1 1 W
ENDDRAW
ENDDEF
#
# RJ45-conn
#
DEF RJ45-conn J 0 40 Y Y 1 F N
F0 "J" 200 500 50 H V C CNN
F1 "RJ45-conn" -150 500 50 H V C CNN
F2 "" 0 0 50 H I C CNN
F3 "" 0 0 50 H I C CNN
DRAW
S -400 -300 400 450 0 1 10 f
P 3 0 1 0 -175 200 -175 250 -175 250 N
P 3 0 1 0 -125 250 -125 200 -125 200 N
P 3 0 1 0 -75 250 -75 200 -75 200 N
P 3 0 1 0 -25 250 -25 200 -25 200 N
P 3 0 1 0 25 250 25 200 25 200 N
P 3 0 1 0 75 250 75 200 75 200 N
P 3 0 1 0 125 200 125 250 125 250 N
P 3 0 1 0 175 200 175 250 175 250 N
P 14 0 1 0 -225 250 225 250 225 -150 125 -150 125 -200 75 -200 75 -250 -75 -250 -75 -200 -125 -200 -125 -150 -225 -150 -225 250 -225 250 N
X ~ 1 -350 -450 150 U 50 50 1 1 P
X ~ 2 -250 -450 150 U 50 50 1 1 P
X ~ 3 -150 -450 150 U 50 50 1 1 P
X ~ 4 -50 -450 150 U 50 50 1 1 P
X ~ 5 50 -450 150 U 50 50 1 1 P
X ~ 6 150 -450 150 U 50 50 1 1 P
X ~ 7 250 -450 150 U 50 50 1 1 P
X ~ 8 350 -450 150 U 50 50 1 1 P
X SHIELD 9 550 350 150 L 50 50 1 1 P
ENDDRAW
ENDDEF
#
# R_Small-device
#
DEF R_Small-device R 0 10 N N 1 F N
F0 "R" 30 20 50 H V L CNN
F1 "R_Small-device" 30 -40 50 H V L CNN
F2 "" 0 0 50 H I C CNN
F3 "" 0 0 50 H I C CNN
$FPLIST
R_*
$ENDFPLIST
DRAW
S -30 70 30 -70 0 1 8 N
X ~ 1 0 100 30 D 50 50 1 1 P
X ~ 2 0 -100 30 U 50 50 1 1 P
ENDDRAW
ENDDEF
#
# SW_Push-switches
#
DEF SW_Push-switches SW 0 40 N N 1 F N
F0 "SW" 50 100 50 H V L CNN
F1 "SW_Push-switches" 0 -60 50 H V C CNN
F2 "" 0 200 50 H I C CNN
F3 "" 0 200 50 H I C CNN
DRAW
C -80 0 20 0 1 0 N
C 80 0 20 0 1 0 N
P 2 0 1 0 0 50 0 120 N
P 2 0 1 0 100 50 -100 50 N
X 1 1 -200 0 100 R 50 50 0 1 P
X 2 2 200 0 100 L 50 50 0 1 P
ENDDRAW
ENDDEF
#
# TSS721-tss721
#
DEF TSS721-tss721 U 0 40 Y Y 1 F N
F0 "U" 200 850 50 H V L CNN
F1 "TSS721-tss721" 200 750 50 H V L CNN
F2 "" 0 -850 50 H V C CIN
F3 "" -200 -800 50 H V C CNN
$FPLIST
SOIC*3.9x9.9mm*Pitch1.27mm*
TSSOP*4.4x5mm*Pitch0.65mm*
$ENDFPLIST
DRAW
S -500 -700 500 700 0 1 10 f
X BUSL2 1 -600 400 100 R 50 50 1 1 I
X VS 10 -600 0 100 R 50 50 1 1 P
X VDD 11 0 800 100 D 50 50 1 1 W
X RX 12 600 500 100 L 50 50 1 1 I
X RXI 13 600 400 100 L 50 50 1 1 I I
X RIS 14 300 -800 100 U 50 50 1 1 I
X GND 15 0 -800 100 U 50 50 1 1 W
X BUSL1 16 -600 500 100 R 50 50 1 1 I
X VB 2 -600 -150 100 R 50 50 1 1 P
X STC 3 -600 -500 100 R 50 50 1 1 P
X RIDD 4 200 -800 100 U 50 50 1 1 O
X PF 5 -600 100 100 R 50 50 1 1 I
X SC 6 400 -800 100 U 50 50 1 1 P
X TXI 7 600 100 100 L 50 50 1 1 O I
X TX 8 600 200 100 L 50 50 1 1 O
X BAT 9 -100 800 100 D 50 50 1 1 I
ENDDRAW
ENDDEF
#
# USB_OTG-conn
#
DEF USB_OTG-conn J 0 40 Y Y 1 F N
F0 "J" -200 450 50 H V L CNN
F1 "USB_OTG-conn" -200 350 50 H V L CNN
F2 "" 150 -50 50 H I C CNN
F3 "" 150 -50 50 H I C CNN
$FPLIST
USB*
$ENDFPLIST
DRAW
C -150 85 25 0 1 10 F
C -25 135 15 0 1 10 F
S -200 -300 200 300 0 1 10 f
S -5 -300 5 -270 0 1 0 N
S 10 50 -20 20 0 1 10 F
S 200 -205 170 -195 0 1 0 N
S 200 -105 170 -95 0 1 0 N
S 200 -5 170 5 0 1 0 N
S 200 195 170 205 0 1 0 N
P 2 0 1 10 -75 85 25 85 N
P 4 0 1 10 -125 85 -100 85 -50 135 -25 135 N
P 4 0 1 10 -100 85 -75 85 -50 35 0 35 N
P 4 0 1 10 25 110 25 60 75 85 25 110 F
P 5 0 1 0 -170 220 -70 220 -80 190 -160 190 -170 220 F
P 9 0 1 0 -185 230 -185 220 -175 190 -175 180 -65 180 -65 190 -55 220 -55 230 -185 230 N
X VBUS 1 300 200 100 L 50 50 1 1 W
X D- 2 300 -100 100 L 50 50 1 1 P
X D+ 3 300 0 100 L 50 50 1 1 P
X ID 4 300 -200 100 L 50 50 1 1 P
X GND 5 0 -400 100 U 50 50 1 1 W
X Shield 6 -100 -400 100 U 50 50 1 1 P
ENDDRAW
ENDDEF
#
#End Library

View File

@@ -1,2 +1,3 @@
(sym_lib_table
(lib (name HAN_ESP_TSS721-rescue)(type Legacy)(uri ${KIPRJMOD}/HAN_ESP_TSS721-rescue.lib)(options "")(descr ""))
)

View File

@@ -1,9 +0,0 @@
name=HanConfigAp
version=1.0.0
author=roarfred
maintainer=roarfred <not@important.com>
sentence=HAN Configuraiton accesspoint
paragraph=HAN Configuraiton accesspoint
category=Sensors
url=https://github.com/roarfred/AmsToMqttBridge
architectures=*

View File

@@ -1,142 +0,0 @@
/*
Copyright (C) 2016 Arturo Guadalupi. All right reserved.
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*/
#include "Base64.h"
#include <Arduino.h>
#if (defined(__AVR__))
#include <avr\pgmspace.h>
#else
#include <pgmspace.h>
#endif
const char PROGMEM _Base64AlphabetTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
int Base64Class::encode(char *output, char *input, int inputLength) {
int i = 0, j = 0;
int encodedLength = 0;
unsigned char A3[3];
unsigned char A4[4];
while(inputLength--) {
A3[i++] = *(input++);
if(i == 3) {
fromA3ToA4(A4, A3);
for(i = 0; i < 4; i++) {
output[encodedLength++] = pgm_read_byte(&_Base64AlphabetTable[A4[i]]);
}
i = 0;
}
}
if(i) {
for(j = i; j < 3; j++) {
A3[j] = '\0';
}
fromA3ToA4(A4, A3);
for(j = 0; j < i + 1; j++) {
output[encodedLength++] = pgm_read_byte(&_Base64AlphabetTable[A4[j]]);
}
while((i++ < 3)) {
output[encodedLength++] = '=';
}
}
output[encodedLength] = '\0';
return encodedLength;
}
int Base64Class::decode(char * output, char * input, int inputLength) {
int i = 0, j = 0;
int decodedLength = 0;
unsigned char A3[3];
unsigned char A4[4];
while (inputLength--) {
if(*input == '=') {
break;
}
A4[i++] = *(input++);
if (i == 4) {
for (i = 0; i <4; i++) {
A4[i] = lookupTable(A4[i]);
}
fromA4ToA3(A3,A4);
for (i = 0; i < 3; i++) {
output[decodedLength++] = A3[i];
}
i = 0;
}
}
if (i) {
for (j = i; j < 4; j++) {
A4[j] = '\0';
}
for (j = 0; j <4; j++) {
A4[j] = lookupTable(A4[j]);
}
fromA4ToA3(A3,A4);
for (j = 0; j < i - 1; j++) {
output[decodedLength++] = A3[j];
}
}
output[decodedLength] = '\0';
return decodedLength;
}
int Base64Class::encodedLength(int plainLength) {
int n = plainLength;
return (n + 2 - ((n + 2) % 3)) / 3 * 4;
}
int Base64Class::decodedLength(char * input, int inputLength) {
int i = 0;
int numEq = 0;
for(i = inputLength - 1; input[i] == '='; i--) {
numEq++;
}
return ((6 * inputLength) / 8) - numEq;
}
//Private utility functions
inline void Base64Class::fromA3ToA4(unsigned char * A4, unsigned char * A3) {
A4[0] = (A3[0] & 0xfc) >> 2;
A4[1] = ((A3[0] & 0x03) << 4) + ((A3[1] & 0xf0) >> 4);
A4[2] = ((A3[1] & 0x0f) << 2) + ((A3[2] & 0xc0) >> 6);
A4[3] = (A3[2] & 0x3f);
}
inline void Base64Class::fromA4ToA3(unsigned char * A3, unsigned char * A4) {
A3[0] = (A4[0] << 2) + ((A4[1] & 0x30) >> 4);
A3[1] = ((A4[1] & 0xf) << 4) + ((A4[2] & 0x3c) >> 2);
A3[2] = ((A4[2] & 0x3) << 6) + A4[3];
}
inline unsigned char Base64Class::lookupTable(char c) {
if(c >='A' && c <='Z') return c - 'A';
if(c >='a' && c <='z') return c - 71;
if(c >='0' && c <='9') return c + 4;
if(c == '+') return 62;
if(c == '/') return 63;
return -1;
}
Base64Class Base64;

View File

@@ -1,26 +0,0 @@
/*
Copyright (C) 2016 Arturo Guadalupi. All right reserved.
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*/
#ifndef _BASE64_H
#define _BASE64_H
class Base64Class{
public:
int encode(char *output, char *input, int inputLength);
int decode(char * output, char * input, int inputLength);
int encodedLength(int plainLength);
int decodedLength(char * input, int inputLength);
private:
inline void fromA3ToA4(unsigned char * A4, unsigned char * A3);
inline void fromA4ToA3(unsigned char * A3, unsigned char * A4);
inline unsigned char lookupTable(char c);
};
extern Base64Class Base64;
#endif // _BASE64_H

View File

@@ -1,91 +0,0 @@
#include "HanConfigAp.h"
Stream* HanConfigAp::debugger;
bool HanConfigAp::hasConfig() {
return config->hasConfig();
}
void HanConfigAp::setup(int accessPointButtonPin, configuration* config, Stream* debugger)
{
this->debugger = debugger;
this->config = config;
// Test if we're missing configuration
if (!config->hasConfig())
{
print("No config. We're booting as AP. Look for SSID ");
println(this->AP_SSID);
isActivated = true;
}
else
{
// Load the configuration
if (this->debugger) config->print(this->debugger);
if (accessPointButtonPin != INVALID_BUTTON_PIN)
{
// Assign pin for boot as AP
pinMode(accessPointButtonPin, INPUT_PULLUP);
// Test if we're holding down the AP pin, over 5 seconds
int time = millis() + 5000;
print("Press the AP button now to boot as access point");
while (millis() < time)
{
print(".");
if (digitalRead(accessPointButtonPin) == LOW)
{
print("AP button was pressed. Booting as access point now. Look for SSID ");
println(this->AP_SSID);
isActivated = true;
break;
}
delay(100);
}
println("");
}
}
if (isActivated)
{
// Setup AP
WiFi.disconnect(true);
WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_OFF);
delay(2000);
WiFi.softAP(AP_SSID);
WiFi.mode(WIFI_AP);
/* Setup the DNS server redirecting all the domains to this IP */
dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
dnsServer.start(DNS_PORT, "*", WiFi.softAPIP());
}
}
bool HanConfigAp::loop() {
if(isActivated) {
//DNS
dnsServer.processNextRequest();
}
return isActivated;
}
size_t HanConfigAp::print(const char* text)
{
if (debugger) debugger->print(text);
}
size_t HanConfigAp::println(const char* text)
{
if (debugger) debugger->println(text);
}
size_t HanConfigAp::print(const Printable& data)
{
if (debugger) debugger->print(data);
}
size_t HanConfigAp::println(const Printable& data)
{
if (debugger) debugger->println(data);
}

View File

@@ -1,50 +0,0 @@
// ap.h
#ifndef _ACCESSPOINT_h
#define _ACCESSPOINT_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32) // ARDUINO_ARCH_ESP32
#include <WiFi.h>
#else
#warning "Unsupported board type"
#endif
#include <DNSServer.h>
#include "configuration.h"
#define INVALID_BUTTON_PIN 0xFFFFFFFF
class HanConfigAp {
public:
void setup(int accessPointButtonPin, configuration* config, Stream* debugger);
bool loop();
bool hasConfig();
bool isActivated = false;
private:
const char* AP_SSID = "AMS2MQTT";
configuration* config;
// DNS server
const byte DNS_PORT = 53;
DNSServer dnsServer;
static size_t print(const char* text);
static size_t println(const char* text);
static size_t print(const Printable& data);
static size_t println(const Printable& data);
static Stream* debugger;
};
#endif

View File

@@ -1,265 +0,0 @@
//
//
//
#include "configuration.h"
bool configuration::hasConfig()
{
bool hasConfig = false;
EEPROM.begin(EEPROM_SIZE);
hasConfig = EEPROM.read(EEPROM_CONFIG_ADDRESS) == EEPROM_CHECK_SUM;
EEPROM.end();
return hasConfig;
}
bool configuration::save()
{
int address = EEPROM_CONFIG_ADDRESS;
EEPROM.begin(EEPROM_SIZE);
EEPROM.put(address, EEPROM_CHECK_SUM);
address++;
address += saveString(address, ssid);
address += saveString(address, ssidPassword);
address += saveByte(address, meterType);
if(mqttHost) {
address += saveBool(address, true);
address += saveString(address, mqttHost);
address += saveInt(address, mqttPort);
address += saveString(address, mqttClientID);
address += saveString(address, mqttPublishTopic);
address += saveString(address, mqttSubscribeTopic);
} else {
address += saveBool(address, false);
}
if (isSecure()) {
address += saveBool(address, true);
address += saveString(address, mqttUser);
address += saveString(address, mqttPass);
}
else
address += saveBool(address, false);
address += saveByte(address, authSecurity);
if (authSecurity > 0) {
address += saveString(address, authUser);
address += saveString(address, authPass);
}
address += saveInt(address, fuseSize);
address += saveInt(address, distSys);
bool success = EEPROM.commit();
EEPROM.end();
return success;
}
bool configuration::load()
{
int address = EEPROM_CONFIG_ADDRESS;
bool success = false;
ssid = 0;
ssidPassword = 0;
meterType = (byte)0;
mqttHost = 0;
mqttClientID = 0;
mqttPublishTopic = 0;
mqttSubscribeTopic = 0;
mqttUser = 0;
mqttPass = 0;
mqttPort = 1883;
authSecurity = 0;
authUser = 0;
authPass = 0;
fuseSize = 0;
distSys = 0;
EEPROM.begin(EEPROM_SIZE);
int cs = EEPROM.read(address);
if (cs == EEPROM_CHECK_SUM)
{
address++;
address += readString(address, &ssid);
address += readString(address, &ssidPassword);
address += readByte(address, &meterType);
bool mqtt = false;
address += readBool(address, &mqtt);
if(mqtt) {
address += readString(address, &mqttHost);
address += readInt(address, &mqttPort);
address += readString(address, &mqttClientID);
address += readString(address, &mqttPublishTopic);
address += readString(address, &mqttSubscribeTopic);
}
bool secure = false;
address += readBool(address, &secure);
if (secure)
{
address += readString(address, &mqttUser);
address += readString(address, &mqttPass);
}
else
{
mqttUser = 0;
mqttPass = 0;
}
address += readByte(address, &authSecurity);
if (authSecurity > 0) {
address += readString(address, &authUser);
address += readString(address, &authPass);
} else {
authUser = 0;
authPass = 0;
}
address += readInt(address, &fuseSize);
address += readByte(address, &distSys);
success = true;
}
EEPROM.end();
return success;
}
bool configuration::isSecure()
{
return (mqttUser != 0) && (String(mqttUser).length() > 0);
}
int configuration::readInt(int address, int *value)
{
int lower = EEPROM.read(address);
int higher = EEPROM.read(address + 1);
*value = lower + (higher << 8);
return 2;
}
int configuration::saveInt(int address, int value)
{
byte lowByte = value & 0xFF;
byte highByte = ((value >> 8) & 0xFF);
EEPROM.write(address, lowByte);
EEPROM.write(address + 1, highByte);
return 2;
}
int configuration::readBool(int address, bool *value)
{
byte y = EEPROM.read(address);
*value = (bool)y;
return 1;
}
int configuration::saveBool(int address, bool value)
{
byte y = (byte)value;
EEPROM.write(address, y);
return 1;
}
int configuration::readByte(int address, byte *value)
{
*value = EEPROM.read(address);
return 1;
}
int configuration::saveByte(int address, byte value)
{
EEPROM.write(address, value);
return 1;
}
void configuration::print(Stream* debugger)
{
debugger->println("Configuration:");
debugger->println("-----------------------------------------------");
debugger->printf("ssid: %s\r\n", this->ssid);
debugger->printf("ssidPassword: %s\r\n", this->ssidPassword);
debugger->printf("meterType: %i\r\n", this->meterType);
if(this->mqttHost) {
debugger->printf("mqttHost: %s\r\n", this->mqttHost);
debugger->printf("mqttPort: %i\r\n", this->mqttPort);
debugger->printf("mqttClientID: %s\r\n", this->mqttClientID);
debugger->printf("mqttPublishTopic: %s\r\n", this->mqttPublishTopic);
debugger->printf("mqttSubscribeTopic: %s\r\n", this->mqttSubscribeTopic);
}
if (this->isSecure())
{
debugger->printf("SECURE MQTT CONNECTION:\r\n");
debugger->printf("mqttUser: %s\r\n", this->mqttUser);
debugger->printf("mqttPass: %s\r\n", this->mqttPass);
}
if (this->authSecurity > 0) {
debugger->printf("WEB AUTH:\r\n");
debugger->printf("authSecurity: %i\r\n", this->authSecurity);
debugger->printf("authUser: %s\r\n", this->authUser);
debugger->printf("authPass: %s\r\n", this->authPass);
}
debugger->printf("fuseSize: %i\r\n", this->fuseSize);
debugger->printf("distSys: %i\r\n", this->distSys);
debugger->println("-----------------------------------------------");
}
template <class T> int configuration::writeAnything(int ee, const T& value)
{
const byte* p = (const byte*)(const void*)&value;
unsigned int i;
for (i = 0; i < sizeof(value); i++)
EEPROM.write(ee++, *p++);
return i;
}
template <class T> int configuration::readAnything(int ee, T& value)
{
byte* p = (byte*)(void*)&value;
unsigned int i;
for (i = 0; i < sizeof(value); i++)
*p++ = EEPROM.read(ee++);
return i;
}
int configuration::readString(int pAddress, char* pString[])
{
int address = 0;
byte length = EEPROM.read(pAddress + address);
address++;
char* buffer = new char[length];
for (int i = 0; i<length; i++)
{
buffer[i] = EEPROM.read(pAddress + address++);
}
*pString = buffer;
return address;
}
int configuration::saveString(int pAddress, char* pString)
{
int address = 0;
int length = pString ? strlen(pString) + 1 : 0;
EEPROM.put(pAddress + address, length);
address++;
for (int i = 0; i < length; i++)
{
EEPROM.put(pAddress + address, pString[i]);
address++;
}
return address;
}

View File

@@ -1,63 +0,0 @@
// config.h
#ifndef _CONFIGURATION_h
#define _CONFIGURATION_h
#include <EEPROM.h>
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
class configuration {
public:
char* ssid;
char* ssidPassword;
char* mqttHost;
int mqttPort;
char* mqttClientID;
char* mqttPublishTopic;
char* mqttSubscribeTopic;
char* mqttUser;
char* mqttPass;
byte meterType;
byte authSecurity;
char* authUser;
char* authPass;
int fuseSize;
byte distSys;
bool hasConfig();
bool isSecure();
bool save();
bool load();
void print(Stream* debugger);
protected:
private:
const int EEPROM_SIZE = 512;
const byte EEPROM_CHECK_SUM = 75; // Used to check if config is stored. Change if structure changes
const int EEPROM_CONFIG_ADDRESS = 0;
int saveString(int pAddress, char* pString);
int readString(int pAddress, char* pString[]);
int saveInt(int pAddress, int pValue);
int readInt(int pAddress, int *pValue);
int saveBool(int pAddress, bool pValue);
int readBool(int pAddress, bool *pValue);
int saveByte(int pAddress, byte pValue);
int readByte(int pAddress, byte *pValue);
template <class T> int writeAnything(int ee, const T& value);
template <class T> int readAnything(int ee, T& value);
};
#endif

View File

@@ -1,5 +1,5 @@
name=HANreader
version=1.0.0
version=1.0.1
author=roarfred
maintainer=roarfred <not@important.com>
sentence=HAN support
@@ -7,3 +7,4 @@ paragraph=HAN support
category=Sensors
url=https://github.com/roarfred/AmsToMqttBridge
architectures=*
depends=Timezone

View File

@@ -3,7 +3,6 @@
#ifndef _AIDON_h
#define _AIDON_h
enum class Aidon
{
List1 = 0x01,

View File

@@ -2,14 +2,19 @@
HanReader::HanReader()
{
}
void HanReader::setup(Stream *hanPort, Stream *debugPort)
void HanReader::setup(Stream *hanPort, RemoteDebug *debug)
{
han = hanPort;
bytesRead = 0;
debug = debugPort;
debugger = debug;
// Central European Time (Frankfurt, Paris)
TimeChangeRule CEST = {"CEST", Last, Sun, Mar, 2, 120}; // Central European Summer Time
TimeChangeRule CET = {"CET ", Last, Sun, Oct, 3, 60}; // Central European Standard Time
localZone = new Timezone(CEST, CET);
if (debug) debug->println("MBUS serial setup complete");
}
@@ -18,26 +23,22 @@ void HanReader::setup(Stream *hanPort)
setup(hanPort, NULL);
}
bool HanReader::read(byte data)
{
if (reader.Read(data))
{
bool HanReader::read(byte data) {
if (reader.Read(data)) {
bytesRead = reader.GetRawData(buffer, 0, 512);
if (debug)
{
debug->print("Got valid DLMS data (");
debug->print(bytesRead);
debug->println(" bytes):");
debugPrint(buffer, 0, bytesRead);
if (debugger->isActive(RemoteDebug::INFO)) {
printI("Got valid DLMS data (%d bytes)", bytesRead);
if (debugger->isActive(RemoteDebug::DEBUG)) {
debugPrint(buffer, 0, bytesRead);
}
}
/*
Data should start with E6 E7 00 0F
and continue with four bytes for the InvokeId
*/
if (bytesRead < 9)
{
if (debug) debug->println("Invalid HAN data: Less than 9 bytes received");
if (bytesRead < 9) {
printW("Invalid HAN data: Less than 9 bytes received");
return false;
}
else if (
@@ -47,85 +48,74 @@ bool HanReader::read(byte data)
buffer[3] != 0x0F
)
{
if (debug) debug->println("Invalid HAN data: Start should be E6 E7 00 0F");
printW("Invalid HAN data: Start should be E6 E7 00 0F");
return false;
}
listSize = getInt(0, buffer, 0, bytesRead);
if (debug) debug->print("HAN data is valid, listSize: ");
if (debug) debug->println(listSize);
printI("HAN data is valid, listSize: %d", listSize);
return true;
}
return false;
}
void HanReader::debugPrint(byte *buffer, int start, int length)
{
for (int i = start; i < start + length; i++)
{
void HanReader::debugPrint(byte *buffer, int start, int length) {
for (int i = start; i < start + length; i++) {
if (buffer[i] < 0x10)
debug->print("0");
debug->print(buffer[i], HEX);
debug->print(" ");
debugger->print("0");
debugger->print(buffer[i], HEX);
debugger->print(" ");
if ((i - start + 1) % 16 == 0)
debug->println("");
debugger->println("");
else if ((i - start + 1) % 4 == 0)
debug->print(" ");
debugger->print(" ");
yield(); // Let other get some resources too
}
debug->println("");
debugger->println("");
}
bool HanReader::read()
{
if (han->available())
{
byte newByte = han->read();
return read(newByte);
bool HanReader::read() {
while(han->available()) {
if(read(han->read())) {
return true;
}
}
return false;
}
int HanReader::getListSize()
{
int HanReader::getListSize() {
return listSize;
}
time_t HanReader::getPackageTime()
{
time_t HanReader::getPackageTime() {
int packageTimePosition = dataHeader
+ (compensateFor09HeaderBug ? 1 : 0);
return getTime(buffer, packageTimePosition, bytesRead);
}
time_t HanReader::getTime(int objectId)
{
time_t HanReader::getTime(int objectId) {
return getTime(objectId, buffer, 0, bytesRead);
}
int HanReader::getInt(int objectId)
{
int HanReader::getInt(int objectId) {
return getInt(objectId, buffer, 0, bytesRead);
}
String HanReader::getString(int objectId)
{
String HanReader::getString(int objectId) {
return getString(objectId, buffer, 0, bytesRead);
}
int HanReader::findValuePosition(int dataPosition, byte *buffer, int start, int length)
{
int HanReader::findValuePosition(int dataPosition, byte *buffer, int start, int length) {
// The first byte after the header gives the length
// of the extended header information (variable)
int headerSize = dataHeader + (compensateFor09HeaderBug ? 1 : 0);
int firstData = headerSize + buffer[headerSize] + 1;
for (int i = start + firstData; i<length; i++)
{
for (int i = start + firstData; i<length; i++) {
if (dataPosition-- == 0)
return i;
else if (buffer[i] == 0x00) // null
@@ -148,42 +138,30 @@ int HanReader::findValuePosition(int dataPosition, byte *buffer, int start, int
i += 1;
else if (buffer[i] == 0x16) // enum (1 bytes)
i += 1;
else
{
if (debug)
{
debug->print("Unknown data type found: 0x");
debug->println(buffer[i], HEX);
}
else {
printW("Unknown data type found: 0x%s", String(buffer[i], HEX).c_str());
return 0; // unknown data type found
}
}
if (debug)
{
debug->print("Passed the end of the data. Length was: ");
debug->println(length);
}
printD("Passed the end of the data. Length was: %d", length);
return 0;
}
time_t HanReader::getTime(int dataPosition, byte *buffer, int start, int length)
{
time_t HanReader::getTime(int dataPosition, byte *buffer, int start, int length) {
// TODO: check if the time is represented always as a 12 byte string (0x09 0x0C)
int timeStart = findValuePosition(dataPosition, buffer, start, length);
timeStart += 1;
return getTime(buffer, start + timeStart, length - timeStart);
}
time_t HanReader::getTime(byte *buffer, int start, int length)
{
time_t HanReader::getTime(byte *buffer, int start, int length) {
int pos = start;
int dataLength = buffer[pos++];
if (dataLength == 0x0C)
{
if (dataLength == 0x0C) {
int year = buffer[pos] << 8 |
buffer[pos + 1];
@@ -193,25 +171,30 @@ time_t HanReader::getTime(byte *buffer, int start, int length)
int minute = buffer[pos + 6];
int second = buffer[pos + 7];
return toUnixTime(year, month, day, hour, minute, second);
}
else
{
tmElements_t tm;
tm.Year = year - 1970;
tm.Month = month;
tm.Day = day;
tm.Hour = hour;
tm.Minute = minute;
tm.Second = second;
return localZone->toUTC(makeTime(tm));
} else if(dataLength == 0) {
return (time_t)0L;
} else {
printW("Unknown time length: %d", dataLength);
// Date format not supported
return (time_t)0L;
}
}
int HanReader::getInt(int dataPosition, byte *buffer, int start, int length)
{
int HanReader::getInt(int dataPosition, byte *buffer, int start, int length) {
int valuePosition = findValuePosition(dataPosition, buffer, start, length);
if (valuePosition > 0)
{
if (valuePosition > 0) {
int value = 0;
int bytes = 0;
switch (buffer[valuePosition++])
{
switch (buffer[valuePosition++]) {
case 0x10:
bytes = 2;
break;
@@ -235,8 +218,7 @@ int HanReader::getInt(int dataPosition, byte *buffer, int start, int length)
break;
}
for (int i = valuePosition; i < valuePosition + bytes; i++)
{
for (int i = valuePosition; i < valuePosition + bytes; i++) {
value = value << 8 | buffer[i];
}
@@ -245,14 +227,11 @@ int HanReader::getInt(int dataPosition, byte *buffer, int start, int length)
return 0;
}
String HanReader::getString(int dataPosition, byte *buffer, int start, int length)
{
String HanReader::getString(int dataPosition, byte *buffer, int start, int length) {
int valuePosition = findValuePosition(dataPosition, buffer, start, length);
if (valuePosition > 0)
{
if (valuePosition > 0) {
String value = String("");
for (int i = valuePosition + 2; i < valuePosition + buffer[valuePosition + 1] + 2; i++)
{
for (int i = valuePosition + 2; i < valuePosition + buffer[valuePosition + 1] + 2; i++) {
value += String((char)buffer[i]);
}
return value;
@@ -260,29 +239,22 @@ String HanReader::getString(int dataPosition, byte *buffer, int start, int lengt
return String("");
}
time_t HanReader::toUnixTime(int year, int month, int day, int hour, int minute, int second)
{
byte daysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
long secondsPerMinute = 60;
long secondsPerHour = secondsPerMinute * 60;
long secondsPerDay = secondsPerHour * 24;
long time = (year - 1970) * secondsPerDay * 365L;
for (int yearCounter = 1970; yearCounter<year; yearCounter++)
if ((yearCounter % 4 == 0) && ((yearCounter % 100 != 0) || (yearCounter % 400 == 0)))
time += secondsPerDay;
if (month > 2 && (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)))
time += secondsPerDay;
for (int monthCounter = 1; monthCounter<month; monthCounter++)
time += daysInMonth[monthCounter - 1] * secondsPerDay;
time += (day - 1) * secondsPerDay;
time += hour * secondsPerHour;
time += minute * secondsPerMinute;
time += second;
return (time_t)time;
void HanReader::printD(String fmt, int arg) {
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf(String("(HanReader)" + fmt + "\n").c_str(), arg);
}
void HanReader::printI(String fmt, int arg) {
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf(String("(HanReader)" + fmt + "\n").c_str(), arg);
}
void HanReader::printW(String fmt, int arg) {
if(debugger->isActive(RemoteDebug::WARNING)) debugger->printf(String("(HanReader)" + fmt + "\n").c_str(), arg);
}
void HanReader::printW(String fmt, const char* arg) {
if(debugger->isActive(RemoteDebug::WARNING)) debugger->printf(String("(HanReader)" + fmt + "\n").c_str(), arg);
}
void HanReader::printE(String fmt, int arg) {
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf(String("(HanReader)" + fmt + "\n").c_str(), arg);
}

View File

@@ -9,7 +9,8 @@
#include "DlmsReader.h"
#include <Timezone.h>
#include "RemoteDebug.h"
class HanReader
{
@@ -19,7 +20,7 @@ public:
HanReader();
void setup(Stream *hanPort);
void setup(Stream *hanPort, Stream *debugPort);
void setup(Stream *hanPort, RemoteDebug *debug);
bool read();
bool read(byte data);
int getListSize();
@@ -29,12 +30,13 @@ public:
time_t getTime(int objectId);
private:
Stream *debug;
RemoteDebug* debugger;
Stream *han;
byte buffer[512];
int bytesRead;
DlmsReader reader;
int listSize;
Timezone *localZone;
int findValuePosition(int dataPosition, byte *buffer, int start, int length);
@@ -46,6 +48,12 @@ private:
time_t toUnixTime(int year, int month, int day, int hour, int minute, int second);
void debugPrint(byte *buffer, int start, int length);
void printD(String fmt, int arg=0);
void printI(String fmt, int arg=0);
void printW(String fmt, int arg=0);
void printW(String fmt, const char* arg);
void printE(String fmt, int arg=0);
};

View File

@@ -3,7 +3,6 @@
#ifndef _KAMSTRUP_h
#define _KAMSTRUP_h
enum class Kamstrup
{
List3PhaseShort = 0x19,

View File

@@ -1,9 +0,0 @@
name=HanToJson
version=1.0.0
author=roarfred
maintainer=roarfred <not@important.com>
sentence=HAN reader data to Json
paragraph=HAN reader data to Json
category=Sensors
url=https://github.com/roarfred/AmsToMqttBridge
architectures=*

View File

@@ -1,280 +0,0 @@
#include "HanToJson.h"
#include "Aidon.h"
#include "Kaifa.h"
#include "Kamstrup.h"
static void hanToJsonKaifa3phase(int listSize, JsonObject& data, HanReader& hanReader, Stream *debugger)
{
if (listSize >= (int)Kaifa::List3PhaseShort)
{
data["lv"] = hanReader.getString( (int)Kaifa_List3Phase::ListVersionIdentifier);
data["id"] = hanReader.getString( (int)Kaifa_List3Phase::MeterID);
data["type"] = hanReader.getString( (int)Kaifa_List3Phase::MeterType);
data["P"] = hanReader.getInt( (int)Kaifa_List3Phase::ActiveImportPower);
data["Q"] = hanReader.getInt( (int)Kaifa_List3Phase::ReactiveImportPower);
data["I1"] = ((double) hanReader.getInt((int)Kaifa_List3Phase::CurrentL1)) / 1000;
data["I2"] = ((double) hanReader.getInt((int)Kaifa_List3Phase::CurrentL2)) / 1000;
data["I3"] = ((double) hanReader.getInt((int)Kaifa_List3Phase::CurrentL3)) / 1000;
data["U1"] = ((double) hanReader.getInt((int)Kaifa_List3Phase::VoltageL1)) / 10;
data["U2"] = ((double) hanReader.getInt((int)Kaifa_List3Phase::VoltageL2)) / 10;
data["U3"] = ((double) hanReader.getInt((int)Kaifa_List3Phase::VoltageL3)) / 10;
}
if (listSize >= (int)Kaifa::List3PhaseLong)
{
data["tPI"] = hanReader.getInt( (int)Kaifa_List3Phase::CumulativeActiveImportEnergy);
data["tPO"] = hanReader.getInt( (int)Kaifa_List3Phase::CumulativeActiveExportEnergy);
data["tQI"] = hanReader.getInt( (int)Kaifa_List3Phase::CumulativeReactiveImportEnergy);
data["tQO"] = hanReader.getInt( (int)Kaifa_List3Phase::CumulativeReactiveExportEnergy);
}
}
static void hanToJsonKaifa1phase(int listSize, JsonObject& data, HanReader& hanReader, Stream *debugger)
{
if (listSize >= (int)Kaifa::List1PhaseShort)
{
data["lv"] = hanReader.getString( (int)Kaifa_List1Phase::ListVersionIdentifier);
data["id"] = hanReader.getString( (int)Kaifa_List1Phase::MeterID);
data["type"] = hanReader.getString( (int)Kaifa_List1Phase::MeterType);
data["P"] = hanReader.getInt( (int)Kaifa_List1Phase::ActiveImportPower);
data["Q"] = hanReader.getInt( (int)Kaifa_List1Phase::ReactiveImportPower);
data["I1"] = ((double) hanReader.getInt((int)Kaifa_List1Phase::CurrentL1)) / 1000;
data["U1"] = ((double) hanReader.getInt((int)Kaifa_List1Phase::VoltageL1)) / 10;
}
if (listSize >= (int)Kaifa::List1PhaseLong)
{
data["tPI"] = hanReader.getInt( (int)Kaifa_List1Phase::CumulativeActiveImportEnergy);
data["tPO"] = hanReader.getInt( (int)Kaifa_List1Phase::CumulativeActiveExportEnergy);
data["tQI"] = hanReader.getInt( (int)Kaifa_List1Phase::CumulativeReactiveImportEnergy);
data["tQO"] = hanReader.getInt( (int)Kaifa_List1Phase::CumulativeReactiveExportEnergy);
}
}
static void hanToJsonKaifa(JsonObject& data, HanReader& hanReader, Stream *debugger)
{
int listSize = hanReader.getListSize();
if (listSize == (int)Kaifa::List1)
{
// Handle listSize == 1 specially
data["P"] = hanReader.getInt( (int)Kaifa_List1::ActivePowerImported);
return;
}
switch (listSize) {
case (int)Kaifa::List3PhaseShort:
case (int)Kaifa::List3PhaseLong:
return hanToJsonKaifa3phase(listSize, data, hanReader, debugger);
case (int)Kaifa::List1PhaseShort:
case (int)Kaifa::List1PhaseLong:
return hanToJsonKaifa1phase(listSize, data, hanReader, debugger);
default:
if (debugger) debugger->printf("Warning: Unknown listSize %d\n", listSize);
return;
}
}
static void hanToJsonAidon3phase(int listSize, JsonObject& data, HanReader& hanReader, Stream *debugger)
{
if (listSize >= (int)Aidon::List3PhaseShort)
{
data["lv"] = hanReader.getString( (int)Aidon_List3Phase::ListVersionIdentifier);
data["id"] = hanReader.getString( (int)Aidon_List3Phase::MeterID);
data["type"] = hanReader.getString( (int)Aidon_List3Phase::MeterType);
data["P"] = hanReader.getInt( (int)Aidon_List3Phase::ActiveImportPower);
data["Q"] = hanReader.getInt( (int)Aidon_List3Phase::ReactiveExportPower);
data["I1"] = ((double) hanReader.getInt( (int)Aidon_List3Phase::CurrentL1)) / 10;
data["I2"] = ((double) hanReader.getInt( (int)Aidon_List3Phase::CurrentL2)) / 10;
data["I3"] = ((double) hanReader.getInt( (int)Aidon_List3Phase::CurrentL3)) / 10;
data["U1"] = ((double) hanReader.getInt( (int)Aidon_List3Phase::VoltageL1)) / 10;
data["U2"] = ((double) hanReader.getInt( (int)Aidon_List3Phase::VoltageL2)) / 10;
data["U3"] = ((double) hanReader.getInt( (int)Aidon_List3Phase::VoltageL3)) / 10;
}
if (listSize >= (int)Aidon::List3PhaseLong)
{
data["tPI"] = hanReader.getInt( (int)Aidon_List3Phase::CumulativeActiveImportEnergy);
data["tPO"] = hanReader.getInt( (int)Aidon_List3Phase::CumulativeActiveExportEnergy);
data["tQI"] = hanReader.getInt( (int)Aidon_List3Phase::CumulativeReactiveImportEnergy);
data["tQO"] = hanReader.getInt( (int)Aidon_List3Phase::CumulativeReactiveExportEnergy);
}
}
static void hanToJsonAidon1phase(int listSize, JsonObject& data, HanReader& hanReader, Stream *debugger)
{
if (listSize >= (int)Aidon::List1PhaseShort)
{
data["lv"] = hanReader.getString( (int)Aidon_List1Phase::ListVersionIdentifier);
data["id"] = hanReader.getString( (int)Aidon_List1Phase::MeterID);
data["type"] = hanReader.getString( (int)Aidon_List1Phase::MeterType);
data["P"] = hanReader.getInt( (int)Aidon_List1Phase::ActiveImportPower);
data["Q"] = hanReader.getInt( (int)Aidon_List1Phase::ReactiveExportPower);
data["I1"] = ((double) hanReader.getInt( (int)Aidon_List1Phase::CurrentL1)) / 10;
data["U1"] = ((double) hanReader.getInt( (int)Aidon_List1Phase::VoltageL1)) / 10;
}
if (listSize >= (int)Aidon::List1PhaseLong)
{
data["tPI"] = hanReader.getInt( (int)Aidon_List1Phase::CumulativeActiveImportEnergy);
data["tPO"] = hanReader.getInt( (int)Aidon_List1Phase::CumulativeActiveExportEnergy);
data["tQI"] = hanReader.getInt( (int)Aidon_List1Phase::CumulativeReactiveImportEnergy);
data["tQO"] = hanReader.getInt( (int)Aidon_List1Phase::CumulativeReactiveExportEnergy);
}
}
static void hanToJsonAidon3phaseIT(int listSize, JsonObject& data, HanReader& hanReader, Stream *debugger)
{
if (listSize >= (int)Aidon::List3PhaseITShort)
{
data["lv"] = hanReader.getString( (int)Aidon_List3PhaseIT::ListVersionIdentifier);
data["id"] = hanReader.getString( (int)Aidon_List3PhaseIT::MeterID);
data["type"] = hanReader.getString( (int)Aidon_List3PhaseIT::MeterType);
int p = hanReader.getInt( (int)Aidon_List3PhaseIT::ActiveImportPower);
data["P"] = p;
data["Q"] = hanReader.getInt( (int)Aidon_List3PhaseIT::ReactiveExportPower);
double i1 = ((double) hanReader.getInt( (int)Aidon_List3PhaseIT::CurrentL1)) / 10;
double i3 = ((double) hanReader.getInt( (int)Aidon_List3PhaseIT::CurrentL3)) / 10;
double u1 = ((double) hanReader.getInt( (int)Aidon_List3PhaseIT::VoltageL1)) / 10;
double u2 = ((double) hanReader.getInt( (int)Aidon_List3PhaseIT::VoltageL2)) / 10;
double u3 = ((double) hanReader.getInt( (int)Aidon_List3PhaseIT::VoltageL3)) / 10;
double i2 = 0.00;
data["I1"] = i1;
data["I2"] = i2;
data["I3"] = i3;
data["U1"] = u1;
data["U2"] = u2;
data["U3"] = u3;
}
if (listSize >= (int)Aidon::List3PhaseITLong)
{
data["tPI"] = hanReader.getInt( (int)Aidon_List3PhaseIT::CumulativeActiveImportEnergy);
data["tPO"] = hanReader.getInt( (int)Aidon_List3PhaseIT::CumulativeActiveExportEnergy);
data["tQI"] = hanReader.getInt( (int)Aidon_List3PhaseIT::CumulativeReactiveImportEnergy);
data["tQO"] = hanReader.getInt( (int)Aidon_List3PhaseIT::CumulativeReactiveExportEnergy);
}
}
static void hanToJsonAidon(JsonObject& data, HanReader& hanReader, Stream *debugger)
{
int listSize = hanReader.getListSize();
// Based on the list number, get all details
// according to OBIS specifications for the meter
if (listSize == (int)Aidon::List1)
{
// Handle listSize == 1 specially
data["P"] = hanReader.getInt((int)Aidon_List1::ActiveImportPower);
return;
}
switch (listSize) {
case (int)Aidon::List3PhaseShort:
case (int)Aidon::List3PhaseLong:
return hanToJsonAidon3phase(listSize, data, hanReader, debugger);
case (int)Aidon::List1PhaseShort:
case (int)Aidon::List1PhaseLong:
return hanToJsonAidon1phase(listSize, data, hanReader, debugger);
case (int)Aidon::List3PhaseITShort:
case (int)Aidon::List3PhaseITLong:
return hanToJsonAidon3phaseIT(listSize, data, hanReader, debugger);
default:
if (debugger) debugger->printf("Warning: Unknown listSize %d\n", listSize);
return;
}
}
static void hanToJsonKamstrup3phase(int listSize, JsonObject& data, HanReader& hanReader, Stream *debugger)
{
if (listSize >= (int)Kamstrup::List3PhaseShort)
{
data["lv"] = hanReader.getString( (int)Kamstrup_List3Phase::ListVersionIdentifier);
data["id"] = hanReader.getString( (int)Kamstrup_List3Phase::MeterID);
data["type"] = hanReader.getString( (int)Kamstrup_List3Phase::MeterType);
data["P"] = hanReader.getInt( (int)Kamstrup_List3Phase::ActiveImportPower);
data["Q"] = hanReader.getInt( (int)Kamstrup_List3Phase::ReactiveImportPower);
data["I1"] = ((double) hanReader.getInt((int)Kamstrup_List3Phase::CurrentL1)) / 100;
data["I2"] = ((double) hanReader.getInt((int)Kamstrup_List3Phase::CurrentL2)) / 100;
data["I3"] = ((double) hanReader.getInt((int)Kamstrup_List3Phase::CurrentL3)) / 100;
data["U1"] = hanReader.getInt( (int)Kamstrup_List3Phase::VoltageL1);
data["U2"] = hanReader.getInt( (int)Kamstrup_List3Phase::VoltageL2);
data["U3"] = hanReader.getInt( (int)Kamstrup_List3Phase::VoltageL3);
}
if (listSize >= (int)Kamstrup::List3PhaseLong)
{
data["tPI"] = hanReader.getInt( (int)Kamstrup_List3Phase::CumulativeActiveImportEnergy);
data["tPO"] = hanReader.getInt( (int)Kamstrup_List3Phase::CumulativeActiveExportEnergy);
data["tQI"] = hanReader.getInt( (int)Kamstrup_List3Phase::CumulativeReactiveImportEnergy);
data["tQO"] = hanReader.getInt( (int)Kamstrup_List3Phase::CumulativeReactiveExportEnergy);
}
}
static void hanToJsonKamstrup1phase(int listSize, JsonObject& data, HanReader& hanReader, Stream *debugger)
{
if (listSize >= (int)Kamstrup::List1PhaseShort)
{
data["lv"] = hanReader.getString( (int)Kamstrup_List1Phase::ListVersionIdentifier);
data["id"] = hanReader.getString( (int)Kamstrup_List1Phase::MeterID);
data["type"] = hanReader.getString( (int)Kamstrup_List1Phase::MeterType);
data["P"] = hanReader.getInt( (int)Kamstrup_List1Phase::ActiveImportPower);
data["Q"] = hanReader.getInt( (int)Kamstrup_List1Phase::ReactiveImportPower);
data["I1"] = ((double) hanReader.getInt((int)Kamstrup_List1Phase::CurrentL1)) / 100;
data["U1"] = hanReader.getInt( (int)Kamstrup_List1Phase::VoltageL1);
}
if (listSize >= (int)Kamstrup::List1PhaseLong)
{
data["tPI"] = hanReader.getInt( (int)Kamstrup_List1Phase::CumulativeActiveImportEnergy);
data["tPO"] = hanReader.getInt( (int)Kamstrup_List1Phase::CumulativeActiveExportEnergy);
data["tQI"] = hanReader.getInt( (int)Kamstrup_List1Phase::CumulativeReactiveImportEnergy);
data["tQO"] = hanReader.getInt( (int)Kamstrup_List1Phase::CumulativeReactiveExportEnergy);
}
}
static void hanToJsonKamstrup(JsonObject& data, HanReader& hanReader, Stream *debugger)
{
int listSize = hanReader.getListSize();
switch (listSize) {
case (int)Kamstrup::List3PhaseShort:
case (int)Kamstrup::List3PhaseLong:
return hanToJsonKamstrup3phase(listSize, data, hanReader, debugger);
case (int)Kamstrup::List1PhaseShort:
case (int)Kamstrup::List1PhaseLong:
return hanToJsonKamstrup1phase(listSize, data, hanReader, debugger);
default:
if (debugger) debugger->printf("Warning: Unknown listSize %d\n", listSize);
return;
}
}
void hanToJson(JsonObject& data, byte meterType, HanReader& hanReader, Stream *debugger)
{
// Based on the list number, get all details
// according to OBIS specifications for the meter
switch (meterType)
{
case 1: // Kaifa
return hanToJsonKaifa(data, hanReader, debugger);
case 2: // Aidon
return hanToJsonAidon(data, hanReader, debugger);
case 3: // Kamstrup
return hanToJsonKamstrup(data, hanReader, debugger);
default:
if (debugger) {
debugger->print("Meter type ");
debugger->print(meterType, HEX);
debugger->println(" is unknown");
}
break;
}
}
void hanToJson(JsonObject& data, byte meterType, HanReader& hanReader)
{
return hanToJson(data, meterType, hanReader, NULL);
}

View File

@@ -1,17 +0,0 @@
#ifndef _HANTOJSON_h
#define _HANTOJSON_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <ArduinoJson.h>
#include "HanReader.h"
void hanToJson(JsonObject& data, byte meterType, HanReader& hanReader);
void hanToJson(JsonObject& root, byte meterType, HanReader& hanReader, Stream *debugPort);
#endif

View File

@@ -0,0 +1,18 @@
# A GitHub Manifesto
### Notes on contributing to my repositories
Jack Christensen
Jan 2018
Surely Git and GitHub are wonderful tools. They make coding and collaboration so much easier. I'm equally impressed with the open source movement, and with the Arduino ecosystem in particular.
I'm just one guy, mostly a hobbyist. Posting my projects to GitHub is my way of giving back a little to the community. It's very gratifying that some of my code has received a modicum of popularity.
Like many things, this has been somewhat of a double-edged sword. Especially since I tend to be a pretty busy guy with many varied interests.
First, I am always interested in bug reports. Please raise an issue in the appropriate repository and please please please include a good, concise description of the issue and a Short, Self Contained, Correct (Compilable), Example (see [sscce.org](http://www.sscce.org/)). I will need to be able to reproduce the issue, with minimal hardware, and without installing a dozen other libraries. I work exclusively with the AVR architecture so most times I will not be able to reproduce issues on other platforms. (There have been one or two occasions where relatively simple changes have been made to accommodate another platform; I am not necessarily averse to these.)
Second, bug reports should always be for problems with *my* code. I will not use GitHub to help you with *your* code, even if you happen to be using one of my libraries. Please use the [Arduino forum](https://forum.arduino.cc/) or other such venue instead.
Finally, pull requests can be problematic, especially if they represent enhancements rather than fixes. I seldom intend my code to be all things to all people. This is mostly a hobby activity and I have very limited bandwidth. Reviewing and managing PRs requires time that I do not often have. Sometimes a PR will take a library in a direction that I'm not interested in. Sometimes a PR will be counter to my original design intent. No doubt the author of a PR thinks that their new feature is the best thing since canned beer, but if I don't happen to share that opinion, then I'll decline it. OTOH, I am certainly capable of making stupid mistakes and missing absolutely fundamental things, and I do appreciate it when these are pointed out.
All this to say, that if I do decline a request, please do not take it personally. Feel free to consider it my problem, not yours. At the end of the day, it's my code, and I reserve the right to decline issues or PRs for any reason, or for no reason at all. But here is the beauty of open source. You can always fork the repository and have your way with it.

675
lib/Timezone/LICENSE.md Normal file
View File

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

196
lib/Timezone/README.md Normal file
View File

@@ -0,0 +1,196 @@
# Arduino Timezone Library
https://github.com/JChristensen/Timezone
README file
Jack Christensen
Mar 2012
## License
Arduino Timezone Library Copyright (C) 2018 Jack Christensen GNU GPL v3.0
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License v3.0 as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/gpl.html>
## Introduction
The **Timezone** library is designed to work in conjunction with the [Arduino Time library](https://github.com/PaulStoffregen/Time), which must also be installed on your system. This documentation assumes some familiarity with the Time library.
The primary aim of the **Timezone** library is to convert Universal Coordinated Time (UTC) to the correct local time, whether it is daylight saving time (a.k.a. summer time) or standard time. The time source could be a GPS receiver, an NTP server, or a Real-Time Clock (RTC) set to UTC. But whether a hardware RTC or other time source is even present is immaterial, since the Time library can function as a software RTC without additional hardware (although its accuracy is dependent on the accuracy of the microcontroller's system clock.)
The **Timezone** library implements two objects to facilitate time zone conversions:
- A **TimeChangeRule** object describes when local time changes to daylight (summer) time, or to standard time, for a particular locale.
- A **Timezone** object uses **TimeChangeRule**s to perform conversions and related functions. It can also write its **TimeChangeRule**s to EEPROM, or read them from EEPROM. Multiple time zones can be represented by defining multiple **Timezone** objects.
## Examples
The following example sketches are included with the **Timezone** library:
- **Clock:** A simple self-adjusting clock for a single time zone. **TimeChangeRule**s may be optionally read from EEPROM.
- **HardwareRTC:** A self-adjusting clock for one time zone using an external real-time clock, either a DS1307 or DS3231 (e.g. Chronodot) which is set to UTC.
- **WorldClock:** A self-adjusting clock for multiple time zones.
- **WriteRules:** A sketch to write **TimeChangeRule**s to EEPROM.
- **Change_TZ_1:** Changes between time zones by modifying the TimeChangeRules.
- **Change_TZ_2:** Changes between time zones by selecting from an array of Timezone objects.
## Coding TimeChangeRules
Normally these will be coded in pairs for a given time zone: One rule to describe when daylight (summer) time starts, and one to describe when standard time starts.
As an example, here in the Eastern US time zone, Eastern Daylight Time (EDT) starts on the 2nd Sunday in March at 02:00 local time. Eastern Standard Time (EST) starts on the 1st Sunday in November at 02:00 local time.
Define a **TimeChangeRule** as follows:
`TimeChangeRule myRule = {abbrev, week, dow, month, hour, offset};`
Where:
**abbrev** is a character string abbreviation for the time zone; it must be no longer than five characters.
**week** is the week of the month that the rule starts.
**dow** is the day of the week that the rule starts.
**hour** is the hour in local time that the rule starts (0-23).
**offset** is the UTC offset _in minutes_ for the time zone being defined.
For convenience, the following symbolic names can be used:
**week:** First, Second, Third, Fourth, Last
**dow:** Sun, Mon, Tue, Wed, Thu, Fri, Sat
**month:** Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
For the Eastern US time zone, the **TimeChangeRule**s could be defined as follows:
```c++
TimeChangeRule usEDT = {"EDT", Second, Sun, Mar, 2, -240}; //UTC - 4 hours
TimeChangeRule usEST = {"EST", First, Sun, Nov, 2, -300}; //UTC - 5 hours
```
## Coding Timezone objects
There are three ways to define **Timezone** objects.
By first defining **TimeChangeRule**s (as above) and giving the daylight time rule and the standard time rule (assuming usEDT and usEST defined as above):
`Timezone usEastern(usEDT, usEST);`
For a time zone that does not change to daylight/summer time, pass a single rule to the constructor. For example:
`Timezone usAZ(usMST, usMST);`
By reading rules previously stored in EEPROM. This reads both the daylight and standard time rules previously stored at EEPROM address 100:
`Timezone usPacific(100);`
Note that **TimeChangeRule**s require 12 bytes of storage each, so the pair of rules associated with a Timezone object requires 24 bytes total. This could possibly change in future versions of the library. The size of a **TimeChangeRule** can be checked with `sizeof(usEDT)`.
## Timezone library methods
Note that the `time_t` data type is defined by the Arduino Time library <TimeLib.h>. See the Time library documentation [here](https://playground.arduino.cc/Code/Time) and [here](https://www.pjrc.com/teensy/td_libs_Time.html) for additional details.
### time_t toLocal(time_t utc);
##### Description
Converts the given UTC time to local time, standard or daylight as appropriate.
##### Syntax
`myTZ.toLocal(utc);`
##### Parameters
***utc:*** Universal Coordinated Time *(time_t)*
##### Returns
Local time *(time_t)*
##### Example
```c++
time_t eastern, utc;
TimeChangeRule usEDT = {"EDT", Second, Sun, Mar, 2, -240}; //UTC - 4 hours
TimeChangeRule usEST = {"EST", First, Sun, Nov, 2, -300}; //UTC - 5 hours
Timezone usEastern(usEDT, usEST);
utc = now(); //current time from the Time Library
eastern = usEastern.toLocal(utc);
```
### time_t toLocal(time_t utc, TimeChangeRule **tcr);
##### Description
As above, converts the given UTC time to local time, and also returns a pointer to the **TimeChangeRule** that was applied to do the conversion. This could then be used, for example, to include the time zone abbreviation as part of a time display. The caller must take care not to alter the pointed **TimeChangeRule**, as this will then result in incorrect conversions.
##### Syntax
`myTZ.toLocal(utc, &tcr);`
##### Parameters
***utc:*** Universal Coordinated Time *(time_t)*
***tcr:*** Address of a pointer to a **TimeChangeRule** _(\*\*TimeChangeRule)_
##### Returns
Local time *(time_t)*
Pointer to **TimeChangeRule** _(\*\*TimeChangeRule)_
##### Example
```c++
time_t eastern, utc;
TimeChangeRule *tcr;
TimeChangeRule usEDT = {"EDT", Second, Sun, Mar, 2, -240}; //UTC - 4 hours
TimeChangeRule usEST = {"EST", First, Sun, Nov, 2, -300}; //UTC - 5 hours
Timezone usEastern(usEDT, usEST);
utc = now(); //current time from the Time Library
eastern = usEastern.toLocal(utc, &tcr);
Serial.print("The time zone is: ");
Serial.println(tcr -> abbrev);
```
### bool utcIsDST(time_t utc);
### bool locIsDST(time_t local);
##### Description
These functions determine whether a given UTC time or a given local time is within the daylight saving (summer) time interval, and return true or false accordingly.
##### Syntax
`utcIsDST(utc);`
`locIsDST(local);`
##### Parameters
***utc:*** Universal Coordinated Time *(time_t)*
***local:*** Local Time *(time_t)*
##### Returns
true or false *(bool)*
##### Example
`if (usEastern.utcIsDST(utc)) { /*do something*/ }`
### void readRules(int address);
### void writeRules(int address);
##### Description
These functions read or write a **Timezone** object's two **TimeChangeRule**s from or to EEPROM.
##### Syntax
`myTZ.readRules(address);`
`myTZ.writeRules(address);`
##### Parameters
***address:*** The beginning EEPROM address to write to or read from *(int)*
##### Returns
None.
##### Example
`usEastern.writeRules(100); //write rules beginning at EEPROM address 100`
### void setRules(TimeChangeRule dstStart, TimeChangeRule stdStart);
##### Description
This function reads or updates the daylight and standard time rules from RAM. Can be used to change TimeChangeRules dynamically while a sketch runs.
##### Syntax
`myTZ.setRules(dstStart, stdStart);`
##### Parameters
***dstStart:*** A TimeChangeRule denoting the start of daylight saving (summer) time.
***stdStart:*** A TimeChangeRule denoting the start of standard time.
##### Returns
None.
##### Example
```c++
TimeChangeRule EDT = {"EDT", Second, Sun, Mar, 2, -240};
TimeChangeRule EST = {"EST", First, Sun, Nov, 2, -300};
Timezone ET(EDT, EST);
...
tz.setRules(EDT, EST);
```
### time_t toUTC(time_t local);
##### Description
Converts the given local time to UTC time.
**WARNING:** This function is provided for completeness, but should seldom be needed and should be used sparingly and carefully.
Ambiguous situations occur after the Standard-to-DST and the DST-to-Standard time transitions. When changing to DST, there is one hour of local time that does not exist, since the clock moves forward one hour. Similarly, when changing to standard time, there is one hour of local time that occurs twice since the clock moves back one hour.
This function does not test whether it is passed an erroneous time value during the Local-to-DST transition that does not exist. If passed such a time, an incorrect UTC time value will be returned.
If passed a local time value during the DST-to-Local transition that occurs twice, it will be treated as the earlier time, i.e. the time that occurs before the transition.
Calling this function with local times during a transition interval should be avoided!
##### Syntax
`myTZ.toUTC(local);`
##### Parameters
***local:*** Local Time *(time_t)*
##### Returns
UTC *(time_t)*

View File

@@ -0,0 +1,119 @@
// Arduino Timezone Library Copyright (C) 2018 by Jack Christensen and
// licensed under GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html
//
// Arduino Timezone Library example sketch.
// Demonstrates changing timezone "on the fly".
// Uses a pushbutton switch to change between the four continental US time zones.
// The current timezone setting is saved in EEPROM so it is remembered if
// the power is cycled.
// Tested with Arduino 1.8.5 and an Arduino Uno.
//
// Jack Christensen 02Jan2018
#include <avr/eeprom.h>
#include <JC_Button.h> // http://github.com/JChristensen/JC_Button
#include <Streaming.h> // http://arduiniana.org/libraries/streaming/
#include <Timezone.h> // http://github.com/JChristensen/Timezone
const uint8_t BUTTON_PIN(8); // connect a button from this pin to ground
Button btn(BUTTON_PIN);
uint8_t tzIndex; //index to the arrays below
EEMEM uint8_t ee_tzIndex; //copy of tzIndex persisted in EEPROM
const char* dstNames[] = {"EDT", "CDT", "MDT", "PDT"};
const char* stdNames[] = {"EST", "CST", "MST", "PST"};
const int dstOffsets[] = {-240, -300, -360, -420};
const int stdOffsets[] = {-300, -360, -420, -480};
TimeChangeRule dstRule = {"EDT", Second, Sun, Mar, 2, -240};
TimeChangeRule stdRule = {"EST", First, Sun, Nov, 2, -300};
Timezone tz(dstRule, stdRule);
void setup()
{
// set the system time to UTC
// warning: assumes that compileTime() returns US EST
// adjust the following line accordingly if you're in another time zone
setTime(compileTime() + 300 * 60);
// get tzIndex from eeprom and ensure that it's valid
tzIndex = eeprom_read_byte( &ee_tzIndex );
if ( tzIndex >= sizeof(stdOffsets) / sizeof(stdOffsets[0]) )
{
tzIndex = 0;
eeprom_write_byte( &ee_tzIndex, tzIndex);
}
btn.begin();
Serial.begin(115200);
changeTZ();
}
void loop()
{
// print the time if it's changed
static time_t tLast;
time_t t = now();
if (t != tLast)
{
tLast = t;
printDateTime(t);
Serial << " UTC ";
TimeChangeRule* tcr; //pointer to current time change rule, used to get TZ abbrev
printDateTime(tz.toLocal(t, &tcr));
Serial << " " << tcr -> abbrev;
Serial << endl;
}
// change the time zone if button pressed
btn.read();
if (btn.wasPressed())
{
if ( ++tzIndex >= sizeof(stdOffsets) / sizeof(stdOffsets[0]) ) tzIndex = 0;
changeTZ();
}
}
void changeTZ()
{
Serial << "tzIndex " << tzIndex << endl;
eeprom_update_byte( &ee_tzIndex, tzIndex );
dstRule.offset = dstOffsets[tzIndex];
stdRule.offset = stdOffsets[tzIndex];
strcpy(dstRule.abbrev, dstNames[tzIndex]);
strcpy(stdRule.abbrev, stdNames[tzIndex]);
tz.setRules(dstRule, stdRule);
}
void printDateTime(time_t t)
{
Serial << ((day(t)<10) ? "0" : "") << _DEC(day(t));
Serial << monthShortStr(month(t)) << _DEC(year(t)) << ' ';
Serial << ((hour(t)<10) ? "0" : "") << _DEC(hour(t)) << ':';
Serial << ((minute(t)<10) ? "0" : "") << _DEC(minute(t)) << ':';
Serial << ((second(t)<10) ? "0" : "") << _DEC(second(t));
}
// function to return the compile date and time as a time_t value
time_t compileTime()
{
const time_t FUDGE(10); //fudge factor to allow for upload time, etc. (seconds, YMMV)
const char *compDate = __DATE__, *compTime = __TIME__, *months = "JanFebMarAprMayJunJulAugSepOctNovDec";
char compMon[4], *m;
strncpy(compMon, compDate, 3);
compMon[3] = '\0';
m = strstr(months, compMon);
tmElements_t tm;
tm.Month = ((m - months) / 3 + 1);
tm.Day = atoi(compDate + 4);
tm.Year = atoi(compDate + 7) - 1970;
tm.Hour = atoi(compTime);
tm.Minute = atoi(compTime + 3);
tm.Second = atoi(compTime + 6);
time_t t = makeTime(tm);
return t + FUDGE; //add fudge factor to allow for compile time
}

View File

@@ -0,0 +1,105 @@
// Arduino Timezone Library Copyright (C) 2018 by Jack Christensen and
// licensed under GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html
//
// Arduino Timezone Library example sketch.
// Demonstrates changing time zones using an array of Timezone objects.
// Uses a pushbutton switch to change between the four US continental time zones.
// Tested with Arduino 1.8.5 and an Arduino Uno.
//
// Jack Christensen 02Jan2018
#include <JC_Button.h> // http://github.com/JChristensen/JC_Button
#include <Streaming.h> // http://arduiniana.org/libraries/streaming/
#include <Timezone.h> // http://github.com/JChristensen/Timezone
const uint8_t BUTTON_PIN(8); // connect a button from this pin to ground
Button btn(BUTTON_PIN);
//Continental US Time Zones
TimeChangeRule EDT = { "EDT", Second, Sun, Mar, 2, -240 }; //Daylight time = UTC - 4 hours
TimeChangeRule EST = { "EST", First, Sun, Nov, 2, -300 }; //Standard time = UTC - 5 hours
Timezone Eastern(EDT, EST);
TimeChangeRule CDT = { "CDT", Second, Sun, Mar, 2, -300 }; //Daylight time = UTC - 5 hours
TimeChangeRule CST = { "CST", First, Sun, Nov, 2, -360 }; //Standard time = UTC - 6 hours
Timezone Central(CDT, CST);
TimeChangeRule MDT = { "MDT", Second, Sun, Mar, 2, -360 }; //Daylight time = UTC - 6 hours
TimeChangeRule MST = { "MST", First, Sun, Nov, 2, -420 }; //Standard time = UTC - 7 hours
Timezone Mountain(MDT, MST);
TimeChangeRule PDT = { "PDT", Second, Sun, Mar, 2, -420 }; //Daylight time = UTC - 7 hours
TimeChangeRule PST = { "PST", First, Sun, Nov, 2, -480 }; //Standard time = UTC - 8 hours
Timezone Pacific(PDT, PST);
Timezone* timezones[] = { &Eastern, &Central, &Mountain, &Pacific };
Timezone* tz; //pointer to the time zone
uint8_t tzIndex; //indexes the timezones[] array
TimeChangeRule* tcr; //pointer to the time change rule, use to get TZ abbrev
void setup()
{
// set the system time to UTC
// warning: assumes that compileTime() returns US EST
// adjust the following line accordingly if you're in another time zone
setTime(compileTime() + 300 * 60);
btn.begin();
Serial.begin(115200);
tz = timezones[tzIndex];
}
void loop()
{
// print the time if it's changed
static time_t tLast;
time_t t = now();
if (t != tLast)
{
tLast = t;
printDateTime(t);
Serial << " UTC ";
TimeChangeRule* tcr; //pointer to current time change rule, used to get TZ abbrev
printDateTime((*tz).toLocal(t, &tcr));
Serial << " " << tcr -> abbrev;
Serial << endl;
}
// change the time zone if button pressed
btn.read();
if (btn.wasPressed())
{
if ( ++tzIndex >= sizeof(timezones) / sizeof(timezones[0]) ) tzIndex = 0;
Serial << "tzIndex " << tzIndex << endl;
tz = timezones[tzIndex];
}
}
void printDateTime(time_t t)
{
Serial << ((day(t)<10) ? "0" : "") << _DEC(day(t));
Serial << monthShortStr(month(t)) << _DEC(year(t)) << ' ';
Serial << ((hour(t)<10) ? "0" : "") << _DEC(hour(t)) << ':';
Serial << ((minute(t)<10) ? "0" : "") << _DEC(minute(t)) << ':';
Serial << ((second(t)<10) ? "0" : "") << _DEC(second(t));
}
// function to return the compile date and time as a time_t value
time_t compileTime()
{
const time_t FUDGE(10); //fudge factor to allow for upload time, etc. (seconds, YMMV)
const char *compDate = __DATE__, *compTime = __TIME__, *months = "JanFebMarAprMayJunJulAugSepOctNovDec";
char compMon[4], *m;
strncpy(compMon, compDate, 3);
compMon[3] = '\0';
m = strstr(months, compMon);
tmElements_t tm;
tm.Month = ((m - months) / 3 + 1);
tm.Day = atoi(compDate + 4);
tm.Year = atoi(compDate + 7) - 1970;
tm.Hour = atoi(compTime);
tm.Minute = atoi(compTime + 3);
tm.Second = atoi(compTime + 6);
time_t t = makeTime(tm);
return t + FUDGE; //add fudge factor to allow for compile time
}

View File

@@ -0,0 +1,71 @@
// Arduino Timezone Library Copyright (C) 2018 by Jack Christensen and
// licensed under GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html
//
// Arduino Timezone Library example sketch.
// Self-adjusting clock for one time zone.
// TimeChangeRules can be hard-coded or read from EEPROM, see comments.
// Jack Christensen Mar 2012
#include <Timezone.h> // https://github.com/JChristensen/Timezone
// US Eastern Time Zone (New York, Detroit)
TimeChangeRule myDST = {"EDT", Second, Sun, Mar, 2, -240}; // Daylight time = UTC - 4 hours
TimeChangeRule mySTD = {"EST", First, Sun, Nov, 2, -300}; // Standard time = UTC - 5 hours
Timezone myTZ(myDST, mySTD);
// If TimeChangeRules are already stored in EEPROM, comment out the three
// lines above and uncomment the line below.
//Timezone myTZ(100); // assumes rules stored at EEPROM address 100
TimeChangeRule *tcr; // pointer to the time change rule, use to get TZ abbrev
void setup()
{
Serial.begin(115200);
setTime(myTZ.toUTC(compileTime()));
//setTime(01, 55, 00, 11, 3, 2012); //another way to set the time (hr,min,sec,day,mnth,yr)
}
void loop()
{
time_t utc = now();
time_t local = myTZ.toLocal(utc, &tcr);
Serial.println();
printDateTime(utc, "UTC");
printDateTime(local, tcr -> abbrev);
delay(10000);
}
// Function to return the compile date and time as a time_t value
time_t compileTime()
{
const time_t FUDGE(10); // fudge factor to allow for compile time (seconds, YMMV)
const char *compDate = __DATE__, *compTime = __TIME__, *months = "JanFebMarAprMayJunJulAugSepOctNovDec";
char chMon[4], *m;
tmElements_t tm;
strncpy(chMon, compDate, 3);
chMon[3] = '\0';
m = strstr(months, chMon);
tm.Month = ((m - months) / 3 + 1);
tm.Day = atoi(compDate + 4);
tm.Year = atoi(compDate + 7) - 1970;
tm.Hour = atoi(compTime);
tm.Minute = atoi(compTime + 3);
tm.Second = atoi(compTime + 6);
time_t t = makeTime(tm);
return t + FUDGE; // add fudge factor to allow for compile time
}
// format and print a time_t value, with a time zone appended.
void printDateTime(time_t t, const char *tz)
{
char buf[32];
char m[4]; // temporary storage for month string (DateStrings.cpp uses shared buffer)
strcpy(m, monthShortStr(month(t)));
sprintf(buf, "%.2d:%.2d:%.2d %s %.2d %s %d %s",
hour(t), minute(t), second(t), dayShortStr(weekday(t)), day(t), m, year(t), tz);
Serial.println(buf);
}

View File

@@ -0,0 +1,57 @@
// Arduino Timezone Library Copyright (C) 2018 by Jack Christensen and
// licensed under GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html
//
// Arduino Timezone Library example sketch.
// Self-adjusting clock for one time zone using an external real-time
// clock, either a DS1307 or DS3231 (e.g. Chronodot).
// Assumes the RTC is set to UTC.
// TimeChangeRules can be hard-coded or read from EEPROM, see comments.
// Check out the Chronodot at http://www.macetech.com/store/
//
// Jack Christensen Aug 2012
#include <DS1307RTC.h> // https://github.com/PaulStoffregen/DS1307RTC
#include <Timezone.h> // https://github.com/JChristensen/Timezone
// US Eastern Time Zone (New York, Detroit)
TimeChangeRule myDST = {"EDT", Second, Sun, Mar, 2, -240}; //Daylight time = UTC - 4 hours
TimeChangeRule mySTD = {"EST", First, Sun, Nov, 2, -300}; //Standard time = UTC - 5 hours
Timezone myTZ(myDST, mySTD);
// If TimeChangeRules are already stored in EEPROM, comment out the three
// lines above and uncomment the line below.
//Timezone myTZ(100); //assumes rules stored at EEPROM address 100
TimeChangeRule *tcr; //pointer to the time change rule, use to get TZ abbrev
void setup()
{
Serial.begin(115200);
setSyncProvider(RTC.get); // the function to get the time from the RTC
if(timeStatus()!= timeSet)
Serial.println("Unable to sync with the RTC");
else
Serial.println("RTC has set the system time");
}
void loop()
{
time_t utc = now();
time_t local = myTZ.toLocal(utc, &tcr);
Serial.println();
printDateTime(utc, "UTC");
printDateTime(local, tcr -> abbrev);
delay(10000);
}
// format and print a time_t value, with a time zone appended.
void printDateTime(time_t t, const char *tz)
{
char buf[32];
char m[4]; // temporary storage for month string (DateStrings.cpp uses shared buffer)
strcpy(m, monthShortStr(month(t)));
sprintf(buf, "%.2d:%.2d:%.2d %s %.2d %s %d %s",
hour(t), minute(t), second(t), dayShortStr(weekday(t)), day(t), m, year(t), tz);
Serial.println(buf);
}

View File

@@ -0,0 +1,123 @@
// Arduino Timezone Library Copyright (C) 2018 by Jack Christensen and
// licensed under GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html
//
// Arduino Timezone Library example sketch.
// Self-adjusting clock for multiple time zones.
// Jack Christensen Mar 2012
//
// For time zone information:
// http://www.timeanddate.com/worldclock/
#include <Timezone.h> // https://github.com/JChristensen/Timezone
// Australia Eastern Time Zone (Sydney, Melbourne)
TimeChangeRule aEDT = {"AEDT", First, Sun, Oct, 2, 660}; // UTC + 11 hours
TimeChangeRule aEST = {"AEST", First, Sun, Apr, 3, 600}; // UTC + 10 hours
Timezone ausET(aEDT, aEST);
// Moscow Standard Time (MSK, does not observe DST)
TimeChangeRule msk = {"MSK", Last, Sun, Mar, 1, 180};
Timezone tzMSK(msk);
// Central European Time (Frankfurt, Paris)
TimeChangeRule CEST = {"CEST", Last, Sun, Mar, 2, 120}; // Central European Summer Time
TimeChangeRule CET = {"CET ", Last, Sun, Oct, 3, 60}; // Central European Standard Time
Timezone CE(CEST, CET);
// United Kingdom (London, Belfast)
TimeChangeRule BST = {"BST", Last, Sun, Mar, 1, 60}; // British Summer Time
TimeChangeRule GMT = {"GMT", Last, Sun, Oct, 2, 0}; // Standard Time
Timezone UK(BST, GMT);
// UTC
TimeChangeRule utcRule = {"UTC", Last, Sun, Mar, 1, 0}; // UTC
Timezone UTC(utcRule);
// US Eastern Time Zone (New York, Detroit)
TimeChangeRule usEDT = {"EDT", Second, Sun, Mar, 2, -240}; // Eastern Daylight Time = UTC - 4 hours
TimeChangeRule usEST = {"EST", First, Sun, Nov, 2, -300}; // Eastern Standard Time = UTC - 5 hours
Timezone usET(usEDT, usEST);
// US Central Time Zone (Chicago, Houston)
TimeChangeRule usCDT = {"CDT", Second, Sun, Mar, 2, -300};
TimeChangeRule usCST = {"CST", First, Sun, Nov, 2, -360};
Timezone usCT(usCDT, usCST);
// US Mountain Time Zone (Denver, Salt Lake City)
TimeChangeRule usMDT = {"MDT", Second, Sun, Mar, 2, -360};
TimeChangeRule usMST = {"MST", First, Sun, Nov, 2, -420};
Timezone usMT(usMDT, usMST);
// Arizona is US Mountain Time Zone but does not use DST
Timezone usAZ(usMST);
// US Pacific Time Zone (Las Vegas, Los Angeles)
TimeChangeRule usPDT = {"PDT", Second, Sun, Mar, 2, -420};
TimeChangeRule usPST = {"PST", First, Sun, Nov, 2, -480};
Timezone usPT(usPDT, usPST);
void setup()
{
Serial.begin(115200);
// set the system time to UTC
// warning: assumes that compileTime() returns US EDT
// adjust the following line accordingly if you're in another time zone
setTime(compileTime() + 240 * 60);
}
void loop()
{
time_t utc = now();
Serial.println();
printDateTime(ausET, utc, "Sydney");
printDateTime(tzMSK, utc, " Moscow");
printDateTime(CE, utc, "Paris");
printDateTime(UK, utc, " London");
printDateTime(UTC, utc, " Universal Coordinated Time");
printDateTime(usET, utc, " New York");
printDateTime(usCT, utc, " Chicago");
printDateTime(usMT, utc, " Denver");
printDateTime(usAZ, utc, " Phoenix");
printDateTime(usPT, utc, " Los Angeles");
delay(10000);
}
// Function to return the compile date and time as a time_t value
time_t compileTime()
{
const time_t FUDGE(10); // fudge factor to allow for compile time (seconds, YMMV)
const char *compDate = __DATE__, *compTime = __TIME__, *months = "JanFebMarAprMayJunJulAugSepOctNovDec";
char chMon[4], *m;
tmElements_t tm;
strncpy(chMon, compDate, 3);
chMon[3] = '\0';
m = strstr(months, chMon);
tm.Month = ((m - months) / 3 + 1);
tm.Day = atoi(compDate + 4);
tm.Year = atoi(compDate + 7) - 1970;
tm.Hour = atoi(compTime);
tm.Minute = atoi(compTime + 3);
tm.Second = atoi(compTime + 6);
time_t t = makeTime(tm);
return t + FUDGE; // add fudge factor to allow for compile time
}
// given a Timezone object, UTC and a string description, convert and print local time with time zone
void printDateTime(Timezone tz, time_t utc, const char *descr)
{
char buf[40];
char m[4]; // temporary storage for month string (DateStrings.cpp uses shared buffer)
TimeChangeRule *tcr; // pointer to the time change rule, use to get the TZ abbrev
time_t t = tz.toLocal(utc, &tcr);
strcpy(m, monthShortStr(month(t)));
sprintf(buf, "%.2d:%.2d:%.2d %s %.2d %s %d %s",
hour(t), minute(t), second(t), dayShortStr(weekday(t)), day(t), m, year(t), tcr -> abbrev);
Serial.print(buf);
Serial.print(' ');
Serial.println(descr);
}

View File

@@ -0,0 +1,29 @@
// Arduino Timezone Library Copyright (C) 2018 by Jack Christensen and
// licensed under GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html
//
// Arduino Timezone Library example sketch.
// Write TimeChangeRules to EEPROM.
// Jack Christensen Mar 2012
#include <Timezone.h> // https://github.com/JChristensen/Timezone
// US Eastern Time Zone (New York, Detroit)
TimeChangeRule usEdt = {"EDT", Second, Sun, Mar, 2, -240}; // UTC - 4 hours
TimeChangeRule usEst = {"EST", First, Sun, Nov, 2, -300}; // UTC - 5 hours
Timezone usEastern(usEdt, usEst);
void setup()
{
pinMode(13, OUTPUT);
usEastern.writeRules(100); // write rules to EEPROM address 100
}
void loop()
{
// fast blink to indicate EEPROM write is complete
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
}

View File

@@ -0,0 +1,85 @@
// Arduino Timezone Library Copyright (C) 2018 by Jack Christensen and
// licensed under GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html
//
// Arduino Timezone Library example sketch.
// Sketch to verify operation of Timezone library.
// Jack Christensen 14Nov2018
#include <Timezone.h> // https://github.com/JChristensen/Timezone
#include <TimeLib.h> // https://github.com/PaulStoffregen/Time
// New Zealand Time Zone
TimeChangeRule nzSTD = {"NZST", First, Sun, Apr, 3, 720}; // UTC + 12 hours
TimeChangeRule nzDST = {"NZDT", Last, Sun, Sep, 2, 780}; // UTC + 13 hours
Timezone nz(nzDST, nzSTD);
// US Eastern Time Zone (New York, Detroit)
TimeChangeRule etDST = {"EDT", Second, Sun, Mar, 2, -240}; // Daylight time = UTC - 4 hours
TimeChangeRule etSTD = {"EST", First, Sun, Nov, 2, -300}; // Standard time = UTC - 5 hours
Timezone et(etDST, etSTD);
void setup()
{
Serial.begin(115200);
// New Zealand
printTimes( 1, 4, 2018, nzSTD.hour, nzDST.offset, nz); // day, month, year, hour, offset, tz
printTimes(30, 9, 2018, nzDST.hour, nzSTD.offset, nz);
printTimes( 7, 4, 2019, nzSTD.hour, nzDST.offset, nz);
printTimes(29, 9, 2019, nzDST.hour, nzSTD.offset, nz);
printTimes( 5, 4, 2020, nzSTD.hour, nzDST.offset, nz);
printTimes(27, 9, 2020, nzDST.hour, nzSTD.offset, nz);
// US Eastern
printTimes(11, 3, 2018, etDST.hour, etSTD.offset, et); // day, month, year, hour, offset, tz
printTimes( 4, 11, 2018, etSTD.hour, etDST.offset, et);
printTimes(10, 3, 2019, etDST.hour, etSTD.offset, et);
printTimes( 3, 11, 2019, etSTD.hour, etDST.offset, et);
printTimes( 8, 3, 2020, etDST.hour, etSTD.offset, et);
printTimes( 1, 11, 2020, etSTD.hour, etDST.offset, et);
}
void loop() {}
// print corresponding UTC and local times "n" seconds before and after the time change.
// h is the hour to change the clock using the *current* time (i.e. before the change).
// offset is the utc offset in minutes for the time *after* the change.
void printTimes(uint8_t d, uint8_t m, int y, uint8_t h, int offset, Timezone tz)
{
const time_t n(3); // number of times to print before and after the time change
tmElements_t tm;
tm.Hour = h;
tm.Minute = 0;
tm.Second = 0;
tm.Day = d;
tm.Month = m;
tm.Year = y - 1970; // offset from 1970
time_t utc = makeTime(tm) - offset * SECS_PER_MIN - n;
Serial.print(F("\n-------- "));
Serial.print(monthShortStr(m));
Serial.print('-');
Serial.print(y);
Serial.print(F(" time change --------\n"));
for (uint16_t i=0; i<n*2; i++)
{
TimeChangeRule *tcr; // pointer to the time change rule, use to get TZ abbrev
time_t local = tz.toLocal(utc, &tcr);
printDateTime(utc, "UTC = ");
printDateTime(local, tcr -> abbrev);
Serial.println();
++utc;
}
}
// format and print a time_t value, with a time zone appended.
void printDateTime(time_t t, const char *tz)
{
char buf[32];
char m[4]; // temporary storage for month string (DateStrings.cpp uses shared buffer)
strcpy(m, monthShortStr(month(t)));
sprintf(buf, "%.2d:%.2d:%.2d %s %.2d %s %d %s",
hour(t), minute(t), second(t), dayShortStr(weekday(t)), day(t), m, year(t), tz);
Serial.print(buf);
}

View File

@@ -0,0 +1,9 @@
TimeChangeRule KEYWORD1
Timezone KEYWORD1
toLocal KEYWORD2
toUTC KEYWORD2
utcIsDST KEYWORD2
locIsDST KEYWORD2
setRules KEYWORD2
readRules KEYWORD2
writeRules KEYWORD2

View File

@@ -0,0 +1,10 @@
name=Timezone
version=1.2.4
author=Jack Christensen <jack.christensen@outlook.com>
maintainer=Jack Christensen <jack.christensen@outlook.com>
sentence=Arduino library to facilitate time zone conversions and automatic daylight saving (summer) time adjustments.
paragraph=The primary aim of the Timezone library is to convert Universal Coordinated Time (UTC) to the correct local time, whether it is daylight saving time (a.k.a. summer time) or standard time.
category=Timing
url=https://github.com/JChristensen/Timezone
architectures=*
depends=Time

View File

@@ -0,0 +1,243 @@
/*----------------------------------------------------------------------*
* Arduino Timezone Library *
* Jack Christensen Mar 2012 *
* *
* Arduino Timezone Library Copyright (C) 2018 by Jack Christensen and *
* licensed under GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html *
*----------------------------------------------------------------------*/
#include "Timezone.h"
#ifdef __AVR__
#include <avr/eeprom.h>
#endif
/*----------------------------------------------------------------------*
* Create a Timezone object from the given time change rules. *
*----------------------------------------------------------------------*/
Timezone::Timezone(TimeChangeRule dstStart, TimeChangeRule stdStart)
: m_dst(dstStart), m_std(stdStart)
{
initTimeChanges();
}
/*----------------------------------------------------------------------*
* Create a Timezone object for a zone that does not observe *
* daylight time. *
*----------------------------------------------------------------------*/
Timezone::Timezone(TimeChangeRule stdTime)
: m_dst(stdTime), m_std(stdTime)
{
initTimeChanges();
}
#ifdef __AVR__
/*----------------------------------------------------------------------*
* Create a Timezone object from time change rules stored in EEPROM *
* at the given address. *
*----------------------------------------------------------------------*/
Timezone::Timezone(int address)
{
readRules(address);
}
#endif
/*----------------------------------------------------------------------*
* Convert the given UTC time to local time, standard or *
* daylight time, as appropriate. *
*----------------------------------------------------------------------*/
time_t Timezone::toLocal(time_t utc)
{
// recalculate the time change points if needed
if (year(utc) != year(m_dstUTC)) calcTimeChanges(year(utc));
if (utcIsDST(utc))
return utc + m_dst.offset * SECS_PER_MIN;
else
return utc + m_std.offset * SECS_PER_MIN;
}
/*----------------------------------------------------------------------*
* Convert the given UTC time to local time, standard or *
* daylight time, as appropriate, and return a pointer to the time *
* change rule used to do the conversion. The caller must take care *
* not to alter this rule. *
*----------------------------------------------------------------------*/
time_t Timezone::toLocal(time_t utc, TimeChangeRule **tcr)
{
// recalculate the time change points if needed
if (year(utc) != year(m_dstUTC)) calcTimeChanges(year(utc));
if (utcIsDST(utc)) {
*tcr = &m_dst;
return utc + m_dst.offset * SECS_PER_MIN;
}
else {
*tcr = &m_std;
return utc + m_std.offset * SECS_PER_MIN;
}
}
/*----------------------------------------------------------------------*
* Convert the given local time to UTC time. *
* *
* WARNING: *
* This function is provided for completeness, but should seldom be *
* needed and should be used sparingly and carefully. *
* *
* Ambiguous situations occur after the Standard-to-DST and the *
* DST-to-Standard time transitions. When changing to DST, there is *
* one hour of local time that does not exist, since the clock moves *
* forward one hour. Similarly, when changing to standard time, there *
* is one hour of local times that occur twice since the clock moves *
* back one hour. *
* *
* This function does not test whether it is passed an erroneous time *
* value during the Local -> DST transition that does not exist. *
* If passed such a time, an incorrect UTC time value will be returned. *
* *
* If passed a local time value during the DST -> Local transition *
* that occurs twice, it will be treated as the earlier time, i.e. *
* the time that occurs before the transistion. *
* *
* Calling this function with local times during a transition interval *
* should be avoided! *
*----------------------------------------------------------------------*/
time_t Timezone::toUTC(time_t local)
{
// recalculate the time change points if needed
if (year(local) != year(m_dstLoc)) calcTimeChanges(year(local));
if (locIsDST(local))
return local - m_dst.offset * SECS_PER_MIN;
else
return local - m_std.offset * SECS_PER_MIN;
}
/*----------------------------------------------------------------------*
* Determine whether the given UTC time_t is within the DST interval *
* or the Standard time interval. *
*----------------------------------------------------------------------*/
bool Timezone::utcIsDST(time_t utc)
{
// recalculate the time change points if needed
if (year(utc) != year(m_dstUTC)) calcTimeChanges(year(utc));
if (m_stdUTC == m_dstUTC) // daylight time not observed in this tz
return false;
else if (m_stdUTC > m_dstUTC) // northern hemisphere
return (utc >= m_dstUTC && utc < m_stdUTC);
else // southern hemisphere
return !(utc >= m_stdUTC && utc < m_dstUTC);
}
/*----------------------------------------------------------------------*
* Determine whether the given Local time_t is within the DST interval *
* or the Standard time interval. *
*----------------------------------------------------------------------*/
bool Timezone::locIsDST(time_t local)
{
// recalculate the time change points if needed
if (year(local) != year(m_dstLoc)) calcTimeChanges(year(local));
if (m_stdUTC == m_dstUTC) // daylight time not observed in this tz
return false;
else if (m_stdLoc > m_dstLoc) // northern hemisphere
return (local >= m_dstLoc && local < m_stdLoc);
else // southern hemisphere
return !(local >= m_stdLoc && local < m_dstLoc);
}
/*----------------------------------------------------------------------*
* Calculate the DST and standard time change points for the given *
* given year as local and UTC time_t values. *
*----------------------------------------------------------------------*/
void Timezone::calcTimeChanges(int yr)
{
m_dstLoc = toTime_t(m_dst, yr);
m_stdLoc = toTime_t(m_std, yr);
m_dstUTC = m_dstLoc - m_std.offset * SECS_PER_MIN;
m_stdUTC = m_stdLoc - m_dst.offset * SECS_PER_MIN;
}
/*----------------------------------------------------------------------*
* Initialize the DST and standard time change points. *
*----------------------------------------------------------------------*/
void Timezone::initTimeChanges()
{
m_dstLoc = 0;
m_stdLoc = 0;
m_dstUTC = 0;
m_stdUTC = 0;
}
/*----------------------------------------------------------------------*
* Convert the given time change rule to a time_t value *
* for the given year. *
*----------------------------------------------------------------------*/
time_t Timezone::toTime_t(TimeChangeRule r, int yr)
{
uint8_t m = r.month; // temp copies of r.month and r.week
uint8_t w = r.week;
if (w == 0) // is this a "Last week" rule?
{
if (++m > 12) // yes, for "Last", go to the next month
{
m = 1;
++yr;
}
w = 1; // and treat as first week of next month, subtract 7 days later
}
// calculate first day of the month, or for "Last" rules, first day of the next month
tmElements_t tm;
tm.Hour = r.hour;
tm.Minute = 0;
tm.Second = 0;
tm.Day = 1;
tm.Month = m;
tm.Year = yr - 1970;
time_t t = makeTime(tm);
// add offset from the first of the month to r.dow, and offset for the given week
t += ( (r.dow - weekday(t) + 7) % 7 + (w - 1) * 7 ) * SECS_PER_DAY;
// back up a week if this is a "Last" rule
if (r.week == 0) t -= 7 * SECS_PER_DAY;
return t;
}
/*----------------------------------------------------------------------*
* Read or update the daylight and standard time rules from RAM. *
*----------------------------------------------------------------------*/
void Timezone::setRules(TimeChangeRule dstStart, TimeChangeRule stdStart)
{
m_dst = dstStart;
m_std = stdStart;
initTimeChanges(); // force calcTimeChanges() at next conversion call
}
#ifdef __AVR__
/*----------------------------------------------------------------------*
* Read the daylight and standard time rules from EEPROM at *
* the given address. *
*----------------------------------------------------------------------*/
void Timezone::readRules(int address)
{
eeprom_read_block((void *) &m_dst, (void *) address, sizeof(m_dst));
address += sizeof(m_dst);
eeprom_read_block((void *) &m_std, (void *) address, sizeof(m_std));
initTimeChanges(); // force calcTimeChanges() at next conversion call
}
/*----------------------------------------------------------------------*
* Write the daylight and standard time rules to EEPROM at *
* the given address. *
*----------------------------------------------------------------------*/
void Timezone::writeRules(int address)
{
eeprom_write_block((void *) &m_dst, (void *) address, sizeof(m_dst));
address += sizeof(m_dst);
eeprom_write_block((void *) &m_std, (void *) address, sizeof(m_std));
}
#endif

View File

@@ -0,0 +1,61 @@
/*----------------------------------------------------------------------*
* Arduino Timezone Library *
* Jack Christensen Mar 2012 *
* *
* Arduino Timezone Library Copyright (C) 2018 by Jack Christensen and *
* licensed under GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html *
*----------------------------------------------------------------------*/
#ifndef TIMEZONE_H_INCLUDED
#define TIMEZONE_H_INCLUDED
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#include <TimeLib.h> // https://github.com/PaulStoffregen/Time
// convenient constants for TimeChangeRules
enum week_t {Last, First, Second, Third, Fourth};
enum dow_t {Sun=1, Mon, Tue, Wed, Thu, Fri, Sat};
enum month_t {Jan=1, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
// structure to describe rules for when daylight/summer time begins,
// or when standard time begins.
struct TimeChangeRule
{
char abbrev[6]; // five chars max
uint8_t week; // First, Second, Third, Fourth, or Last week of the month
uint8_t dow; // day of week, 1=Sun, 2=Mon, ... 7=Sat
uint8_t month; // 1=Jan, 2=Feb, ... 12=Dec
uint8_t hour; // 0-23
int offset; // offset from UTC in minutes
};
class Timezone
{
public:
Timezone(TimeChangeRule dstStart, TimeChangeRule stdStart);
Timezone(TimeChangeRule stdTime);
Timezone(int address);
time_t toLocal(time_t utc);
time_t toLocal(time_t utc, TimeChangeRule **tcr);
time_t toUTC(time_t local);
bool utcIsDST(time_t utc);
bool locIsDST(time_t local);
void setRules(TimeChangeRule dstStart, TimeChangeRule stdStart);
void readRules(int address);
void writeRules(int address);
private:
void calcTimeChanges(int yr);
void initTimeChanges();
time_t toTime_t(TimeChangeRule r, int yr);
TimeChangeRule m_dst; // rule for start of dst or summer time for any year
TimeChangeRule m_std; // rule for start of standard time for any year
time_t m_dstUTC; // dst start for given/current year, given in UTC
time_t m_stdUTC; // std time start for given/current year, given in UTC
time_t m_dstLoc; // dst start for given/current year, given in local time
time_t m_stdLoc; // std time start for given/current year, given in local time
};
#endif

View File

@@ -9,6 +9,9 @@ lib_deps = ${common.lib_deps}
build_flags =
-D HW_ROARFRED=1
-D DEBUG_MODE=1
extra_scripts =
pre:scripts/addversion.py
scripts/makeweb.py
monitor_speed = 2400
monitor_flags =
--parity

View File

@@ -4,10 +4,10 @@ extra_configs = platformio-user.ini
[common]
framework = arduino
lib_deps = HanConfigAp@1.0.0, HanReader@1.0.0, HanToJson@1.0.0, ArduinoJson@^6.0.0, MQTT@^2.4.0, DallasTemperature@^3.8.0, EspSoftwareSerial@^6.7.1
lib_deps = HanReader@1.0.1, ArduinoJson@6.14.1, MQTT@2.4.7, DallasTemperature@3.8.1, EspSoftwareSerial@6.7.1, Base64@1.0.0, RemoteDebug@3.0.5
[env:hw1esp12e]
platform = espressif8266
platform = espressif8266@2.3.3
board = esp12e
framework = ${common.framework}
lib_deps = ${common.lib_deps}
@@ -18,7 +18,7 @@ extra_scripts =
scripts/makeweb.py
[env:esp12e]
platform = espressif8266
platform = espressif8266@2.3.3
board = esp12e
framework = ${common.framework}
lib_deps = ${common.lib_deps}
@@ -27,7 +27,7 @@ extra_scripts =
scripts/makeweb.py
[env:d1mini]
platform = espressif8266
platform = espressif8266@2.3.3
board = d1_mini
framework = ${common.framework}
lib_deps = ${common.lib_deps}
@@ -36,7 +36,7 @@ extra_scripts =
scripts/makeweb.py
[env:esp32]
platform = espressif32
platform = espressif32@1.11.2
board = esp32dev
framework = ${common.framework}
lib_deps = ${common.lib_deps}
@@ -45,7 +45,7 @@ extra_scripts =
scripts/makeweb.py
[env:lolind32]
platform = espressif32
platform = espressif32@1.11.2
board = lolin_d32
framework = ${common.framework}
lib_deps = ${common.lib_deps}
@@ -54,7 +54,7 @@ extra_scripts =
scripts/makeweb.py
[env:featheresp32]
platform = espressif32
platform = espressif32@1.11.2
board = featheresp32
framework = ${common.framework}
lib_deps = ${common.lib_deps}

View File

@@ -1,7 +1,7 @@
import os
FILENAME_VERSION_H = 'src/version.h'
version = os.environ.get('GITHUB_REF')
version = os.environ.get('GITHUB_TAG')
if version == None:
version = "SNAPSHOT"

799
src/AmsConfiguration.cpp Normal file
View File

@@ -0,0 +1,799 @@
#include "AmsConfiguration.h"
String AmsConfiguration::getWifiSsid() {
return wifiSsid;
}
void AmsConfiguration::setWifiSsid(String wifiSsid) {
wifiChanged |= this->wifiSsid != wifiSsid;
this->wifiSsid = String(wifiSsid);
}
String AmsConfiguration::getWifiPassword() {
return wifiPassword;
}
void AmsConfiguration::setWifiPassword(String wifiPassword) {
wifiChanged |= this->wifiPassword != wifiPassword;
this->wifiPassword = String(wifiPassword);
}
String AmsConfiguration::getWifiIp() {
return wifiIp;
}
void AmsConfiguration::setWifiIp(String wifiIp) {
wifiChanged |= this->wifiIp != wifiIp;
this->wifiIp = String(wifiIp);
}
String AmsConfiguration::getWifiGw() {
return wifiGw;
}
void AmsConfiguration::setWifiGw(String wifiGw) {
wifiChanged |= this->wifiGw != wifiGw;
this->wifiGw = String(wifiGw);
}
String AmsConfiguration::getWifiSubnet() {
return wifiSubnet;
}
void AmsConfiguration::setWifiSubnet(String wifiSubnet) {
wifiChanged |= this->wifiSubnet != wifiSubnet;
this->wifiSubnet = String(wifiSubnet);
}
String AmsConfiguration::getWifiDns1() {
return wifiDns1;
}
void AmsConfiguration::setWifiDns1(String wifiDns1) {
wifiChanged |= this->wifiDns1 != wifiDns1;
this->wifiDns1 = wifiDns1;
}
String AmsConfiguration::getWifiDns2() {
return wifiDns2;
}
void AmsConfiguration::setWifiDns2(String wifiDns2) {
wifiChanged |= this->wifiDns2 != wifiDns2;
this->wifiDns2 = wifiDns2;
}
String AmsConfiguration::getWifiHostname() {
return wifiHostname;
}
void AmsConfiguration::setWifiHostname(String wifiHostname) {
wifiChanged |= this->wifiHostname != wifiHostname;
this->wifiHostname = wifiHostname;
}
void AmsConfiguration::clearWifiIp() {
setWifiIp("");
setWifiGw("");
setWifiSubnet("");
setWifiDns1("");
setWifiDns2("");
}
bool AmsConfiguration::isWifiChanged() {
return wifiChanged;
}
void AmsConfiguration::ackWifiChange() {
wifiChanged = false;
}
String AmsConfiguration::getMqttHost() {
return mqttHost;
}
void AmsConfiguration::setMqttHost(String mqttHost) {
mqttChanged |= this->mqttHost != mqttHost;
this->mqttHost = String(mqttHost);
}
int AmsConfiguration::getMqttPort() {
return mqttPort;
}
void AmsConfiguration::setMqttPort(int mqttPort) {
mqttChanged |= this->mqttPort != mqttPort;
this->mqttPort = mqttPort;
}
String AmsConfiguration::getMqttClientId() {
return mqttClientId;
}
void AmsConfiguration::setMqttClientId(String mqttClientId) {
mqttChanged |= this->mqttClientId != mqttClientId;
this->mqttClientId = String(mqttClientId);
}
String AmsConfiguration::getMqttPublishTopic() {
return mqttPublishTopic;
}
void AmsConfiguration::setMqttPublishTopic(String mqttPublishTopic) {
mqttChanged |= this->mqttPublishTopic != mqttPublishTopic;
this->mqttPublishTopic = String(mqttPublishTopic);
}
String AmsConfiguration::getMqttSubscribeTopic() {
return mqttSubscribeTopic;
}
void AmsConfiguration::setMqttSubscribeTopic(String mqttSubscribeTopic) {
mqttChanged |= this->mqttSubscribeTopic != mqttSubscribeTopic;
this->mqttSubscribeTopic = String(mqttSubscribeTopic);
}
String AmsConfiguration::getMqttUser() {
return mqttUser;
}
void AmsConfiguration::setMqttUser(String mqttUser) {
mqttChanged |= this->mqttUser != mqttUser;
this->mqttUser = String(mqttUser);
}
String AmsConfiguration::getMqttPassword() {
return mqttPassword;
}
void AmsConfiguration::setMqttPassword(String mqttPassword) {
mqttChanged |= this->mqttPassword != mqttPassword;
this->mqttPassword = String(mqttPassword);
}
int AmsConfiguration::getMqttPayloadFormat() {
return this->mqttPayloadFormat;
}
void AmsConfiguration::setMqttPayloadFormat(int mqttPayloadFormat) {
this->mqttPayloadFormat = mqttPayloadFormat;
}
void AmsConfiguration::clearMqtt() {
setMqttHost("");
setMqttPort(1883);
setMqttClientId("");
setMqttPublishTopic("");
setMqttSubscribeTopic("");
setMqttUser("");
setMqttPassword("");
}
bool AmsConfiguration::isMqttChanged() {
return mqttChanged;
}
void AmsConfiguration::ackMqttChange() {
mqttChanged = false;
}
byte AmsConfiguration::getAuthSecurity() {
return authSecurity;
}
void AmsConfiguration::setAuthSecurity(byte authSecurity) {
this->authSecurity = authSecurity;
}
String AmsConfiguration::getAuthUser() {
return authUser;
}
void AmsConfiguration::setAuthUser(String authUser) {
this->authUser = String(authUser);
}
String AmsConfiguration::getAuthPassword() {
return authPassword;
}
void AmsConfiguration::setAuthPassword(String authPassword) {
this->authPassword = String(authPassword);
}
void AmsConfiguration::clearAuth() {
setAuthSecurity(0);
setAuthUser("");
setAuthPassword("");
}
int AmsConfiguration::getMeterType() {
return this->meterType;
}
void AmsConfiguration::setMeterType(int meterType) {
this->meterType = meterType;
}
int AmsConfiguration::getDistributionSystem() {
return this->distributionSystem;
}
void AmsConfiguration::setDistributionSystem(int distributionSystem) {
this->distributionSystem = distributionSystem;
}
int AmsConfiguration::getMainFuse() {
return this->mainFuse;
}
void AmsConfiguration::setMainFuse(int mainFuse) {
this->mainFuse = mainFuse;
}
int AmsConfiguration::getProductionCapacity() {
return this->productionCapacity;
}
void AmsConfiguration::setProductionCapacity(int productionCapacity) {
this->productionCapacity = productionCapacity;
}
bool AmsConfiguration::isDebugTelnet() {
return this->debugTelnet;
}
void AmsConfiguration::setDebugTelnet(bool debugTelnet) {
this->debugTelnet = debugTelnet;
}
bool AmsConfiguration::isDebugSerial() {
return this->debugSerial;
}
void AmsConfiguration::setDebugSerial(bool debugSerial) {
this->debugSerial = debugSerial;
}
int AmsConfiguration::getDebugLevel() {
return this->debugLevel;
}
void AmsConfiguration::setDebugLevel(int debugLevel) {
this->debugLevel = debugLevel;
}
bool AmsConfiguration::hasConfig() {
if(configVersion == 0) {
EEPROM.begin(EEPROM_SIZE);
configVersion = EEPROM.read(EEPROM_CONFIG_ADDRESS);
EEPROM.end();
}
switch(configVersion) {
case 71:
case 72:
case 75:
case 80:
case 81:
return true;
default:
configVersion = 0;
return false;
}
}
int AmsConfiguration::getConfigVersion() {
return configVersion;
}
bool AmsConfiguration::load() {
int address = EEPROM_CONFIG_ADDRESS;
bool success = false;
EEPROM.begin(EEPROM_SIZE);
int cs = EEPROM.read(address);
address++;
switch(cs) {
case 71: // Same as 72
case 72:
success = loadConfig72(address);
break;
case 75:
success = loadConfig75(address);
break;
case 80:
success = loadConfig80(address);
break;
case 81:
success = loadConfig81(address);
break;
}
EEPROM.end();
return success;
}
bool AmsConfiguration::loadConfig72(int address) {
char* temp;
address += readString(address, &temp);
setWifiSsid(temp);
address += readString(address, &temp);
setWifiPassword(temp);
byte b;
address += readByte(address, &b);
setMeterType(b);
address += readString(address, &temp);
setMqttHost(temp);
int port;
address += readInt(address, &port);
setMqttPort(port);
address += readString(address, &temp);
setMqttClientId(temp);
address += readString(address, &temp);
setMqttPublishTopic(temp);
address += readString(address, &temp);
setMqttSubscribeTopic(temp);
bool secure = false;
address += readBool(address, &secure);
if (secure) {
address += readString(address, &temp);
setMqttUser(temp);
address += readString(address, &temp);
setMqttPassword(temp);
} else {
setMqttUser("");
setMqttPassword("");
}
setMqttPayloadFormat(0);
clearAuth();
setWifiIp("");
setWifiGw("");
setWifiSubnet("");
setMainFuse(0);
setProductionCapacity(0);
setDistributionSystem(0);
ackWifiChange();
setDebugLevel(3); // 3=Info
setDebugTelnet(false);
setDebugSerial(false);
return true;
}
bool AmsConfiguration::loadConfig75(int address) {
char* temp;
address += readString(address, &temp);
setWifiSsid(temp);
address += readString(address, &temp);
setWifiPassword(temp);
byte b;
address += readByte(address, &b);
setMeterType(b);
bool mqtt = false;
address += readBool(address, &mqtt);
if(mqtt) {
address += readString(address, &temp);
setMqttHost(temp);
int port;
address += readInt(address, &port);
setMqttPort(port);
address += readString(address, &temp);
setMqttClientId(temp);
address += readString(address, &temp);
setMqttPublishTopic(temp);
address += readString(address, &temp);
setMqttSubscribeTopic(temp);
}
bool secure = false;
address += readBool(address, &secure);
if (secure) {
address += readString(address, &temp);
setMqttUser(temp);
address += readString(address, &temp);
setMqttPassword(temp);
} else {
setMqttUser("");
setMqttPassword("");
}
setMqttPayloadFormat(0);
address += readByte(address, &authSecurity);
if (authSecurity > 0) {
address += readString(address, &temp);
setAuthUser(temp);
address += readString(address, &temp);
setAuthPassword(temp);
} else {
clearAuth();
}
int i;
address += readInt(address, &i);
setMainFuse(i);
address += readByte(address, &b);
setDistributionSystem(b);
setWifiIp("");
setWifiGw("");
setWifiSubnet("");
setProductionCapacity(0);
ackWifiChange();
setDebugLevel(3); // 3=Info
setDebugTelnet(false);
setDebugSerial(false);
return true;
}
bool AmsConfiguration::loadConfig80(int address) {
char* temp;
address += readString(address, &temp);
setWifiSsid(temp);
address += readString(address, &temp);
setWifiPassword(temp);
address += readString(address, &temp);
setWifiIp(temp);
address += readString(address, &temp);
setWifiGw(temp);
address += readString(address, &temp);
setWifiSubnet(temp);
bool mqtt = false;
address += readBool(address, &mqtt);
if(mqtt) {
address += readString(address, &temp);
setMqttHost(temp);
int port;
address += readInt(address, &port);
setMqttPort(port);
address += readString(address, &temp);
setMqttClientId(temp);
address += readString(address, &temp);
setMqttPublishTopic(temp);
address += readString(address, &temp);
setMqttSubscribeTopic(temp);
bool secure = false;
address += readBool(address, &secure);
if (secure)
{
address += readString(address, &temp);
setMqttUser(temp);
address += readString(address, &temp);
setMqttPassword(temp);
} else {
setMqttUser("");
setMqttPassword("");
}
} else {
clearMqtt();
}
setMqttPayloadFormat(0);
address += readByte(address, &authSecurity);
if (authSecurity > 0) {
address += readString(address, &temp);
setAuthUser(temp);
address += readString(address, &temp);
setAuthPassword(temp);
} else {
clearAuth();
}
int i;
address += readInt(address, &i);
setMeterType(i);
address += readInt(address, &i);
setDistributionSystem(i);
address += readInt(address, &i);
setMainFuse(i);
address += readInt(address, &i);
setProductionCapacity(i);
ackWifiChange();
setDebugLevel(3); // 3=Info
setDebugTelnet(false);
setDebugSerial(false);
return true;
}
bool AmsConfiguration::loadConfig81(int address) {
char* temp;
address += readString(address, &temp);
setWifiSsid(temp);
address += readString(address, &temp);
setWifiPassword(temp);
bool staticIp = false;
address += readBool(address, &staticIp);
if(staticIp) {
address += readString(address, &temp);
setWifiIp(temp);
address += readString(address, &temp);
setWifiGw(temp);
address += readString(address, &temp);
setWifiSubnet(temp);
address += readString(address, &temp);
setWifiDns1(temp);
address += readString(address, &temp);
setWifiDns2(temp);
}
address += readString(address, &temp);
setWifiHostname(temp);
bool mqtt = false;
address += readBool(address, &mqtt);
if(mqtt) {
address += readString(address, &temp);
setMqttHost(temp);
int port;
address += readInt(address, &port);
setMqttPort(port);
address += readString(address, &temp);
setMqttClientId(temp);
address += readString(address, &temp);
setMqttPublishTopic(temp);
address += readString(address, &temp);
setMqttSubscribeTopic(temp);
bool secure = false;
address += readBool(address, &secure);
if (secure)
{
address += readString(address, &temp);
setMqttUser(temp);
address += readString(address, &temp);
setMqttPassword(temp);
} else {
setMqttUser("");
setMqttPassword("");
}
int payloadFormat;
address += readInt(address, &payloadFormat);
setMqttPayloadFormat(payloadFormat);
} else {
clearMqtt();
}
address += readByte(address, &authSecurity);
if (authSecurity > 0) {
address += readString(address, &temp);
setAuthUser(temp);
address += readString(address, &temp);
setAuthPassword(temp);
} else {
clearAuth();
}
int i;
address += readInt(address, &i);
setMeterType(i);
address += readInt(address, &i);
setDistributionSystem(i);
address += readInt(address, &i);
setMainFuse(i);
address += readInt(address, &i);
setProductionCapacity(i);
bool debugTelnet = false;
address += readBool(address, &debugTelnet);
setDebugTelnet(debugTelnet);
bool debugSerial = false;
address += readBool(address, &debugSerial);
setDebugSerial(debugSerial);
address += readInt(address, &i);
setDebugLevel(i);
ackWifiChange();
return true;
}
bool AmsConfiguration::save() {
int address = EEPROM_CONFIG_ADDRESS;
EEPROM.begin(EEPROM_SIZE);
EEPROM.put(address, EEPROM_CHECK_SUM);
address++;
address += saveString(address, wifiSsid.c_str());
address += saveString(address, wifiPassword.c_str());
if(!wifiIp.isEmpty()) {
address += saveBool(address, true);
address += saveString(address, wifiIp.c_str());
address += saveString(address, wifiGw.c_str());
address += saveString(address, wifiSubnet.c_str());
address += saveString(address, wifiDns1.c_str());
address += saveString(address, wifiDns2.c_str());
} else {
address += saveBool(address, false);
}
address += saveString(address, wifiHostname.c_str());
if(!mqttHost.isEmpty()) {
address += saveBool(address, true);
address += saveString(address, mqttHost.c_str());
address += saveInt(address, mqttPort);
address += saveString(address, mqttClientId.c_str());
address += saveString(address, mqttPublishTopic.c_str());
address += saveString(address, mqttSubscribeTopic.c_str());
if (!mqttUser.isEmpty()) {
address += saveBool(address, true);
address += saveString(address, mqttUser.c_str());
address += saveString(address, mqttPassword.c_str());
} else {
address += saveBool(address, false);
}
address += saveInt(address, mqttPayloadFormat);
} else {
address += saveBool(address, false);
}
address += saveByte(address, authSecurity);
if (authSecurity > 0) {
address += saveString(address, authUser.c_str());
address += saveString(address, authPassword.c_str());
}
address += saveInt(address, meterType);
address += saveInt(address, distributionSystem);
address += saveInt(address, mainFuse);
address += saveInt(address, productionCapacity);
address += saveBool(address, debugTelnet);
address += saveBool(address, debugSerial);
address += saveInt(address, debugLevel);
bool success = EEPROM.commit();
EEPROM.end();
configVersion = EEPROM_CHECK_SUM;
return success;
}
int AmsConfiguration::readString(int pAddress, char* pString[]) {
int address = 0;
byte length = EEPROM.read(pAddress + address);
address++;
char* buffer = new char[length];
for (int i = 0; i<length; i++)
{
buffer[i] = EEPROM.read(pAddress + address++);
}
*pString = buffer;
return address;
}
int AmsConfiguration::saveString(int pAddress, const char* pString) {
int address = 0;
int length = pString ? strlen(pString) + 1 : 0;
EEPROM.put(pAddress + address, length);
address++;
for (int i = 0; i < length; i++)
{
EEPROM.put(pAddress + address, pString[i]);
address++;
}
return address;
}
int AmsConfiguration::readInt(int address, int *value) {
int lower = EEPROM.read(address);
int higher = EEPROM.read(address + 1);
*value = lower + (higher << 8);
return 2;
}
int AmsConfiguration::saveInt(int address, int value) {
byte lowByte = value & 0xFF;
byte highByte = ((value >> 8) & 0xFF);
EEPROM.write(address, lowByte);
EEPROM.write(address + 1, highByte);
return 2;
}
int AmsConfiguration::readBool(int address, bool *value) {
byte y = EEPROM.read(address);
*value = (bool)y;
return 1;
}
int AmsConfiguration::saveBool(int address, bool value) {
byte y = (byte)value;
EEPROM.write(address, y);
return 1;
}
int AmsConfiguration::readByte(int address, byte *value) {
*value = EEPROM.read(address);
return 1;
}
int AmsConfiguration::saveByte(int address, byte value) {
EEPROM.write(address, value);
return 1;
}
template <class T> int AmsConfiguration::writeAnything(int ee, const T& value) {
const byte* p = (const byte*)(const void*)&value;
unsigned int i;
for (i = 0; i < sizeof(value); i++)
EEPROM.write(ee++, *p++);
return i;
}
template <class T> int AmsConfiguration::readAnything(int ee, T& value) {
byte* p = (byte*)(void*)&value;
unsigned int i;
for (i = 0; i < sizeof(value); i++)
*p++ = EEPROM.read(ee++);
return i;
}
void AmsConfiguration::print(Print* debugger)
{
debugger->println("Configuration:");
debugger->println("-----------------------------------------------");
debugger->printf("WiFi SSID: %s\r\n", this->getWifiSsid().c_str());
debugger->printf("WiFi Psk: %s\r\n", this->getWifiPassword().c_str());
if(!getWifiIp().isEmpty()) {
debugger->printf("IP: %s\r\n", this->getWifiIp().c_str());
debugger->printf("Gateway: %s\r\n", this->getWifiGw().c_str());
debugger->printf("Subnet: %s\r\n", this->getWifiSubnet().c_str());
debugger->printf("Primary DNS: %s\r\n", this->getWifiDns1().c_str());
debugger->printf("Secondary DNS: %s\r\n", this->getWifiDns2().c_str());
}
if(!getMqttHost().isEmpty()) {
debugger->printf("mqttHost: %s\r\n", this->getMqttHost().c_str());
debugger->printf("mqttPort: %i\r\n", this->getMqttPort());
debugger->printf("mqttClientID: %s\r\n", this->getMqttClientId().c_str());
debugger->printf("mqttPublishTopic: %s\r\n", this->getMqttPublishTopic().c_str());
debugger->printf("mqttSubscribeTopic: %s\r\n", this->getMqttSubscribeTopic().c_str());
if (this->getMqttUser()) {
debugger->printf("SECURE MQTT CONNECTION:\r\n");
debugger->printf("mqttUser: %s\r\n", this->getMqttUser().c_str());
debugger->printf("mqttPass: %s\r\n", this->getMqttPassword().c_str());
}
debugger->printf("payload format: %i\r\n", this->getMqttPayloadFormat());
}
if (this->getAuthSecurity()) {
debugger->printf("WEB AUTH:\r\n");
debugger->printf("authSecurity: %i\r\n", this->getAuthSecurity());
debugger->printf("authUser: %s\r\n", this->getAuthUser().c_str());
debugger->printf("authPass: %s\r\n", this->getAuthPassword().c_str());
}
debugger->printf("meterType: %i\r\n", this->getMeterType());
debugger->printf("distSys: %i\r\n", this->getDistributionSystem());
debugger->printf("fuseSize: %i\r\n", this->getMainFuse());
debugger->printf("productionCapacity: %i\r\n", this->getProductionCapacity());
debugger->println("-----------------------------------------------");
}

137
src/AmsConfiguration.h Normal file
View File

@@ -0,0 +1,137 @@
#ifndef _AMSCONFIGURATION_h
#define _AMSCONFIGURATION_h
#include <EEPROM.h>
#include "Arduino.h"
class AmsConfiguration {
public:
bool hasConfig();
int getConfigVersion();
bool load();
bool save();
String getWifiSsid();
void setWifiSsid(String wifiSsid);
String getWifiPassword();
void setWifiPassword(String wifiPassword);
String getWifiIp();
void setWifiIp(String wifiIp);
String getWifiGw();
void setWifiGw(String wifiGw);
String getWifiSubnet();
void setWifiSubnet(String wifiSubnet);
String getWifiDns1();
void setWifiDns1(String wifiDns1);
String getWifiDns2();
void setWifiDns2(String wifiDns1);
String getWifiHostname();
void setWifiHostname(String wifiHostname);
void clearWifiIp();
bool isWifiChanged();
void ackWifiChange();
String getMqttHost();
void setMqttHost(String mqttHost);
int getMqttPort();
void setMqttPort(int mqttPort);
String getMqttClientId();
void setMqttClientId(String mqttClientId);
String getMqttPublishTopic();
void setMqttPublishTopic(String mqttPublishTopic);
String getMqttSubscribeTopic();
void setMqttSubscribeTopic(String mqttSubscribeTopic);
String getMqttUser();
void setMqttUser(String mqttUser);
String getMqttPassword();
void setMqttPassword(String mqttPassword);
int getMqttPayloadFormat();
void setMqttPayloadFormat(int mqttPayloadFormat);
void clearMqtt();
bool isMqttChanged();
void ackMqttChange();
byte getAuthSecurity();
void setAuthSecurity(byte authSecurity);
String getAuthUser();
void setAuthUser(String authUser);
String getAuthPassword();
void setAuthPassword(String authPassword);
void clearAuth();
int getMeterType();
void setMeterType(int meterType);
int getDistributionSystem();
void setDistributionSystem(int distributionSystem);
int getMainFuse();
void setMainFuse(int mainFuse);
int getProductionCapacity();
void setProductionCapacity(int productionCapacity);
bool isDebugTelnet();
void setDebugTelnet(bool debugTelnet);
bool isDebugSerial();
void setDebugSerial(bool debugSerial);
int getDebugLevel();
void setDebugLevel(int debugLevel);
void print(Print* debugger);
protected:
private:
int configVersion = 0;
String wifiSsid;
String wifiPassword;
String wifiIp;
String wifiGw;
String wifiSubnet;
String wifiDns1;
String wifiDns2;
String wifiHostname;
bool wifiChanged = false;
String mqttHost;
int mqttPort = 1883;
String mqttClientId;
String mqttPublishTopic;
String mqttSubscribeTopic;
String mqttUser;
String mqttPassword;
int mqttPayloadFormat = 0;
bool mqttChanged = false;
byte authSecurity;
String authUser;
String authPassword;
int meterType = 0, distributionSystem = 0, mainFuse = 0, productionCapacity = 0;
bool debugTelnet = false, debugSerial = false;
int debugLevel = 3;
const int EEPROM_SIZE = 512;
const int EEPROM_CHECK_SUM = 81; // Used to check if config is stored. Change if structure changes
const int EEPROM_CONFIG_ADDRESS = 0;
bool loadConfig72(int address);
bool loadConfig75(int address);
bool loadConfig80(int address);
bool loadConfig81(int address);
int saveString(int pAddress, const char* pString);
int readString(int pAddress, char* pString[]);
int saveInt(int pAddress, int pValue);
int readInt(int pAddress, int *pValue);
int saveBool(int pAddress, bool pValue);
int readBool(int pAddress, bool *pValue);
int saveByte(int pAddress, byte pValue);
int readByte(int pAddress, byte *pValue);
template <class T> int writeAnything(int ee, const T& value);
template <class T> int readAnything(int ee, T& value);
};
#endif

349
src/AmsData.cpp Normal file
View File

@@ -0,0 +1,349 @@
#include "AmsData.h"
#include "Kaifa.h"
#include "Aidon.h"
#include "Kamstrup.h"
AmsData::AmsData() {}
AmsData::AmsData(int meterType, HanReader& hanReader) {
lastUpdateMillis = millis();
packageTimestamp = hanReader.getPackageTime();
int listSize = hanReader.getListSize();
switch(meterType) {
case METER_TYPE_KAIFA:
extractFromKaifa(hanReader, listSize);
break;
case METER_TYPE_AIDON:
extractFromAidon(hanReader, listSize);
break;
case METER_TYPE_KAMSTRUP:
extractFromKamstrup(hanReader, listSize);
break;
}
}
void AmsData::extractFromKaifa(HanReader& hanReader, int listSize) {
switch(listSize) {
case (int)Kaifa::List1:
listType = 1;
break;
case (int)Kaifa::List3PhaseShort:
threePhase = true;
case (int)Kaifa::List1PhaseShort:
listType = 2;
break;
case (int)Kaifa::List3PhaseLong:
threePhase = true;
case (int)Kaifa::List1PhaseLong:
listType = 3;
break;
}
if(listSize == (int)Kaifa::List1) {
activeImportPower = hanReader.getInt((int)Kaifa_List1::ActivePowerImported);
} else {
switch(listSize) {
case (int)Kaifa::List3PhaseLong:
meterTimestamp = hanReader.getTime( (int)Kaifa_List3Phase::MeterClock);
activeImportCounter = ((double) hanReader.getInt((int)Kaifa_List3Phase::CumulativeActiveImportEnergy)) / 1000;
activeExportCounter = ((double) hanReader.getInt((int)Kaifa_List3Phase::CumulativeActiveExportEnergy)) / 1000;
reactiveImportCounter = ((double) hanReader.getInt((int)Kaifa_List3Phase::CumulativeReactiveImportEnergy)) / 1000;
reactiveExportCounter = ((double) hanReader.getInt((int)Kaifa_List3Phase::CumulativeReactiveExportEnergy)) / 1000;
case (int)Kaifa::List3PhaseShort:
listId = hanReader.getString( (int)Kaifa_List3Phase::ListVersionIdentifier);
meterId = hanReader.getString( (int)Kaifa_List3Phase::MeterID);
meterType = hanReader.getString( (int)Kaifa_List3Phase::MeterType);
activeImportPower = hanReader.getInt( (int)Kaifa_List3Phase::ActiveImportPower);
reactiveImportPower = hanReader.getInt( (int)Kaifa_List3Phase::ReactiveImportPower);
activeExportPower = hanReader.getInt( (int)Kaifa_List3Phase::ActiveExportPower);
reactiveExportPower = hanReader.getInt( (int)Kaifa_List3Phase::ReactiveExportPower);
l1current = ((double) hanReader.getInt((int)Kaifa_List3Phase::CurrentL1)) / 1000;
l2current = ((double) hanReader.getInt((int)Kaifa_List3Phase::CurrentL2)) / 1000;
l3current = ((double) hanReader.getInt((int)Kaifa_List3Phase::CurrentL3)) / 1000;
l1voltage = ((double) hanReader.getInt((int)Kaifa_List3Phase::VoltageL1)) / 10;
l2voltage = ((double) hanReader.getInt((int)Kaifa_List3Phase::VoltageL2)) / 10;
l3voltage = ((double) hanReader.getInt((int)Kaifa_List3Phase::VoltageL3)) / 10;
break;
case (int)Kaifa::List1PhaseLong:
meterTimestamp = hanReader.getTime( (int)Kaifa_List1Phase::MeterClock);
activeImportCounter = ((double) hanReader.getInt((int)Kaifa_List1Phase::CumulativeActiveImportEnergy));
activeExportCounter = ((double) hanReader.getInt((int)Kaifa_List1Phase::CumulativeActiveExportEnergy));
reactiveImportCounter = ((double) hanReader.getInt((int)Kaifa_List1Phase::CumulativeReactiveImportEnergy));
reactiveExportCounter = ((double) hanReader.getInt((int)Kaifa_List1Phase::CumulativeReactiveExportEnergy));
case (int)Kaifa::List1PhaseShort:
listId = hanReader.getString( (int)Kaifa_List1Phase::ListVersionIdentifier);
meterId = hanReader.getString( (int)Kaifa_List1Phase::MeterID);
meterType = hanReader.getString( (int)Kaifa_List1Phase::MeterType);
activeImportPower = hanReader.getInt( (int)Kaifa_List1Phase::ActiveImportPower);
reactiveImportPower = hanReader.getInt( (int)Kaifa_List1Phase::ReactiveImportPower);
activeExportPower = hanReader.getInt( (int)Kaifa_List1Phase::ActiveExportPower);
reactiveExportPower = hanReader.getInt( (int)Kaifa_List1Phase::ReactiveExportPower);
l1current = ((double) hanReader.getInt((int)Kaifa_List1Phase::CurrentL1)) / 1000;
l1voltage = ((double) hanReader.getInt((int)Kaifa_List1Phase::VoltageL1)) / 10;
break;
}
}
}
void AmsData::extractFromAidon(HanReader& hanReader, int listSize) {
switch(listSize) {
case (int)Aidon::List1:
listType = 1;
break;
case (int)Aidon::List3PhaseITShort:
case (int)Aidon::List3PhaseShort:
threePhase = true;
case (int)Aidon::List1PhaseShort:
listType = 2;
break;
case (int)Aidon::List3PhaseITLong:
case (int)Aidon::List3PhaseLong:
threePhase = true;
case (int)Aidon::List1PhaseLong:
listType = 3;
break;
}
if(listSize == (int)Aidon::List1) {
activeImportPower = hanReader.getInt((int)Aidon_List1::ActiveImportPower);
} else {
switch(listSize) {
case (int)Aidon::List3PhaseLong:
meterTimestamp = hanReader.getTime( (int)Aidon_List3Phase::Timestamp);
activeImportCounter = ((double) hanReader.getInt( (int)Aidon_List3Phase::CumulativeActiveImportEnergy)) / 100;
activeExportCounter = ((double) hanReader.getInt( (int)Aidon_List3Phase::CumulativeActiveExportEnergy)) / 100;
reactiveImportCounter = ((double) hanReader.getInt( (int)Aidon_List3Phase::CumulativeReactiveImportEnergy)) / 100;
reactiveExportCounter = ((double) hanReader.getInt( (int)Aidon_List3Phase::CumulativeReactiveExportEnergy)) / 100;
case (int)Aidon::List3PhaseShort:
listId = hanReader.getString( (int)Aidon_List3Phase::ListVersionIdentifier);
meterId = hanReader.getString( (int)Aidon_List3Phase::MeterID);
meterType = hanReader.getString( (int)Aidon_List3Phase::MeterType);
activeImportPower = hanReader.getInt( (int)Aidon_List3Phase::ActiveImportPower);
reactiveImportPower = hanReader.getInt( (int)Aidon_List3Phase::ReactiveImportPower);
activeExportPower = hanReader.getInt( (int)Aidon_List3Phase::ActiveExportPower);
reactiveExportPower = hanReader.getInt( (int)Aidon_List3Phase::ReactiveExportPower);
l1current = ((double) hanReader.getInt( (int)Aidon_List3Phase::CurrentL1)) / 10;
l2current = ((double) hanReader.getInt( (int)Aidon_List3Phase::CurrentL2)) / 10;
l3current = ((double) hanReader.getInt( (int)Aidon_List3Phase::CurrentL3)) / 10;
l1voltage = ((double) hanReader.getInt( (int)Aidon_List3Phase::VoltageL1)) / 10;
l2voltage = ((double) hanReader.getInt( (int)Aidon_List3Phase::VoltageL2)) / 10;
l3voltage = ((double) hanReader.getInt( (int)Aidon_List3Phase::VoltageL3)) / 10;
break;
case (int)Aidon::List1PhaseLong:
meterTimestamp = hanReader.getTime( (int)Aidon_List1Phase::Timestamp);
activeImportCounter = ((double) hanReader.getInt( (int)Aidon_List1Phase::CumulativeActiveImportEnergy)) / 100;
activeExportCounter = ((double) hanReader.getInt( (int)Aidon_List1Phase::CumulativeActiveExportEnergy)) / 100;
reactiveImportCounter = ((double) hanReader.getInt( (int)Aidon_List1Phase::CumulativeReactiveImportEnergy)) / 100;
reactiveExportCounter = ((double) hanReader.getInt( (int)Aidon_List1Phase::CumulativeReactiveExportEnergy)) / 100;
case (int)Aidon::List1PhaseShort:
listId = hanReader.getString( (int)Aidon_List1Phase::ListVersionIdentifier);
meterId = hanReader.getString( (int)Aidon_List1Phase::MeterID);
meterType = hanReader.getString( (int)Aidon_List1Phase::MeterType);
activeImportPower = hanReader.getInt( (int)Aidon_List1Phase::ActiveImportPower);
reactiveImportPower = hanReader.getInt( (int)Aidon_List1Phase::ReactiveImportPower);
activeExportPower = hanReader.getInt( (int)Aidon_List1Phase::ActiveExportPower);
reactiveExportPower = hanReader.getInt( (int)Aidon_List1Phase::ReactiveExportPower);
l1current = ((double) hanReader.getInt( (int)Aidon_List1Phase::CurrentL1)) / 10;
l1voltage = ((double) hanReader.getInt( (int)Aidon_List1Phase::VoltageL1)) / 10;
break;
case (int)Aidon::List3PhaseITLong:
meterTimestamp = hanReader.getTime( (int)Aidon_List3PhaseIT::Timestamp);
activeImportCounter = ((double) hanReader.getInt( (int)Aidon_List3PhaseIT::CumulativeActiveImportEnergy)) / 100;
activeExportCounter = ((double) hanReader.getInt( (int)Aidon_List3PhaseIT::CumulativeActiveExportEnergy)) / 100;
reactiveImportCounter = ((double) hanReader.getInt( (int)Aidon_List3PhaseIT::CumulativeReactiveImportEnergy)) / 100;
reactiveExportCounter = ((double) hanReader.getInt( (int)Aidon_List3PhaseIT::CumulativeReactiveExportEnergy)) / 100;
case (int)Aidon::List3PhaseITShort:
listId = hanReader.getString( (int)Aidon_List3PhaseIT::ListVersionIdentifier);
meterId = hanReader.getString( (int)Aidon_List3PhaseIT::MeterID);
meterType = hanReader.getString( (int)Aidon_List3PhaseIT::MeterType);
activeImportPower = hanReader.getInt( (int)Aidon_List3PhaseIT::ActiveImportPower);
reactiveImportPower = hanReader.getInt( (int)Aidon_List3PhaseIT::ReactiveImportPower);
activeExportPower = hanReader.getInt( (int)Aidon_List3PhaseIT::ActiveExportPower);
reactiveExportPower = hanReader.getInt( (int)Aidon_List3PhaseIT::ReactiveExportPower);
l1current = ((double) hanReader.getInt( (int)Aidon_List3PhaseIT::CurrentL1)) / 10;
l2current = 0;
l3current = ((double) hanReader.getInt( (int)Aidon_List3PhaseIT::CurrentL3)) / 10;
l1voltage = ((double) hanReader.getInt( (int)Aidon_List3PhaseIT::VoltageL1)) / 10;
l2voltage = ((double) hanReader.getInt( (int)Aidon_List3PhaseIT::VoltageL2)) / 10;
l3voltage = ((double) hanReader.getInt( (int)Aidon_List3PhaseIT::VoltageL3)) / 10;
//l2current = ((activeImportPower * sqrt(3)) - (l1voltage * l1current) - (l3voltage * l3current)) / l2voltage;
break;
}
}
}
void AmsData::extractFromKamstrup(HanReader& hanReader, int listSize) {
switch(listSize) {
case (int)Kamstrup::List3PhaseShort:
threePhase = true;
case (int)Kamstrup::List1PhaseShort:
listType = 2;
break;
case (int)Kamstrup::List3PhaseLong:
threePhase = true;
case (int)Kamstrup::List1PhaseLong:
listType = 3;
break;
}
switch(listSize) {
case (int)Kamstrup::List3PhaseLong:
meterTimestamp = hanReader.getTime( (int)Kamstrup_List3Phase::MeterClock);
activeImportCounter = ((double) hanReader.getInt((int)Kamstrup_List3Phase::CumulativeActiveImportEnergy)) / 100;
activeExportCounter = ((double) hanReader.getInt((int)Kamstrup_List3Phase::CumulativeActiveExportEnergy)) / 100;
reactiveImportCounter = ((double) hanReader.getInt((int)Kamstrup_List3Phase::CumulativeReactiveImportEnergy)) / 100;
reactiveExportCounter = ((double) hanReader.getInt((int)Kamstrup_List3Phase::CumulativeReactiveExportEnergy)) / 100;
case (int)Kamstrup::List3PhaseShort:
listId = hanReader.getString( (int)Kamstrup_List3Phase::ListVersionIdentifier);
meterId = hanReader.getString( (int)Kamstrup_List3Phase::MeterID);
meterType = hanReader.getString( (int)Kamstrup_List3Phase::MeterType);
activeImportPower = hanReader.getInt( (int)Kamstrup_List3Phase::ActiveImportPower);
reactiveImportPower = hanReader.getInt( (int)Kamstrup_List3Phase::ReactiveImportPower);
activeExportPower = hanReader.getInt( (int)Kamstrup_List3Phase::ActiveExportPower);
reactiveExportPower = hanReader.getInt( (int)Kamstrup_List3Phase::ReactiveExportPower);
l1current = ((double) hanReader.getInt((int)Kamstrup_List3Phase::CurrentL1)) / 100;
l2current = ((double) hanReader.getInt((int)Kamstrup_List3Phase::CurrentL2)) / 100;
l3current = ((double) hanReader.getInt((int)Kamstrup_List3Phase::CurrentL3)) / 100;
l1voltage = hanReader.getInt( (int)Kamstrup_List3Phase::VoltageL1);
l2voltage = hanReader.getInt( (int)Kamstrup_List3Phase::VoltageL2);
l3voltage = hanReader.getInt( (int)Kamstrup_List3Phase::VoltageL3);
break;
case (int)Kamstrup::List1PhaseLong:
meterTimestamp = hanReader.getTime( (int)Kamstrup_List1Phase::MeterClock);
activeImportCounter = ((double) hanReader.getInt((int)Kamstrup_List1Phase::CumulativeActiveImportEnergy)) / 100;
activeExportCounter = ((double) hanReader.getInt((int)Kamstrup_List1Phase::CumulativeActiveExportEnergy)) / 100;
reactiveImportCounter = ((double) hanReader.getInt((int)Kamstrup_List1Phase::CumulativeReactiveImportEnergy)) / 100;
reactiveExportCounter = ((double) hanReader.getInt((int)Kamstrup_List1Phase::CumulativeReactiveExportEnergy)) / 100;
case (int)Kamstrup::List1PhaseShort:
listId = hanReader.getString( (int)Kamstrup_List1Phase::ListVersionIdentifier);
meterId = hanReader.getString( (int)Kamstrup_List1Phase::MeterID);
meterType = hanReader.getString( (int)Kamstrup_List1Phase::MeterType);
activeImportPower = hanReader.getInt( (int)Kamstrup_List1Phase::ActiveImportPower);
reactiveImportPower = hanReader.getInt( (int)Kamstrup_List1Phase::ReactiveImportPower);
activeExportPower = hanReader.getInt( (int)Kamstrup_List1Phase::ActiveExportPower);
reactiveExportPower = hanReader.getInt( (int)Kamstrup_List1Phase::ReactiveExportPower);
l1current = ((double) hanReader.getInt((int)Kamstrup_List1Phase::CurrentL1)) / 100;
l1voltage = hanReader.getInt( (int)Kamstrup_List1Phase::VoltageL1);
break;
}
}
void AmsData::apply(AmsData& other) {
this->lastUpdateMillis = other.getLastUpdateMillis();
this->packageTimestamp = other.getPackageTimestamp();
this->listType = max(this->listType, other.getListType());
switch(other.getListType()) {
case 3:
this->meterTimestamp = other.getMeterTimestamp();
this->activeImportCounter = other.getActiveImportCounter();
this->activeExportCounter = other.getActiveExportCounter();
this->reactiveImportCounter = other.getReactiveImportCounter();
this->reactiveExportCounter = other.getReactiveExportCounter();
case 2:
this->listId = other.getListId();
this->meterId = other.getMeterId();
this->meterType = other.getMeterType();
this->reactiveImportPower = other.getReactiveImportPower();
this->activeExportPower = other.getActiveExportPower();
this->reactiveExportPower = other.getReactiveExportPower();
this->l1current = other.getL1Current();
this->l2current = other.getL2Current();
this->l3current = other.getL3Current();
this->l1voltage = other.getL1Voltage();
this->l2voltage = other.getL2Voltage();
this->l3voltage = other.getL3Voltage();
this->threePhase = other.isThreePhase();
case 1:
this->activeImportPower = other.getActiveImportPower();
}
}
unsigned long AmsData::getLastUpdateMillis() {
return this->lastUpdateMillis;
}
unsigned long AmsData::getPackageTimestamp() {
return this->packageTimestamp;
}
int AmsData::getListType() {
return this->listType;
}
String AmsData::getListId() {
return this->listId;
}
String AmsData::getMeterId() {
return this->meterId;
}
String AmsData::getMeterType() {
return this->meterType;
}
unsigned long AmsData::getMeterTimestamp() {
return this->meterTimestamp;
}
int AmsData::getActiveImportPower() {
return this->activeImportPower;
}
int AmsData::getReactiveImportPower() {
return this->reactiveImportPower;
}
int AmsData::getActiveExportPower() {
return this->activeExportPower;
}
int AmsData::getReactiveExportPower() {
return this->reactiveExportPower;
}
double AmsData::getL1Voltage() {
return this->l1voltage;
}
double AmsData::getL2Voltage() {
return this->l2voltage;
}
double AmsData::getL3Voltage() {
return this->l3voltage;
}
double AmsData::getL1Current() {
return this->l1current;
}
double AmsData::getL2Current() {
return this->l2current;
}
double AmsData::getL3Current() {
return this->l3current;
}
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;
}

67
src/AmsData.h Normal file
View File

@@ -0,0 +1,67 @@
#ifndef _AMSDATA_H
#define _AMSDATA_H
#include "Arduino.h"
#include <Timezone.h>
#include "HanReader.h"
#define METER_TYPE_KAIFA 1
#define METER_TYPE_AIDON 2
#define METER_TYPE_KAMSTRUP 3
class AmsData {
public:
AmsData();
AmsData(int meterType, HanReader& hanReader);
void apply(AmsData& other);
unsigned long getLastUpdateMillis();
unsigned long getPackageTimestamp();
int getListType();
String getListId();
String getMeterId();
String getMeterType();
unsigned long getMeterTimestamp();
int getActiveImportPower();
int getReactiveImportPower();
int getActiveExportPower();
int getReactiveExportPower();
double getL1Voltage();
double getL2Voltage();
double getL3Voltage();
double getL1Current();
double getL2Current();
double getL3Current();
double getActiveImportCounter();
double getReactiveImportCounter();
double getActiveExportCounter();
double getReactiveExportCounter();
bool isThreePhase();
private:
unsigned long lastUpdateMillis = 0;
int listType = 0;
unsigned long packageTimestamp = 0;
String listId, meterId, meterType;
unsigned long meterTimestamp = 0;
int activeImportPower = 0, reactiveImportPower = 0, activeExportPower = 0, reactiveExportPower = 0;
double l1voltage = 0, l2voltage = 0, l3voltage = 0, l1current = 0, l2current = 0, l3current = 0;
double activeImportCounter = 0, reactiveImportCounter = 0, activeExportCounter = 0, reactiveExportCounter = 0;
bool threePhase = false;
void extractFromKaifa(HanReader& hanReader, int listSize);
void extractFromAidon(HanReader& hanReader, int listSize);
void extractFromKamstrup(HanReader& hanReader, int listSize);
};
#endif

View File

@@ -1,22 +1,33 @@
#ifndef _AMSTOMQTTBRIDGE_H
#define _AMSTOMQTTBRIDGE_H
#define WIFI_CONNECTION_TIMEOUT 30000;
#define INVALID_BUTTON_PIN 0xFFFFFFFF
#if defined(ESP8266)
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#elif defined(ESP32)
#include <WiFi.h>
#include <ESPmDNS.h>
#include "SPIFFS.h"
#include "Update.h"
#endif
#define RGB_RED 1
#define RGB_GREEN 2
#define RGB_YELLOW 3
#define RGB_ON 1
#define RGB_OFF 0
// Build settings for custom hardware by Roar Fredriksen
#if HW_ROARFRED
#define LED_PIN 2 // The blue on-board LED of the ESP8266 custom AMS board
#define LED_ACTIVE_HIGH 0
#define AP_BUTTON_PIN 0
#include <DallasTemperature.h>
#include <OneWire.h>
#define TEMP_SENSOR_PIN 5 // Temperature sensor connected to GPIO5
HardwareSerial *hanSerial = &Serial;
// Build settings for Wemos Lolin D32
@@ -25,9 +36,7 @@ HardwareSerial *hanSerial = &Serial;
#define LED_ACTIVE_HIGH 0
#define AP_BUTTON_PIN 4
#define SOFTWARE_SERIAL 1
#include <SoftwareSerial.h>
SoftwareSerial *hanSerial = new SoftwareSerial(GPIO_NUM_21);
HardwareSerial *hanSerial = &Serial2;
// Build settings for Wemos D1 mini
#elif defined(ARDUINO_ESP8266_WEMOS_D1MINI)
@@ -45,7 +54,15 @@ SoftwareSerial *hanSerial = new SoftwareSerial(D1);
#define LED_ACTIVE_HIGH 1
#define AP_BUTTON_PIN INVALID_BUTTON_PIN
HardwareSerial *hanSerial = &Serial;
HardwareSerial *hanSerial = &Serial2;
// Default build for ESP32
#elif defined(ESP32)
#define LED_PIN INVALID_BUTTON_PIN
#define LED_ACTIVE_HIGH 1
#define AP_BUTTON_PIN INVALID_BUTTON_PIN
HardwareSerial *hanSerial = &Serial2;
// Default build settings
#else
@@ -57,8 +74,4 @@ HardwareSerial *hanSerial = &Serial;
SoftwareSerial *hanSerial = new SoftwareSerial(5);
#endif
#if defined TEMP_SENSOR_PIN
OneWire oneWire(TEMP_SENSOR_PIN);
DallasTemperature tempSensor(&oneWire);
#endif
#endif

View File

@@ -1,141 +1,342 @@
/*
Name: AmsToMqttBridge.ino
Created: 3/13/2018 7:40:28 PM
Author: roarf
*/
/**
* @brief ESP8266 based program to receive data from AMS electric meters and send to MQTT
*
* @details Originally developed by Roar Fredriksen, this program was created to receive data from
* AMS electric meters via M-Bus, decode and send to a MQTT broker. The data packet structure
* supported by this software is specific to Norwegian meters, but may also support data from
* electricity providers in other countries. It was originally based on ESP8266, but have also been
* adapted to work with ESP32.
*
* @author Roar Fredriksen (@roarfred)
* The original developer for this project
* https://github.com/roarfred/AmsToMqttBridge
*
* @author Gunnar Skjold (@gskjold)
* Maintainer of current code
* https://github.com/gskjold/AmsToMqttBridge
*/
#include "AmsToMqttBridge.h"
#define ARDUINOJSON_POSITIVE_EXPONENTIATION_THRESHOLD 1e9
#include <ArduinoJson.h>
#include <MQTT.h>
#include <DNSServer.h>
#if defined(ESP8266)
ADC_MODE(ADC_VCC);
#endif
#include "HwTools.h"
#include "web/AmsWebServer.h"
#include "HanConfigAp.h"
#include "AmsConfiguration.h"
#include "HanReader.h"
#include "HanToJson.h"
// Configuration
configuration config;
#include "Aidon.h"
#include "Kaifa.h"
#include "Kamstrup.h"
// Object used to boot as Access Point
HanConfigAp ap;
#include "Uptime.h"
// Web server
AmsWebServer ws;
#define WEBSOCKET_DISABLED true
#include "RemoteDebug.h"
HwTools hw;
DNSServer dnsServer;
AmsConfiguration config;
RemoteDebug Debug;
AmsWebServer ws(&Debug);
// WiFi client and MQTT client
WiFiClient *client;
MQTTClient mqtt(384);
MQTTClient mqtt(512);
// Object used for debugging
HardwareSerial* debugger = NULL;
// The HAN Port reader, used to read serial data and decode DLMS
HanReader hanReader;
// the setup function runs once when you press reset or power the board
void setup() {
if(config.hasConfig()) {
config.load();
}
#if DEBUG_MODE
debugger = &Serial;
#if SOFTWARE_SERIAL
debugger->begin(115200, SERIAL_8N1);
#else
if(config.meterType == 3) {
hanSerial->begin(2400, SERIAL_8N1);
} else {
hanSerial->begin(2400, SERIAL_8E1);
}
#endif
while (!&debugger);
#if HW_ROARFRED
if(config.getMeterType() == 3) {
Serial.begin(2400, SERIAL_8N1);
} else {
Serial.begin(2400, SERIAL_8E1);
}
#else
Serial.begin(115200);
#endif
#endif
if (debugger) {
debugger->println("");
debugger->println("Started...");
if(config.hasConfig()) {
Debug.begin(config.getWifiHostname(), (uint8_t) config.getDebugLevel());
if(config.getAuthSecurity() > 0) {
Debug.setPassword(config.getAuthPassword());
}
Debug.setSerialEnabled(config.isDebugSerial());
if(!config.isDebugTelnet()) {
Debug.stop();
}
} else {
#if DEBUG_MODE
Debug.begin("localhost", RemoteDebug::DEBUG);
Debug.setSerialEnabled(true);
#endif
}
// Flash the LED, to indicate we can boot as AP now
double vcc = hw.getVcc();
if (Debug.isActive(RemoteDebug::INFO)) {
debugI("AMS bridge started");
debugI("Voltage: %.2fV", vcc);
}
if (vcc > 0 && vcc < 3.1) {
if(Debug.isActive(RemoteDebug::INFO)) {
debugI("Votltage is too low, sleeping");
Serial.flush();
}
ESP.deepSleep(10000000); //Deep sleep to allow output cap to charge up
}
#if HAS_RGB_LED
// Initialize RGB LED pins
pinMode(LEDPIN_RGB_GREEN, OUTPUT);
pinMode(LEDPIN_RGB_RED, OUTPUT);
#endif
pinMode(LED_PIN, OUTPUT);
led_on();
delay(1000);
// Initialize the AP
ap.setup(AP_BUTTON_PIN, &config, debugger);
pinMode(AP_BUTTON_PIN, INPUT_PULLUP);
led_off();
if (!ap.isActivated)
{
setupWiFi();
WiFi.disconnect(true);
WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_OFF);
if(config.mqttHost) {
mqtt.begin(config.mqttHost, *client);
// Notify everyone we're here!
sendMqttData("Connected!");
}
// Configure uart for AMS data
#if defined SOFTWARE_SERIAL
if(config.meterType == 3) {
hanSerial->begin(2400, SWSERIAL_8N1);
} else {
hanSerial->begin(2400, SWSERIAL_8E1);
}
#else
if(config.meterType == 3) {
hanSerial->begin(2400, SERIAL_8N1);
} else {
hanSerial->begin(2400, SERIAL_8E1);
}
#if defined UART2
hanSerial->swap();
if(SPIFFS.begin()) {
bool flashed = false;
if(SPIFFS.exists("/firmware.bin")) {
if(Debug.isActive(RemoteDebug::INFO)) debugI("Found firmware");
#if defined(ESP8266)
WiFi.setSleepMode(WIFI_LIGHT_SLEEP);
WiFi.forceSleepBegin();
#endif
int i = 0;
while(hw.getVcc() < 3.3 && i < 3) {
if(Debug.isActive(RemoteDebug::INFO)) debugI(" vcc not optimal, light sleep 10s");
#if defined(ESP8266)
delay(10000);
#elif defined(ESP32)
esp_sleep_enable_timer_wakeup(10000000);
esp_light_sleep_start();
#endif
while (!&hanSerial);
i++;
}
hanReader.setup(hanSerial, debugger);
// Compensate for the known Kaifa bug
hanReader.compensateFor09HeaderBug = (config.meterType == 1);
if(Debug.isActive(RemoteDebug::INFO)) debugI(" flashing");
File firmwareFile = SPIFFS.open("/firmware.bin", "r");
uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
if (!Update.begin(maxSketchSpace, U_FLASH)) {
if(Debug.isActive(RemoteDebug::ERROR)) {
debugE("Unable to start firmware update");
Update.printError(Serial);
}
} else {
while (firmwareFile.available()) {
uint8_t ibuffer[128];
firmwareFile.read((uint8_t *)ibuffer, 128);
Update.write(ibuffer, sizeof(ibuffer));
}
flashed = Update.end(true);
}
firmwareFile.close();
SPIFFS.remove("/firmware.bin");
}
SPIFFS.end();
if(flashed) {
if(Debug.isActive(RemoteDebug::INFO)) {
debugI("Firmware update complete, restarting");
Serial.flush();
}
#if defined(ESP8266)
ESP.reset();
#elif defined(ESP32)
ESP.restart();
#endif
return;
}
}
ws.setup(&config, debugger);
if(!config.hasConfig() || config.getConfigVersion() < 81) {
debugI("Setting default hostname");
uint16_t chipId;
#if defined(ARDUINO_ARCH_ESP32)
chipId = ESP.getEfuseMac();
#else
chipId = ESP.getChipId();
#endif
config.setWifiHostname(String("ams-") + String(chipId, HEX));
}
if(config.hasConfig()) {
if(Debug.isActive(RemoteDebug::INFO)) config.print(&Debug);
WiFi_connect();
client = new WiFiClient();
} else {
if(Debug.isActive(RemoteDebug::INFO)) {
debugI("No configuration, booting AP");
}
swapWifiMode();
}
#if SOFTWARE_SERIAL
if(Debug.isActive(RemoteDebug::DEBUG)) debugD("HAN has software serial");
if(config.getMeterType() == 3) {
hanSerial->begin(2400, SWSERIAL_8N1);
} else {
hanSerial->begin(2400, SWSERIAL_8E1);
}
#else
if(Debug.isActive(RemoteDebug::DEBUG)) {
debugD("HAN has hardware serial");
Serial.flush();
}
if(config.getMeterType() == 3) {
hanSerial->begin(2400, SERIAL_8N1);
} else {
hanSerial->begin(2400, SERIAL_8E1);
}
#if UART2
hanSerial->swap();
#endif
#endif
hanReader.setup(hanSerial, &Debug);
// Compensate for the known Kaifa bug
hanReader.compensateFor09HeaderBug = (config.getMeterType() == 1);
// Empty buffer before starting
while (hanSerial->available() > 0) {
hanSerial->read();
}
ws.setup(&config, &mqtt);
#if HAS_RGB_LED
//Signal startup by blinking red / green / yellow
rgb_led(RGB_RED, 2);
delay(250);
rgb_led(RGB_GREEN, 2);
delay(250);
rgb_led(RGB_YELLOW, 2);
#endif
}
// the loop function runs over and over again until power down or reset
void loop()
{
// Only do normal stuff if we're not booted as AP
if (!ap.loop())
{
// Turn off the LED
led_off();
int buttonTimer = 0;
bool buttonActive = false;
unsigned long longPressTime = 5000;
bool longPressActive = false;
// Reconnect to WiFi and MQTT as needed
if (WiFi.status() != WL_CONNECTED) {
WiFi_connect();
}
bool wifiConnected = false;
if (config.mqttHost) {
mqtt.loop();
delay(10); // <- fixes some issues with WiFi stability
if(!mqtt.connected()) {
MQTT_connect();
unsigned long lastTemperatureRead = 0;
double temperature = -127;
bool even = true;
unsigned long lastRead = 0;
unsigned long lastSuccessfulRead = 0;
unsigned long lastErrorBlink = 0;
int lastError = 0;
void loop() {
Debug.handle();
unsigned long now = millis();
if(AP_BUTTON_PIN != INVALID_BUTTON_PIN) {
if (digitalRead(AP_BUTTON_PIN) == LOW) {
if (buttonActive == false) {
buttonActive = true;
buttonTimer = now;
}
if ((now - buttonTimer > longPressTime) && (longPressActive == false)) {
longPressActive = true;
swapWifiMode();
}
} else {
if (buttonActive == true) {
if (longPressActive == true) {
longPressActive = false;
} else {
// Single press action
}
buttonActive = false;
}
}
readHanPort();
}
else
{
if(now - lastTemperatureRead > 5000) {
temperature = hw.getTemperature();
lastTemperatureRead = now;
}
if(now > 10000 && now - lastErrorBlink > 3000) {
errorBlink();
}
// Only do normal stuff if we're not booted as AP
if (WiFi.getMode() != WIFI_AP) {
led_off();
if (WiFi.status() != WL_CONNECTED) {
wifiConnected = false;
WiFi_connect();
} else {
if(!wifiConnected) {
wifiConnected = true;
if(Debug.isActive(RemoteDebug::INFO)) {
debugI("Successfully connected to WiFi!");
debugI("IP: %s", WiFi.localIP().toString().c_str());
}
if(!config.getWifiHostname().isEmpty()) {
MDNS.begin(config.getWifiHostname().c_str());
MDNS.addService("http", "tcp", 80);
}
}
if (!config.getMqttHost().isEmpty()) {
mqtt.loop();
delay(10); // Needed to preserve power. After adding this, the voltage is super smooth on a HAN powered device
if(!mqtt.connected() || config.isMqttChanged()) {
MQTT_connect();
}
if(config.getMqttPayloadFormat() == 1) {
sendSystemStatusToMqtt();
}
} else if(mqtt.connected()) {
mqtt.disconnect();
}
}
} else {
dnsServer.processNextRequest();
// Continously flash the LED when AP mode
if (millis() / 1000 % 2 == 0) led_on();
else led_off();
if (now / 50 % 64 == 0) led_on();
else led_off();
}
if(now - lastRead > 100) {
yield();
readHanPort();
lastRead = now;
}
ws.loop();
delay(1); // Needed for auto modem sleep
}
@@ -158,215 +359,388 @@ void led_off()
#endif
}
void setupWiFi()
{
// Turn off AP
WiFi.enableAP(false);
// Connect to WiFi
WiFi.mode(WIFI_STA);
WiFi.begin(config.ssid, config.ssidPassword);
// Wait for WiFi connection
if (debugger) debugger->print("\nWaiting for WiFi to connect...");
while (WiFi.status() != WL_CONNECTED) {
if (debugger) debugger->print(".");
delay(500);
void errorBlink() {
if(lastError == 3)
lastError = 0;
lastErrorBlink = millis();
for(;lastError < 3;lastError++) {
switch(lastError) {
case 0:
if(lastErrorBlink - lastSuccessfulRead > 30000) {
rgb_led(1, 2); // If no message received from AMS in 30 sec, blink once
return;
}
break;
case 1:
if(!config.getMqttHost().isEmpty() && mqtt.lastError() != 0) {
rgb_led(1, 3); // If MQTT error, blink twice
return;
}
break;
case 2:
if(WiFi.getMode() != WIFI_AP && WiFi.status() != WL_CONNECTED) {
rgb_led(1, 4); // If WiFi not connected, blink three times
return;
}
break;
}
}
if (debugger) debugger->println(" connected");
}
client = new WiFiClient();
void swapWifiMode() {
led_on();
WiFiMode_t mode = WiFi.getMode();
dnsServer.stop();
WiFi.disconnect(true);
WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_OFF);
yield();
if (mode != WIFI_AP || !config.hasConfig()) {
if(Debug.isActive(RemoteDebug::INFO)) debugI("Swapping to AP mode");
WiFi.softAP("AMS2MQTT");
WiFi.mode(WIFI_AP);
dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
dnsServer.start(53, "*", WiFi.softAPIP());
} else {
if(Debug.isActive(RemoteDebug::INFO)) debugI("Swapping to STA mode");
WiFi_connect();
}
delay(500);
led_off();
}
void mqttMessageReceived(String &topic, String &payload)
{
if (debugger) {
debugger->println("Incoming MQTT message:");
debugger->print("[");
debugger->print(topic);
debugger->print("] ");
debugger->println(payload);
if (Debug.isActive(RemoteDebug::DEBUG)) {
debugD("Incoming MQTT message: [%s] %s", topic.c_str(), payload.c_str());
}
// Do whatever needed here...
// Ideas could be to query for values or to initiate OTA firmware update
}
void readHanPort()
{
if (hanReader.read() && config.hasConfig())
{
// Flash LED on, this shows us that data is received
led_on();
AmsData lastMqttData;
void readHanPort() {
if (hanReader.read()) {
// Empty serial buffer. For some reason this seems to make a difference. Some garbage on the wire after package?
while(hanSerial->available()) {
hanSerial->read();
}
// Get the timestamp (as unix time) from the package
time_t time = hanReader.getPackageTime();
if (debugger) debugger->print("Time of the package is: ");
if (debugger) debugger->println(time);
lastSuccessfulRead = millis();
// Define a json object to keep the data
StaticJsonDocument<500> json;
if(config.getMeterType() > 0) {
rgb_led(RGB_GREEN, 2);
// Any generic useful info here
json["id"] = WiFi.macAddress();
json["up"] = millis();
json["t"] = time;
AmsData data(config.getMeterType(), hanReader);
if(data.getListType() > 0) {
ws.setData(data);
// Add a sub-structure to the json object,
// to keep the data from the meter itself
JsonObject data = json.createNestedObject("data");
if(!config.getMqttHost().isEmpty() && !config.getMqttPublishTopic().isEmpty()) {
if(config.getMqttPayloadFormat() == 0) {
StaticJsonDocument<512> json;
hanToJson(json, data, hw, temperature);
if (Debug.isActive(RemoteDebug::INFO)) {
debugI("Sending data to MQTT");
if (Debug.isActive(RemoteDebug::DEBUG)) {
serializeJsonPretty(json, Debug);
}
}
#if defined TEMP_SENSOR_PIN
// Get the temperature too
tempSensor.requestTemperatures();
data["temp"] = tempSensor.getTempCByIndex(0);
String msg;
serializeJson(json, msg);
mqtt.publish(config.getMqttPublishTopic(), msg.c_str());
} else if(config.getMqttPayloadFormat() == 1) {
mqtt.publish(config.getMqttPublishTopic() + "/meter/dlms/timestamp", String(data.getPackageTimestamp()));
switch(data.getListType()) {
case 3:
// ID and type belongs to List 2, but I see no need to send that every 10s
mqtt.publish(config.getMqttPublishTopic() + "/meter/id", data.getMeterId());
mqtt.publish(config.getMqttPublishTopic() + "/meter/type", data.getMeterType());
mqtt.publish(config.getMqttPublishTopic() + "/meter/clock", String(data.getMeterTimestamp()));
mqtt.publish(config.getMqttPublishTopic() + "/meter/import/reactive/accumulated", String(data.getReactiveImportCounter(), 2));
mqtt.publish(config.getMqttPublishTopic() + "/meter/import/active/accumulated", String(data.getActiveImportCounter(), 2));
mqtt.publish(config.getMqttPublishTopic() + "/meter/export/reactive/accumulated", String(data.getReactiveExportCounter(), 2));
mqtt.publish(config.getMqttPublishTopic() + "/meter/export/active/accumulated", String(data.getActiveExportCounter(), 2));
case 2:
// Only send data if changed. ID and Type is sent on the 10s interval only if changed
if(lastMqttData.getMeterId() != data.getMeterId()) {
mqtt.publish(config.getMqttPublishTopic() + "/meter/id", data.getMeterId());
}
if(lastMqttData.getMeterType() != data.getMeterType()) {
mqtt.publish(config.getMqttPublishTopic() + "/meter/type", data.getMeterType());
}
if(lastMqttData.getL1Current() != data.getL1Current()) {
mqtt.publish(config.getMqttPublishTopic() + "/meter/l1/current", String(data.getL1Current(), 2));
}
if(lastMqttData.getL1Voltage() != data.getL1Voltage()) {
mqtt.publish(config.getMqttPublishTopic() + "/meter/l1/voltage", String(data.getL1Voltage(), 2));
}
if(lastMqttData.getL2Current() != data.getL2Current()) {
mqtt.publish(config.getMqttPublishTopic() + "/meter/l2/current", String(data.getL2Current(), 2));
}
if(lastMqttData.getL2Voltage() != data.getL2Voltage()) {
mqtt.publish(config.getMqttPublishTopic() + "/meter/l2/voltage", String(data.getL2Voltage(), 2));
}
if(lastMqttData.getL3Current() != data.getL3Current()) {
mqtt.publish(config.getMqttPublishTopic() + "/meter/l3/current", String(data.getL3Current(), 2));
}
if(lastMqttData.getL3Voltage() != data.getL3Voltage()) {
mqtt.publish(config.getMqttPublishTopic() + "/meter/l3/voltage", String(data.getL3Voltage(), 2));
}
if(lastMqttData.getReactiveExportPower() != data.getReactiveExportPower()) {
mqtt.publish(config.getMqttPublishTopic() + "/meter/export/reactive", String(data.getReactiveExportPower()));
}
if(lastMqttData.getActiveExportPower() != data.getActiveExportPower()) {
mqtt.publish(config.getMqttPublishTopic() + "/meter/export/active", String(data.getActiveExportPower()));
}
if(lastMqttData.getReactiveImportPower() != data.getReactiveImportPower()) {
mqtt.publish(config.getMqttPublishTopic() + "/meter/import/reactive", String(data.getReactiveImportPower()));
}
case 1:
if(lastMqttData.getActiveImportPower() != data.getActiveImportPower()) {
mqtt.publish(config.getMqttPublishTopic() + "/meter/import/active", String(data.getActiveImportPower()));
}
}
}
lastMqttData.apply(data);
mqtt.loop();
delay(10);
}
}
} else {
// Auto detect meter if not set
for(int i = 1; i <= 3; i++) {
String list;
switch(i) {
case 1:
list = hanReader.getString((int) Kaifa_List1Phase::ListVersionIdentifier);
break;
case 2:
list = hanReader.getString((int) Aidon_List1Phase::ListVersionIdentifier);
break;
case 3:
list = hanReader.getString((int) Kamstrup_List1Phase::ListVersionIdentifier);
break;
}
if(!list.isEmpty()) {
list.toLowerCase();
if(list.startsWith("kfm")) {
config.setMeterType(1);
if(Debug.isActive(RemoteDebug::INFO)) debugI("Detected Kaifa meter");
break;
} else if(list.startsWith("aidon")) {
config.setMeterType(2);
if(Debug.isActive(RemoteDebug::INFO)) debugI("Detected Aidon meter");
break;
} else if(list.startsWith("kamstrup")) {
config.setMeterType(3);
if(Debug.isActive(RemoteDebug::INFO)) debugI("Detected Kamstrup meter");
break;
}
}
}
hanReader.compensateFor09HeaderBug = (config.getMeterType() == 1);
}
}
// Switch parity if meter is still not detected
if(config.getMeterType() == 0 && millis() - lastSuccessfulRead > 10000) {
lastSuccessfulRead = millis();
if(Debug.isActive(RemoteDebug::DEBUG)) debugD("No data for current setting, switching parity");
Serial.flush();
#if SOFTWARE_SERIAL
if(even) {
hanSerial->begin(2400, SWSERIAL_8N1);
} else {
hanSerial->begin(2400, SWSERIAL_8E1);
}
#else
if(even) {
hanSerial->begin(2400, SERIAL_8N1);
} else {
hanSerial->begin(2400, SERIAL_8E1);
}
#endif
hanToJson(data, config.meterType, hanReader);
if(config.mqttHost != 0 && strlen(config.mqttHost) != 0 && config.mqttPublishTopic != 0 && strlen(config.mqttPublishTopic) != 0) {
// Write the json to the debug port
if (debugger) {
debugger->print("Sending data to MQTT: ");
serializeJsonPretty(json, *debugger);
debugger->println();
}
// Publish the json to the MQTT server
String msg;
serializeJson(json, msg);
mqtt.publish(config.mqttPublishTopic, msg.c_str());
mqtt.loop();
}
ws.setJson(json);
// Flash LED off
led_off();
even = !even;
}
}
unsigned long wifiTimeout = WIFI_CONNECTION_TIMEOUT;
unsigned long lastWifiRetry = -WIFI_CONNECTION_TIMEOUT;
void WiFi_connect() {
// Connect to WiFi access point.
if (debugger)
{
debugger->println();
debugger->println();
debugger->print("Connecting to WiFi network ");
debugger->println(config.ssid);
}
if (WiFi.status() != WL_CONNECTED)
{
// Make one first attempt at connect, this seems to considerably speed up the first connection
WiFi.disconnect();
WiFi.begin(config.ssid, config.ssidPassword);
delay(1000);
}
// Wait for the WiFi connection to complete
long vTimeout = millis() + WIFI_CONNECTION_TIMEOUT;
while (WiFi.status() != WL_CONNECTED) {
if(millis() - lastWifiRetry < wifiTimeout) {
delay(50);
if (debugger) debugger->print(".");
// If we timed out, disconnect and try again
if (vTimeout < millis())
{
if (debugger)
{
debugger->print("Timout during connect. WiFi status is: ");
debugger->println(WiFi.status());
}
WiFi.disconnect();
WiFi.begin(config.ssid, config.ssidPassword);
vTimeout = millis() + WIFI_CONNECTION_TIMEOUT;
}
yield();
return;
}
lastWifiRetry = millis();
if (debugger) {
debugger->println();
debugger->println("WiFi connected");
debugger->println("IP address: ");
debugger->println(WiFi.localIP());
if (Debug.isActive(RemoteDebug::INFO)) debugI("Connecting to WiFi network: %s", config.getWifiSsid().c_str());
if (WiFi.status() != WL_CONNECTED) {
MDNS.end();
WiFi.disconnect();
yield();
WiFi.enableAP(false);
WiFi.mode(WIFI_STA);
if(!config.getWifiIp().isEmpty()) {
IPAddress ip, gw, sn(255,255,255,0), dns1, dns2;
ip.fromString(config.getWifiIp());
gw.fromString(config.getWifiGw());
sn.fromString(config.getWifiSubnet());
dns1.fromString(config.getWifiDns1());
dns2.fromString(config.getWifiDns2());
WiFi.config(ip, gw, sn, dns1, dns2);
}
if(!config.getWifiHostname().isEmpty()) {
#if defined(ESP8266)
WiFi.hostname(config.getWifiHostname());
#elif defined(ESP32)
WiFi.setHostname(config.getWifiHostname().c_str());
#endif
}
WiFi.begin(config.getWifiSsid().c_str(), config.getWifiPassword().c_str());
yield();
}
}
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect()
{
if(debugger) {
debugger->print("Connecting to MQTT: ");
debugger->print(config.mqttHost);
debugger->print(", port: ");
debugger->print(config.mqttPort);
debugger->println();
unsigned long lastMqttRetry = -10000;
void MQTT_connect() {
if(config.getMqttHost().isEmpty()) {
if(Debug.isActive(RemoteDebug::WARNING)) debugW("No MQTT config");
return;
}
// Wait for the MQTT connection to complete
while (!mqtt.connected()) {
// Connect to a unsecure or secure MQTT server
if ((config.mqttUser == 0 && mqtt.connect(config.mqttClientID)) ||
(config.mqttUser != 0 && mqtt.connect(config.mqttClientID, config.mqttUser, config.mqttPass)))
{
if (debugger) debugger->println("\nSuccessfully connected to MQTT!");
// Subscribe to the chosen MQTT topic, if set in configuration
if (config.mqttSubscribeTopic != 0 && strlen(config.mqttSubscribeTopic) > 0)
{
mqtt.subscribe(config.mqttSubscribeTopic);
if (debugger) debugger->printf(" Subscribing to [%s]\r\n", config.mqttSubscribeTopic);
}
}
else
{
if (debugger)
{
debugger->print(".");
debugger->print("failed, ");
debugger->println(" trying again in 5 seconds");
}
// Wait 2 seconds before retrying
mqtt.disconnect();
delay(2000);
}
// Allow some resources for the WiFi connection
if(millis() - lastMqttRetry < 5000) {
yield();
delay(2000);
return;
}
lastMqttRetry = millis();
if(Debug.isActive(RemoteDebug::INFO)) {
debugI("Connecting to MQTT %s:%d", config.getMqttHost().c_str(), config.getMqttPort());
}
mqtt.disconnect();
yield();
mqtt.begin(config.getMqttHost().c_str(), config.getMqttPort(), *client);
// Connect to a unsecure or secure MQTT server
if ((config.getMqttUser().isEmpty() && mqtt.connect(config.getMqttClientId().c_str())) ||
(!config.getMqttUser().isEmpty() && mqtt.connect(config.getMqttClientId().c_str(), config.getMqttUser().c_str(), config.getMqttPassword().c_str()))) {
if (Debug.isActive(RemoteDebug::INFO)) debugI("Successfully connected to MQTT!");
config.ackMqttChange();
// Subscribe to the chosen MQTT topic, if set in configuration
if (!config.getMqttSubscribeTopic().isEmpty()) {
mqtt.subscribe(config.getMqttSubscribeTopic());
if (Debug.isActive(RemoteDebug::INFO)) debugI(" Subscribing to [%s]\r\n", config.getMqttSubscribeTopic().c_str());
}
if(config.getMqttPayloadFormat() == 0) {
sendMqttData("Connected!");
} else if(config.getMqttPayloadFormat() == 1) {
sendSystemStatusToMqtt();
}
} else {
if (Debug.isActive(RemoteDebug::ERROR)) {
debugI("Failed to connect to MQTT");
}
}
yield();
}
// Send a simple string embedded in json over MQTT
void sendMqttData(String data)
{
// Make sure we have configured a publish topic
if (config.mqttPublishTopic == 0 || strlen(config.mqttPublishTopic) == 0)
if (config.getMqttPublishTopic().isEmpty())
return;
// Make sure we're connected
if (!client->connected() || !mqtt.connected()) {
MQTT_connect();
}
// Build a json with the message in a "data" attribute
StaticJsonDocument<500> json;
StaticJsonDocument<128> json;
json["id"] = WiFi.macAddress();
json["up"] = millis();
json["up"] = millis64()/1000;
json["data"] = data;
double vcc = hw.getVcc();
if(vcc > 0) {
json["vcc"] = vcc;
}
json["rssi"] = hw.getWifiRssi();
// Stringify the json
String msg;
serializeJson(json, msg);
// Send the json over MQTT
mqtt.publish(config.mqttPublishTopic, msg.c_str());
mqtt.publish(config.getMqttPublishTopic(), msg.c_str());
if (debugger) debugger->print("sendMqttData: ");
if (debugger) debugger->println(data);
if (Debug.isActive(RemoteDebug::INFO)) debugI("Sending MQTT data");
if (Debug.isActive(RemoteDebug::DEBUG)) debugD("[%s]", data.c_str());
}
unsigned long lastSystemDataSent = -10000;
void sendSystemStatusToMqtt() {
if (config.getMqttPublishTopic().isEmpty())
return;
if(millis() - lastSystemDataSent < 10000)
return;
lastSystemDataSent = millis();
mqtt.publish(config.getMqttPublishTopic() + "/id", WiFi.macAddress());
mqtt.publish(config.getMqttPublishTopic() + "/uptime", String((unsigned long) millis64()/1000));
double vcc = hw.getVcc();
if(vcc > 0) {
mqtt.publish(config.getMqttPublishTopic() + "/vcc", String(vcc, 2));
}
mqtt.publish(config.getMqttPublishTopic() + "/rssi", String(hw.getWifiRssi()));
if(temperature != DEVICE_DISCONNECTED_C) {
mqtt.publish(config.getMqttPublishTopic() + "/vcc", String(temperature, 2));
}
}
void rgb_led(int color, int mode) {
// Activate red and green LEDs if RGB LED is present (HAS_RGB_LED=1)
// If no RGB LED present (HAS_RGB_LED=0 or not defined), all output goes to ESP onboard LED
// color: 1=red, 2=green, 3=yellow
// mode: 0=OFF, 1=ON, >=2 -> Short blink(s), number of blinks: (mode - 1)
#ifndef HAS_RGB_LED
#define LEDPIN_RGB_RED LED_PIN
#define LEDPIN_RGB_GREEN LED_PIN
#endif
int blinkduration = 50; // milliseconds
switch (mode) {
case RGB_OFF: //OFF
digitalWrite(LEDPIN_RGB_RED, HIGH);
digitalWrite(LEDPIN_RGB_GREEN, HIGH);
break;
case RGB_ON: //ON
switch (color) {
case RGB_RED: //Red
digitalWrite(LEDPIN_RGB_RED, LOW);
digitalWrite(LEDPIN_RGB_GREEN, HIGH);
break;
case RGB_GREEN: //Green
digitalWrite(LEDPIN_RGB_RED, HIGH);
digitalWrite(LEDPIN_RGB_GREEN, LOW);
break;
case RGB_YELLOW: //Yellow
digitalWrite(LEDPIN_RGB_RED, LOW);
digitalWrite(LEDPIN_RGB_GREEN, LOW);
break;
}
break;
default: // Blink
for(int i = 1; i < mode; i++) {
rgb_led(color, RGB_ON);
delay(blinkduration);
rgb_led(color, RGB_OFF);
if(i != mode)
delay(blinkduration);
}
break;
}
}

View File

@@ -1,142 +0,0 @@
/*
Copyright (C) 2016 Arturo Guadalupi. All right reserved.
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*/
#include "Base64.h"
#include <Arduino.h>
#if (defined(__AVR__))
#include <avr\pgmspace.h>
#else
#include <pgmspace.h>
#endif
const char PROGMEM _Base64AlphabetTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
int Base64Class::encode(char *output, char *input, int inputLength) {
int i = 0, j = 0;
int encodedLength = 0;
unsigned char A3[3];
unsigned char A4[4];
while(inputLength--) {
A3[i++] = *(input++);
if(i == 3) {
fromA3ToA4(A4, A3);
for(i = 0; i < 4; i++) {
output[encodedLength++] = pgm_read_byte(&_Base64AlphabetTable[A4[i]]);
}
i = 0;
}
}
if(i) {
for(j = i; j < 3; j++) {
A3[j] = '\0';
}
fromA3ToA4(A4, A3);
for(j = 0; j < i + 1; j++) {
output[encodedLength++] = pgm_read_byte(&_Base64AlphabetTable[A4[j]]);
}
while((i++ < 3)) {
output[encodedLength++] = '=';
}
}
output[encodedLength] = '\0';
return encodedLength;
}
int Base64Class::decode(char * output, char * input, int inputLength) {
int i = 0, j = 0;
int decodedLength = 0;
unsigned char A3[3];
unsigned char A4[4];
while (inputLength--) {
if(*input == '=') {
break;
}
A4[i++] = *(input++);
if (i == 4) {
for (i = 0; i <4; i++) {
A4[i] = lookupTable(A4[i]);
}
fromA4ToA3(A3,A4);
for (i = 0; i < 3; i++) {
output[decodedLength++] = A3[i];
}
i = 0;
}
}
if (i) {
for (j = i; j < 4; j++) {
A4[j] = '\0';
}
for (j = 0; j <4; j++) {
A4[j] = lookupTable(A4[j]);
}
fromA4ToA3(A3,A4);
for (j = 0; j < i - 1; j++) {
output[decodedLength++] = A3[j];
}
}
output[decodedLength] = '\0';
return decodedLength;
}
int Base64Class::encodedLength(int plainLength) {
int n = plainLength;
return (n + 2 - ((n + 2) % 3)) / 3 * 4;
}
int Base64Class::decodedLength(char * input, int inputLength) {
int i = 0;
int numEq = 0;
for(i = inputLength - 1; input[i] == '='; i--) {
numEq++;
}
return ((6 * inputLength) / 8) - numEq;
}
//Private utility functions
inline void Base64Class::fromA3ToA4(unsigned char * A4, unsigned char * A3) {
A4[0] = (A3[0] & 0xfc) >> 2;
A4[1] = ((A3[0] & 0x03) << 4) + ((A3[1] & 0xf0) >> 4);
A4[2] = ((A3[1] & 0x0f) << 2) + ((A3[2] & 0xc0) >> 6);
A4[3] = (A3[2] & 0x3f);
}
inline void Base64Class::fromA4ToA3(unsigned char * A3, unsigned char * A4) {
A3[0] = (A4[0] << 2) + ((A4[1] & 0x30) >> 4);
A3[1] = ((A4[1] & 0xf) << 4) + ((A4[2] & 0x3c) >> 2);
A3[2] = ((A4[2] & 0x3) << 6) + A4[3];
}
inline unsigned char Base64Class::lookupTable(char c) {
if(c >='A' && c <='Z') return c - 'A';
if(c >='a' && c <='z') return c - 71;
if(c >='0' && c <='9') return c + 4;
if(c == '+') return 62;
if(c == '/') return 63;
return -1;
}
Base64Class Base64;

View File

@@ -1,26 +0,0 @@
/*
Copyright (C) 2016 Arturo Guadalupi. All right reserved.
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*/
#ifndef _BASE64_H
#define _BASE64_H
class Base64Class{
public:
int encode(char *output, char *input, int inputLength);
int decode(char * output, char * input, int inputLength);
int encodedLength(int plainLength);
int decodedLength(char * input, int inputLength);
private:
inline void fromA3ToA4(unsigned char * A4, unsigned char * A3);
inline void fromA4ToA3(unsigned char * A3, unsigned char * A4);
inline unsigned char lookupTable(char c);
};
extern Base64Class Base64;
#endif // _BASE64_H

46
src/HanToJson.cpp Normal file
View File

@@ -0,0 +1,46 @@
#include "HanToJson.h"
void hanToJson(JsonDocument& json, AmsData& data, HwTools& hw, double temperature) {
json["id"] = WiFi.macAddress();
json["up"] = millis();
json["t"] = data.getPackageTimestamp();
double vcc = hw.getVcc();
if(vcc > 0) {
json["vcc"] = serialized(String(vcc, 3));
}
json["rssi"] = hw.getWifiRssi();
if(temperature != DEVICE_DISCONNECTED_C) {
json["temp"] = serialized(String(temperature, 2));
}
// Add a sub-structure to the json object,
// to keep the data from the meter itself
JsonObject jd = json.createNestedObject("data");
switch(data.getListType()) {
case 3:
jd["rtc"] = data.getMeterTimestamp();
jd["tPI"] = data.getActiveImportCounter();
jd["tPO"] = data.getActiveExportCounter();
jd["tQI"] = data.getReactiveImportCounter();
jd["tQO"] = data.getReactiveExportCounter();
case 2:
jd["lv"] = data.getListId();
jd["id"] = data.getMeterId();
jd["type"] = data.getMeterType();
jd["Q"] = data.getReactiveImportPower();
jd["PO"] = data.getActiveExportPower();
jd["QO"] = data.getReactiveExportPower();
jd["I1"] = data.getL1Current();
jd["I2"] = data.getL2Current();
jd["I3"] = data.getL3Current();
jd["U1"] = data.getL1Voltage();
jd["U2"] = data.getL2Voltage();
jd["U3"] = data.getL3Voltage();
case 1:
jd["P"] = data.getActiveImportPower();
}
}

16
src/HanToJson.h Normal file
View File

@@ -0,0 +1,16 @@
#ifndef _HANTOJSON_h
#define _HANTOJSON_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <ArduinoJson.h>
#include "AmsData.h"
#include "HwTools.h"
void hanToJson(JsonDocument& json, AmsData& data, HwTools& hw, double temperature);
#endif

40
src/HwTools.cpp Normal file
View File

@@ -0,0 +1,40 @@
#include "HwTools.h"
double HwTools::getVcc() {
#if defined(ARDUINO_ESP8266_WEMOS_D1MINI)
return (((double) ESP.getVcc()) / 900); // This board has a voltage divider on VCC. Yes, 900 is correct
#elif defined(ESP8266)
#if defined(ESP_VCC_CALIB_FACTOR)
return ((double) ESP.getVcc()) / 1024 * ESP_VCC_CALIB_FACTOR;
#else
return ((double) ESP.getVcc()) / 1024;
#endif
#endif
return -1;
}
double HwTools::getTemperature() {
#if defined TEMP_SENSOR_PIN
if(!tempSensorInit) {
tempSensor->begin();
delay(50);
tempSensor->requestTemperatures();
hasTempSensor = tempSensor->getTempCByIndex(0) != DEVICE_DISCONNECTED_C;
tempSensorInit = true;
}
if(hasTempSensor) {
tempSensor->requestTemperatures();
return tempSensor->getTempCByIndex(0);
} else {
return DEVICE_DISCONNECTED_C;
}
#endif
return DEVICE_DISCONNECTED_C;
}
int HwTools::getWifiRssi() {
int rssi = WiFi.RSSI();
return isnan(rssi) ? -100.0 : rssi;
}

43
src/HwTools.h Normal file
View File

@@ -0,0 +1,43 @@
#ifndef _HWTOOLS_H
#define _HWTOOLS_H
#include "Arduino.h"
#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#endif
#include <DallasTemperature.h>
#include <OneWire.h>
#if HW_ROARFRED
#define TEMP_SENSOR_PIN 5
#elif defined(ARDUINO_LOLIN_D32)
#define TEMP_SENSOR_PIN 14
#elif defined(ARDUINO_ESP8266_WEMOS_D1MINI)
#define TEMP_SENSOR_PIN D5
#else
#define TEMP_SENSOR_PIN 0xFFFFFFFF
#endif
class HwTools {
public:
double getVcc();
double getTemperature();
int getWifiRssi();
HwTools() {
oneWire = new OneWire(TEMP_SENSOR_PIN);
tempSensor = new DallasTemperature(this->oneWire);
};
private:
bool tempSensorInit, hasTempSensor;
OneWire *oneWire;
DallasTemperature *tempSensor;
};
#endif

8
src/Uptime.cpp Normal file
View File

@@ -0,0 +1,8 @@
#include "Uptime.h"
uint64_t millis64() {
uint32_t new_low32 = millis();
if (new_low32 < _uptime_last_value) _uptime_rollovers++;
_uptime_last_value = new_low32;
return (uint64_t) _uptime_rollovers << 32 | _uptime_last_value;
}

10
src/Uptime.h Normal file
View File

@@ -0,0 +1,10 @@
#ifndef _UPTIME_H
#define _UPTIME_H
#include "Arduino.h"
static uint32_t _uptime_last_value = 0;
static uint32_t _uptime_rollovers = 0;
uint64_t millis64();
#endif

View File

@@ -2,95 +2,69 @@
#include "version.h"
#include "root/index_html.h"
#include "root/configuration_html.h"
#include "root/configmeter_html.h"
#include "root/configwifi_html.h"
#include "root/configmqtt_html.h"
#include "root/configweb_html.h"
#include "root/configsystem_html.h"
#include "root/restartwait_html.h"
#include "root/boot_css.h"
#include "root/gaugemeter_js.h"
#include "Base64.h"
#if defined(ESP8266)
ESP8266WebServer server(80);
#elif defined(ESP32) // ARDUINO_ARCH_ESP32
WebServer server(80);
#endif
AmsWebServer::AmsWebServer(RemoteDebug* Debug) {
this->debugger = Debug;
}
void AmsWebServer::setup(configuration* config, Stream* debugger) {
void AmsWebServer::setup(AmsConfiguration* config, MQTTClient* mqtt) {
this->config = config;
this->debugger = debugger;
this->mqtt = mqtt;
server.on("/", std::bind(&AmsWebServer::indexHtml, this));
server.on("/configuration", std::bind(&AmsWebServer::configurationHtml, this));
server.on("/boot.css", std::bind(&AmsWebServer::bootCss, this));
server.on("/gaugemeter.js", std::bind(&AmsWebServer::gaugemeterJs, this));
server.on("/data.json", std::bind(&AmsWebServer::dataJson, this));
server.on("/config-meter", HTTP_GET, std::bind(&AmsWebServer::configMeterHtml, this));
server.on("/config-wifi", HTTP_GET, std::bind(&AmsWebServer::configWifiHtml, this));
server.on("/config-mqtt", HTTP_GET, std::bind(&AmsWebServer::configMqttHtml, this));
server.on("/config-web", HTTP_GET, std::bind(&AmsWebServer::configWebHtml, this));
server.on("/boot.css", HTTP_GET, std::bind(&AmsWebServer::bootCss, this));
server.on("/gaugemeter.js", HTTP_GET, std::bind(&AmsWebServer::gaugemeterJs, this));
server.on("/data.json", HTTP_GET, std::bind(&AmsWebServer::dataJson, this));
server.on("/save", std::bind(&AmsWebServer::handleSave, this));
server.begin(); // Web server start
server.on("/config-system", HTTP_GET, std::bind(&AmsWebServer::configSystemHtml, this));
server.on("/config-system", HTTP_POST, std::bind(&AmsWebServer::configSystemPost, this), std::bind(&AmsWebServer::configSystemUpload, this));
server.on("/restart-wait", HTTP_GET, std::bind(&AmsWebServer::restartWaitHtml, this));
server.on("/is-alive", HTTP_GET, std::bind(&AmsWebServer::isAliveCheck, this));
print("Web server is ready for config at http://");
if(WiFi.getMode() == WIFI_AP) {
print(WiFi.softAPIP());
} else {
print(WiFi.localIP());
}
println("/");
server.begin(); // Web server start
}
void AmsWebServer::loop() {
server.handleClient();
}
void AmsWebServer::setJson(StaticJsonDocument<500> json) {
if(!json.isNull()) {
p = json["data"]["P"].as<int>();
if(json["data"].containsKey("U1")) {
u1 = json["data"]["U1"].as<double>();
i1 = json["data"]["I1"].as<double>();
if(json["data"].containsKey("U2")) {
u2 = json["data"]["U2"].as<double>();
i2 = json["data"]["I2"].as<double>();
void AmsWebServer::setData(AmsData& data) {
millis64(); // Make sure it catch all those rollovers
if(json["data"].containsKey("U3")) {
u3 = json["data"]["U3"].as<double>();
i3 = json["data"]["I3"].as<double>();
}
}
this->data.apply(data);
if(maxPwr == 0 && config->hasConfig() && config->fuseSize > 0 && config->distSys > 0) {
int volt = config->distSys == 2 ? 400 : 230;
if(u2 > 0) {
maxPwr = config->fuseSize * sqrt(3) * volt;
} else {
maxPwr = config->fuseSize * 230;
}
}
if(maxPwr == 0 && data.getListType() > 1 && config->hasConfig() && config->getMainFuse() > 0 && config->getDistributionSystem() > 0) {
int volt = config->getDistributionSystem() == 2 ? 400 : 230;
if(data.isThreePhase()) {
maxPwr = config->getMainFuse() * sqrt(3) * volt;
} else {
if(u1 > 0) {
json["data"]["U1"] = u1;
json["data"]["I1"] = i1;
}
if(u2 > 0) {
json["data"]["U2"] = u2;
json["data"]["I2"] = i2;
}
if(u3 > 0) {
json["data"]["U3"] = u3;
json["data"]["I3"] = i3;
}
maxPwr = config->getMainFuse() * 230;
}
this->json = json;
}
}
bool AmsWebServer::checkSecurity(byte level) {
bool access = !config->hasConfig() || config->authSecurity < level;
if(!access && config->authSecurity >= level && server.hasHeader("Authorization")) {
println(" forcing web security");
String expectedAuth = String(config->authUser) + ":" + String(config->authPass);
bool access = WiFi.getMode() == WIFI_AP || !config->hasConfig() || config->getAuthSecurity() < level;
if(!access && config->getAuthSecurity() >= level && server.hasHeader("Authorization")) {
printD(" forcing web security");
String expectedAuth = String(config->getAuthUser()) + ":" + String(config->getAuthPassword());
String providedPwd = server.header("Authorization");
providedPwd.replace("Basic ", "");
@@ -101,28 +75,47 @@ bool AmsWebServer::checkSecurity(byte level) {
int decodedLength = Base64.decodedLength(inputString, inputStringLength);
char decodedString[decodedLength];
Base64.decode(decodedString, inputString, inputStringLength);
print("Received auth: ");
println(decodedString);
printD("Received auth: %s", decodedString);
access = String(decodedString).equals(expectedAuth);
}
if(!access) {
println(" no access, requesting user/pass");
printD(" no access, requesting user/pass");
server.sendHeader("WWW-Authenticate", "Basic realm=\"Secure Area\"");
server.setContentLength(0);
server.send(401, "text/html", "");
}
return access;
}
void AmsWebServer::indexHtml() {
println("Serving /index.html over http...");
printD("Serving /index.html over http...");
if(!checkSecurity(2))
return;
String html = String((const __FlashStringHelper*) INDEX_HTML);
html.replace("${version}", VERSION);
html.replace("${data.P}", String(p));
if(WiFi.getMode() != WIFI_AP) {
html.replace("boot.css", BOOTSTRAP_URL);
}
double u1 = data.getL1Voltage();
double u2 = data.getL2Voltage();
double u3 = data.getL3Voltage();
double i1 = data.getL1Current();
double i2 = data.getL2Current();
double i3 = data.getL3Current();
double tpi = data.getActiveImportCounter();
double tpo = data.getActiveExportCounter();
double tqi = data.getReactiveImportCounter();
double tqo = data.getReactiveExportCounter();
html.replace("${data.P}", String(data.getActiveImportPower()));
html.replace("${data.PO}", String(data.getActiveExportPower()));
html.replace("${display.export}", config->getProductionCapacity() > 0 ? "" : "none");
html.replace("${text.import}", config->getProductionCapacity() > 0 ? "Import" : "Consumption");
html.replace("${data.U1}", u1 > 0 ? String(u1, 1) : "");
html.replace("${data.I1}", u1 > 0 ? String(i1, 1) : "");
@@ -136,240 +129,544 @@ void AmsWebServer::indexHtml() {
html.replace("${data.I3}", u3 > 0 ? String(i3, 1) : "");
html.replace("${display.P3}", u3 > 0 ? "" : "none");
html.replace("${data.tPI}", tpi > 0 ? String(tpi, 1) : "");
html.replace("${data.tPO}", tpi > 0 ? String(tpo, 1) : "");
html.replace("${data.tQI}", tpi > 0 ? String(tqi, 1) : "");
html.replace("${data.tQO}", tpi > 0 ? String(tqo, 1) : "");
html.replace("${display.accumulative}", tpi > 0 ? "" : "none");
double vcc = hw.getVcc();
html.replace("${vcc}", vcc > 0 ? String(vcc, 2) : "");
double temp = hw.getTemperature();
html.replace("${temp}", temp > 0 ? String(temp, 1) : "");
html.replace("${display.temp}", temp != DEVICE_DISCONNECTED_C ? "" : "none");
int rssi = hw.getWifiRssi();
html.replace("${wifi.rssi}", vcc > 0 ? String(rssi) : "");
html.replace("${wifi.channel}", WiFi.channel() > 0 ? String(WiFi.channel()) : "");
html.replace("${wifi.ssid}", !WiFi.SSID().isEmpty() ? String(WiFi.SSID()) : "");
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
server.sendHeader("Pragma", "no-cache");
server.sendHeader("Expires", "-1");
server.setContentLength(html.length());
server.send(200, "text/html", html);
}
void AmsWebServer::configurationHtml() {
println("Serving /configuration.html over http...");
void AmsWebServer::configMeterHtml() {
printD("Serving /config-meter.html over http...");
if(!checkSecurity(1))
return;
String html = String((const __FlashStringHelper*) CONFIGURATION_HTML);
String html = String((const __FlashStringHelper*) CONFIGMETER_HTML);
html.replace("${version}", VERSION);
if(WiFi.getMode() != WIFI_AP) {
html.replace("boot.css", BOOTSTRAP_URL);
}
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
server.sendHeader("Pragma", "no-cache");
server.sendHeader("Expires", "-1");
if(config->hasConfig()) {
html.replace("${config.ssid}", config->ssid);
html.replace("${config.ssidPassword}", config->ssidPassword);
html.replace("${config.meterType}", String(config->fuseSize));
for(int i = 0; i<4; i++) {
html.replace("${config.meterType" + String(i) + "}", config->meterType == i ? "selected" : "");
}
html.replace("${config.mqtt}", config->mqttHost == 0 ? "" : "checked");
html.replace("${config.mqttHost}", config->mqttHost);
html.replace("${config.mqttPort}", String(config->mqttPort));
html.replace("${config.mqttClientID}", config->mqttClientID);
html.replace("${config.mqttPublishTopic}", config->mqttPublishTopic);
html.replace("${config.mqttSubscribeTopic}", config->mqttSubscribeTopic);
html.replace("${config.mqttUser}", config->mqttUser);
html.replace("${config.mqttPass}", config->mqttPass);
html.replace("${config.authUser}", config->authUser);
html.replace("${config.authSecurity}", String(config->authSecurity));
for(int i = 0; i<3; i++) {
html.replace("${config.authSecurity" + String(i) + "}", config->authSecurity == i ? "selected" : "");
}
html.replace("${config.authPass}", config->authPass);
html.replace("${config.fuseSize}", String(config->fuseSize));
for(int i = 0; i<64; i++) {
html.replace("${config.fuseSize" + String(i) + "}", config->fuseSize == i ? "selected" : "");
}
for(int i = 0; i<3; i++) {
html.replace("${config.distSys" + String(i) + "}", config->distSys == i ? "selected" : "");
}
} else {
html.replace("${config.ssid}", "");
html.replace("${config.ssidPassword}", "");
html.replace("${config.meterType}", "");
for(int i = 0; i<4; i++) {
html.replace("${config.meterType" + String(i) + "}", i == 0 ? "selected" : "");
}
html.replace("${config.mqtt}", "");
html.replace("${config.mqttHost}", "");
html.replace("${config.mqttPort}", "1883");
html.replace("${config.mqttClientID}", "");
html.replace("${config.mqttPublishTopic}", "");
html.replace("${config.mqttSubscribeTopic}", "");
html.replace("${config.mqttUser}", "");
html.replace("${config.mqttPass}", "");
html.replace("${config.authSecurity}", "");
for(int i = 0; i<3; i++) {
html.replace("${config.authSecurity" + String(i) + "}", i == 0 ? "selected" : "");
}
html.replace("${config.authUser}", "");
html.replace("${config.authPass}", "");
html.replace("${config.fuseSize}", "");
for(int i = 0; i<64; i++) {
html.replace("${config.fuseSize" + String(i) + "}", i == 0 ? "selected" : "");
}
for(int i = 0; i<3; i++) {
html.replace("${config.distSys" + String(i) + "}", i == 0 ? "selected" : "");
}
html.replace("${config.meterType}", String(config->getMainFuse()));
for(int i = 0; i<4; i++) {
html.replace("${config.meterType" + String(i) + "}", config->getMeterType() == i ? "selected" : "");
}
html.replace("${config.distributionSystem}", String(config->getDistributionSystem()));
for(int i = 0; i<3; i++) {
html.replace("${config.distributionSystem" + String(i) + "}", config->getDistributionSystem() == i ? "selected" : "");
}
html.replace("${config.mainFuse}", String(config->getMainFuse()));
for(int i = 0; i<64; i++) {
html.replace("${config.mainFuse" + String(i) + "}", config->getMainFuse() == i ? "selected" : "");
}
html.replace("${config.productionCapacity}", String(config->getProductionCapacity()));
server.setContentLength(html.length());
server.send(200, "text/html", html);
}
void AmsWebServer::configWifiHtml() {
printD("Serving /config-wifi.html over http...");
if(!checkSecurity(1))
return;
String html = String((const __FlashStringHelper*) CONFIGWIFI_HTML);
html.replace("${version}", VERSION);
if(WiFi.getMode() != WIFI_AP) {
html.replace("boot.css", BOOTSTRAP_URL);
}
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
server.sendHeader("Pragma", "no-cache");
html.replace("${config.wifiSsid}", config->getWifiSsid());
html.replace("${config.wifiPassword}", config->getWifiPassword());
html.replace("${config.wifiIpType1}", config->getWifiIp().isEmpty() ? "" : "selected");
html.replace("${config.wifiIp}", config->getWifiIp());
html.replace("${config.wifiGw}", config->getWifiGw());
html.replace("${config.wifiSubnet}", config->getWifiSubnet());
html.replace("${config.wifiDns1}", config->getWifiDns1());
html.replace("${config.wifiDns2}", config->getWifiDns2());
html.replace("${config.wifiHostname}", config->getWifiHostname());
server.setContentLength(html.length());
server.send(200, "text/html", html);
}
void AmsWebServer::configMqttHtml() {
printD("Serving /config-mqtt.html over http...");
if(!checkSecurity(1))
return;
String html = String((const __FlashStringHelper*) CONFIGMQTT_HTML);
html.replace("${version}", VERSION);
if(WiFi.getMode() != WIFI_AP) {
html.replace("boot.css", BOOTSTRAP_URL);
}
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
server.sendHeader("Pragma", "no-cache");
html.replace("${config.mqtt}", config->getMqttHost() == 0 ? "" : "checked");
html.replace("${config.mqttHost}", config->getMqttHost());
if(config->getMqttPort() > 0) {
html.replace("${config.mqttPort}", String(config->getMqttPort()));
} else {
html.replace("${config.mqttPort}", String(1883));
}
html.replace("${config.mqttClientId}", config->getMqttClientId());
html.replace("${config.mqttPublishTopic}", config->getMqttPublishTopic());
html.replace("${config.mqttSubscribeTopic}", config->getMqttSubscribeTopic());
html.replace("${config.mqttUser}", config->getMqttUser());
html.replace("${config.mqttPassword}", config->getMqttPassword());
html.replace("${config.mqttPayloadFormat}", String(config->getMqttPayloadFormat()));
server.setContentLength(html.length());
server.send(200, "text/html", html);
}
void AmsWebServer::configWebHtml() {
printD("Serving /config-web.html over http...");
if(!checkSecurity(1))
return;
String html = String((const __FlashStringHelper*) CONFIGWEB_HTML);
html.replace("${version}", VERSION);
if(WiFi.getMode() != WIFI_AP) {
html.replace("boot.css", BOOTSTRAP_URL);
}
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
server.sendHeader("Pragma", "no-cache");
html.replace("${config.authSecurity}", String(config->getAuthSecurity()));
for(int i = 0; i<3; i++) {
html.replace("${config.authSecurity" + String(i) + "}", config->getAuthSecurity() == i ? "selected" : "");
}
html.replace("${config.authUser}", config->getAuthUser());
html.replace("${config.authPassword}", config->getAuthPassword());
server.setContentLength(html.length());
server.send(200, "text/html", html);
}
void AmsWebServer::bootCss() {
println("Serving /boot.css over http...");
printD("Serving /boot.css over http...");
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
server.sendHeader("Pragma", "no-cache");
server.sendHeader("Expires", "-1");
server.send(200, "text/css", BOOT_CSS);
String css = String((const __FlashStringHelper*) BOOT_CSS);
server.sendHeader("Cache-Control", "public, max-age=3600");
server.setContentLength(css.length());
server.send(200, "text/css", css);
}
void AmsWebServer::gaugemeterJs() {
println("Serving /gaugemeter.js over http...");
printD("Serving /gaugemeter.js over http...");
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
server.sendHeader("Pragma", "no-cache");
server.sendHeader("Expires", "-1");
server.send(200, "application/javascript", GAUGEMETER_JS);
String js = String((const __FlashStringHelper*) GAUGEMETER_JS);
server.sendHeader("Cache-Control", "public, max-age=3600");
server.setContentLength(js.length());
server.send(200, "application/javascript", js);
}
void AmsWebServer::dataJson() {
println("Serving /data.json over http...");
printD("Serving /data.json over http...");
if(!checkSecurity(2))
return;
String jsonStr;
if(!json.isNull()) {
println(" json has data");
StaticJsonDocument<768> json;
String jsonStr;
if(data.getLastUpdateMillis() > 0) {
int maxPwr = this->maxPwr;
if(maxPwr == 0) {
if(u2 > 0) {
if(data.isThreePhase()) {
maxPwr = 20000;
} else {
maxPwr = 10000;
}
}
json["maxPower"] = maxPwr;
json["pct"] = min(p*100/maxPwr, 100);
json["meterType"] = config->meterType;
json["currentMillis"] = millis();
json["up"] = data.getLastUpdateMillis();
json["t"] = data.getPackageTimestamp();
json.createNestedObject("data");
json["data"]["P"] = data.getActiveImportPower();
json["data"]["PO"] = data.getActiveExportPower();
serializeJson(json, jsonStr);
double u1 = data.getL1Voltage();
double u2 = data.getL2Voltage();
double u3 = data.getL3Voltage();
double i1 = data.getL1Current();
double i2 = data.getL2Current();
double i3 = data.getL3Current();
double tpi = data.getActiveImportCounter();
double tpo = data.getActiveExportCounter();
double tqi = data.getReactiveImportCounter();
double tqo = data.getReactiveExportCounter();
if(u1 > 0) {
json["data"]["U1"] = u1;
json["data"]["I1"] = i1;
}
if(u2 > 0) {
json["data"]["U2"] = u2;
json["data"]["I2"] = i2;
}
if(u3 > 0) {
json["data"]["U3"] = u3;
json["data"]["I3"] = i3;
}
if(tpi > 0) {
json["data"]["tPI"] = tpi;
json["data"]["tPO"] = tpo;
json["data"]["tQI"] = tqi;
json["data"]["tQO"] = tqo;
}
json["p_pct"] = min(data.getActiveImportPower()*100/maxPwr, 100);
if(config->getProductionCapacity() > 0) {
int maxPrd = config->getProductionCapacity() * 1000;
json["po_pct"] = min(data.getActiveExportPower()*100/maxPrd, 100);
}
} else {
println(" json is empty");
jsonStr = "{}";
json["p_pct"] = -1;
json["po_pct"] = -1;
}
json["id"] = WiFi.macAddress();
json["maxPower"] = maxPwr;
json["meterType"] = config->getMeterType();
json["uptime_seconds"] = millis64() / 1000;
double vcc = hw.getVcc();
json["vcc"] = serialized(String(vcc, 3));
double temp = hw.getTemperature();
json["temp"] = serialized(String(temp, 2));
json.createNestedObject("wifi");
float rssi = WiFi.RSSI();
rssi = isnan(rssi) ? -100.0 : rssi;
json["wifi"]["ssid"] = WiFi.SSID();
json["wifi"]["channel"] = (int) WiFi.channel();
json["wifi"]["rssi"] = rssi;
json.createNestedObject("status");
String espStatus;
if(vcc == 0) {
espStatus = "secondary";
} else if(vcc > 3.1) {
espStatus = "success";
} else if(vcc > 2.8) {
espStatus = "warning";
} else {
espStatus = "danger";
}
json["status"]["esp"] = espStatus;
unsigned long now = millis();
String hanStatus;
if(config->getMeterType() == 0) {
hanStatus = "secondary";
} else if(now - data.getLastUpdateMillis() < 15000) {
hanStatus = "success";
} else if(now - data.getLastUpdateMillis() < 30000) {
hanStatus = "warning";
} else {
hanStatus = "danger";
}
json["status"]["han"] = hanStatus;
String wifiStatus;
if(config->getWifiSsid().isEmpty()) {
wifiStatus = "secondary";
} else if(rssi > -75) {
wifiStatus = "success";
} else if(rssi > -95) {
wifiStatus = "warning";
} else {
wifiStatus = "danger";
}
json["status"]["wifi"] = wifiStatus;
String mqttStatus;
if(config->getMqttHost().isEmpty()) {
mqttStatus = "secondary";
} else if(mqtt->connected()) {
mqttStatus = "success";
} else if(mqtt->lastError() == 0) {
mqttStatus = "warning";
} else {
mqttStatus = "danger";
}
json["status"]["mqtt"] = mqttStatus;
json.createNestedObject("mqtt");
json["mqtt"]["lastError"] = (int) mqtt->lastError();
serializeJson(json, jsonStr);
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
server.sendHeader("Pragma", "no-cache");
server.sendHeader("Expires", "-1");
server.setContentLength(jsonStr.length());
server.send(200, "application/json", jsonStr);
}
void AmsWebServer::handleSave() {
String temp;
temp = server.arg("ssid");
config->ssid = new char[temp.length() + 1];
temp.toCharArray(config->ssid, temp.length() + 1, 0);
if(server.hasArg("meterConfig") && server.arg("meterConfig") == "true") {
config->setMeterType(server.arg("meterType").toInt());
config->setDistributionSystem(server.arg("distributionSystem").toInt());
config->setMainFuse(server.arg("mainFuse").toInt());
config->setProductionCapacity(server.arg("productionCapacity").toInt());
}
temp = server.arg("ssidPassword");
config->ssidPassword = new char[temp.length() + 1];
temp.toCharArray(config->ssidPassword, temp.length() + 1, 0);
if(server.hasArg("wifiConfig") && server.arg("wifiConfig") == "true") {
config->setWifiSsid(server.arg("wifiSsid"));
config->setWifiPassword(server.arg("wifiPassword"));
if(server.hasArg("wifiIpType") && server.arg("wifiIpType").toInt() == 1) {
config->setWifiIp(server.arg("wifiIp"));
config->setWifiGw(server.arg("wifiGw"));
config->setWifiSubnet(server.arg("wifiSubnet"));
config->setWifiDns1(server.arg("wifiDns1"));
config->setWifiDns2(server.arg("wifiDns2"));
} else {
config->clearWifiIp();
}
config->setWifiHostname(server.arg("wifiHostname"));
}
config->meterType = (byte)server.arg("meterType").toInt();
if(server.hasArg("mqttConfig") && server.arg("mqttConfig") == "true") {
if(server.hasArg("mqtt") && server.arg("mqtt") == "true") {
config->setMqttHost(server.arg("mqttHost"));
int port = server.arg("mqttPort").toInt();
config->setMqttPort(port == 0 ? 1883 : port);
config->setMqttClientId(server.arg("mqttClientId"));
config->setMqttPublishTopic(server.arg("mqttPublishTopic"));
config->setMqttSubscribeTopic(server.arg("mqttSubscribeTopic"));
config->setMqttUser(server.arg("mqttUser"));
config->setMqttPassword(server.arg("mqttPassword"));
config->setMqttPayloadFormat(server.arg("mqttPayloadFormat").toInt());
} else {
config->clearMqtt();
}
}
if(server.hasArg("mqtt") && server.arg("mqtt") == "true") {
println("MQTT enabled");
temp = server.arg("mqttHost");
config->mqttHost = new char[temp.length() + 1];
temp.toCharArray(config->mqttHost, temp.length() + 1, 0);
if(server.hasArg("authConfig") && server.arg("authConfig") == "true") {
config->setAuthSecurity((byte)server.arg("authSecurity").toInt());
if(config->getAuthSecurity() > 0) {
config->setAuthUser(server.arg("authUser"));
config->setAuthPassword(server.arg("authPassword"));
} else {
config->clearAuth();
}
}
config->mqttPort = (int)server.arg("mqttPort").toInt();
if(server.hasArg("sysConfig") && server.arg("sysConfig") == "true") {
config->setDebugTelnet(server.hasArg("debugTelnet") && server.arg("debugTelnet") == "true");
config->setDebugSerial(server.hasArg("debugSerial") && server.arg("debugSerial") == "true");
config->setDebugLevel(server.arg("debugLevel").toInt());
debugger->stop();
debugger->begin(config->getWifiHostname(), (uint8_t) config->getDebugLevel());
if(config->getAuthSecurity() > 0) {
debugger->setPassword(config->getAuthPassword());
}
debugger->setSerialEnabled(config->isDebugSerial());
if(!config->isDebugTelnet()) {
debugger->stop();
}
}
temp = server.arg("mqttClientID");
config->mqttClientID = new char[temp.length() + 1];
temp.toCharArray(config->mqttClientID, temp.length() + 1, 0);
printI("Saving configuration now...");
temp = server.arg("mqttPublishTopic");
config->mqttPublishTopic = new char[temp.length() + 1];
temp.toCharArray(config->mqttPublishTopic, temp.length() + 1, 0);
temp = server.arg("mqttSubscribeTopic");
config->mqttSubscribeTopic = new char[temp.length() + 1];
temp.toCharArray(config->mqttSubscribeTopic, temp.length() + 1, 0);
temp = server.arg("mqttUser");
config->mqttUser = new char[temp.length() + 1];
temp.toCharArray(config->mqttUser, temp.length() + 1, 0);
temp = server.arg("mqttPass");
config->mqttPass = new char[temp.length() + 1];
temp.toCharArray(config->mqttPass, temp.length() + 1, 0);
if (debugger->isActive(RemoteDebug::DEBUG)) config->print(debugger);
if (config->save()) {
printI("Successfully saved.");
if(config->isWifiChanged()) {
performRestart = true;
server.sendHeader("Location","/restart-wait");
server.send(303);
} else {
server.sendHeader("Location", String("/"), true);
server.send (302, "text/plain", "");
}
} else {
println("MQTT disabled");
config->mqttHost = NULL;
config->mqttUser = NULL;
config->mqttPass = NULL;
printE("Error saving configuration");
String html = "<html><body><h1>Error saving configuration!</h1></form>";
server.send(500, "text/html", html);
}
}
void AmsWebServer::configSystemHtml() {
printD("Serving /config-system.html over http...");
if(!checkSecurity(1))
return;
String html = String((const __FlashStringHelper*) CONFIGSYSTEM_HTML);
html.replace("${version}", VERSION);
if(WiFi.getMode() != WIFI_AP) {
html.replace("boot.css", BOOTSTRAP_URL);
}
config->authSecurity = (byte)server.arg("authSecurity").toInt();
if(config->authSecurity > 0) {
temp = server.arg("authUser");
config->authUser = new char[temp.length() + 1];
temp.toCharArray(config->authUser, temp.length() + 1, 0);
temp = server.arg("authPass");
config->authPass = new char[temp.length() + 1];
temp.toCharArray(config->authPass, temp.length() + 1, 0);
html.replace("${config.debugTelnet}", config->isDebugTelnet() ? "checked" : "");
html.replace("${config.debugSerial}", config->isDebugSerial() ? "checked" : "");
html.replace("${config.debugLevel}", String(config->getDebugLevel()));
for(int i = 0; i<=RemoteDebug::ANY; i++) {
html.replace("${config.debugLevel" + String(i) + "}", config->getDebugLevel() == i ? "selected" : "");
}
config->fuseSize = (int)server.arg("fuseSize").toInt();
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
server.sendHeader("Pragma", "no-cache");
config->distSys = (byte)server.arg("distSys").toInt();
server.setContentLength(html.length());
server.send(200, "text/html", html);
}
println("Saving configuration now...");
void AmsWebServer::configSystemPost() {
server.send(200);
}
if (debugger) config->print(debugger);
if (config->save())
{
println("Successfully saved. Will reboot now.");
String html = "<html><body><h1>Successfully Saved!</h1><h3>Device is restarting now...</h3><a href=\"/\">Go to index</a></form>";
server.send(200, "text/html", html);
yield();
void AmsWebServer::configSystemUpload() {
HTTPUpload& upload = server.upload();
if(upload.status == UPLOAD_FILE_START){
String filename = upload.filename;
if(!filename.endsWith(".bin")) {
server.send(500, "text/plain", "500: couldn't create file");
} else if (!SPIFFS.begin()) {
printE("An Error has occurred while mounting SPIFFS");
String html = "<html><body><h1>Error uploading!</h1></form>";
server.send(500, "text/html", html);
} else {
printD("handleFileUpload Name: %s", filename.c_str());
firmwareFile = SPIFFS.open("/firmware.bin", "w");
filename = String();
}
} else if(upload.status == UPLOAD_FILE_WRITE) {
if(firmwareFile)
firmwareFile.write(upload.buf, upload.currentSize);
} else if(upload.status == UPLOAD_FILE_END) {
if(firmwareFile) {
firmwareFile.close();
SPIFFS.end();
printD("handleFileUpload Size: %d", upload.totalSize);
performRestart = true;
server.sendHeader("Location","/restart-wait");
server.send(303);
} else {
server.send(500, "text/plain", "500: couldn't create file");
}
}
}
void AmsWebServer::restartWaitHtml() {
printD("Serving /restart-wait.html over http...");
if(!checkSecurity(1))
return;
String html = String((const __FlashStringHelper*) RESTARTWAIT_HTML);
html.replace("${version}", VERSION);
if(WiFi.getMode() != WIFI_AP) {
html.replace("boot.css", BOOTSTRAP_URL);
}
if(config->getWifiIp().isEmpty() && WiFi.getMode() != WIFI_AP) {
html.replace("${ip}", WiFi.localIP().toString());
} else {
html.replace("${ip}", config->getWifiIp());
}
html.replace("${hostname}", config->getWifiHostname());
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
server.sendHeader("Pragma", "no-cache");
server.setContentLength(html.length());
server.send(200, "text/html", html);
yield();
if(performRestart) {
SPIFFS.end();
printI("Firmware uploaded, rebooting");
delay(1000);
#if defined(ESP8266)
ESP.reset();
#elif defined(ESP32)
ESP.restart();
#endif
}
else
{
println("Error saving configuration");
String html = "<html><body><h1>Error saving configuration!</h1></form>";
server.send(500, "text/html", html);
performRestart = false;
}
}
void AmsWebServer::isAliveCheck() {
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200);
}
size_t AmsWebServer::print(const char* text)
{
if (debugger) debugger->print(text);
void AmsWebServer::printD(String fmt, ...) {
va_list args;
va_start(args, fmt);
if(debugger->isActive(RemoteDebug::DEBUG)) debugger->printf(String("(AmsWebServer)" + fmt + "\n").c_str(), args);
va_end(args);
}
size_t AmsWebServer::println(const char* text)
{
if (debugger) debugger->println(text);
void AmsWebServer::printI(String fmt, ...) {
va_list args;
va_start(args, fmt);
if(debugger->isActive(RemoteDebug::INFO)) debugger->printf(String("(AmsWebServer)" + fmt + "\n").c_str(), args);
va_end(args);
}
size_t AmsWebServer::print(const Printable& data)
{
if (debugger) debugger->print(data);
void AmsWebServer::printW(String fmt, ...) {
va_list args;
va_start(args, fmt);
if(debugger->isActive(RemoteDebug::WARNING)) debugger->printf(String("(AmsWebServer)" + fmt + "\n").c_str(), args);
va_end(args);
}
size_t AmsWebServer::println(const Printable& data)
{
if (debugger) debugger->println(data);
void AmsWebServer::printE(String fmt, ...) {
va_list args;
va_start(args, fmt);
if(debugger->isActive(RemoteDebug::ERROR)) debugger->printf(String("(AmsWebServer)" + fmt + "\n").c_str(), args);
va_end(args);
}

View File

@@ -1,8 +1,15 @@
#ifndef _AMSWEBSERVER_h
#define _AMSWEBSERVER_h
#define BOOTSTRAP_URL "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css"
#include <MQTT.h>
#include <ArduinoJson.h>
#include "configuration.h"
#include "AmsConfiguration.h"
#include "HwTools.h"
#include "AmsData.h"
#include "Uptime.h"
#include "RemoteDebug.h"
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
@@ -16,23 +23,29 @@
#elif defined(ESP32) // ARDUINO_ARCH_ESP32
#include <WiFi.h>
#include <WebServer.h>
#include "SPIFFS.h"
#include "Update.h"
#else
#warning "Unsupported board type"
#endif
class AmsWebServer {
public:
void setup(configuration* config, Stream* debugger);
AmsWebServer(RemoteDebug* Debug);
void setup(AmsConfiguration* config, MQTTClient* mqtt);
void loop();
void setJson(StaticJsonDocument<500> json);
void setData(AmsData& data);
private:
configuration* config;
Stream* debugger;
StaticJsonDocument<500> json;
int maxPwr;
int p;
double u1, u2, u3, i1, i2, i3;
RemoteDebug* debugger;
int maxPwr = 0;
HwTools hw;
AmsConfiguration* config;
AmsData data;
MQTTClient* mqtt;
File firmwareFile;
bool performRestart = false;
#if defined(ESP8266)
ESP8266WebServer server;
@@ -43,18 +56,26 @@ private:
bool checkSecurity(byte level);
void indexHtml();
void configurationHtml();
void configMeterHtml();
void configWifiHtml();
void configMqttHtml();
void configWebHtml();
void bootCss();
void gaugemeterJs();
void dataJson();
void handleSave();
size_t print(const char* text);
size_t println(const char* text);
size_t print(const Printable& data);
size_t println(const Printable& data);
void configSystemHtml();
void configSystemPost();
void configSystemUpload();
void restartWaitHtml();
void isAliveCheck();
void printD(String fmt, ...);
void printI(String fmt, ...);
void printW(String fmt, ...);
void printE(String fmt, ...);
};
#endif

View File

@@ -62,6 +62,9 @@ body {
.mb-0, .my-0 {
margin-bottom: 0!important;
}
.m-2 {
margin: .5rem!important;
}
.mb-2, .my-2 {
margin-bottom: .5rem!important;
}
@@ -92,7 +95,8 @@ body {
}
.border-bottom {
border-bottom: 1px solid #dee2e6!important;
}.rounded {
}
.rounded {
border-radius: .25rem!important;
}
div {
@@ -140,10 +144,6 @@ h1, h2, h3, h4, h5, h6 {
margin-right: -15px;
margin-left: -15px;
}
.d-flex {
display: -ms-flexbox!important;
display: flex!important;
}
.col, .col-1, .col-10, .col-11, .col-12, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-auto, .col-lg, .col-lg-1, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-auto, .col-md, .col-md-1, .col-md-10, .col-md-11, .col-md-12, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-auto, .col-sm, .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-auto, .col-xl, .col-xl-1, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-auto {
position: relative;
width: 100%;
@@ -185,6 +185,22 @@ h1, h2, h3, h4, h5, h6 {
flex: 0 0 75%;
max-width: 75%;
}
.d-none {
display: none!important;
}
.d-flex {
display: -ms-flexbox!important;
display: flex!important;
}
.flex-row {
-ms-flex-direction: row!important;
flex-direction: row!important;
}
.flex-column {
-ms-flex-direction: column!important;
flex-direction: column!important;
}
a {
color: #007bff;
text-decoration: none;
@@ -218,6 +234,107 @@ a {
background-color: #007bff;
border-color: #007bff;
}
.navbar {
position: relative;
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
-ms-flex-align: center;
align-items: center;
-ms-flex-pack: justify;
justify-content: space-between;
padding: .5rem 1rem;
}
.navbar-dark .navbar-brand {
color: #fff;
}
.navbar-expand {
-ms-flex-flow: row nowrap;
flex-flow: row nowrap;
-ms-flex-pack: start;
justify-content: flex-start;
}
.navbar-nav {
display: -ms-flexbox;
display: flex;
-ms-flex-direction: column;
flex-direction: column;
padding-left: 0;
margin-bottom: 0;
list-style: none;
}
.navbar-expand .navbar-nav {
-ms-flex-direction: row;
flex-direction: row;
}
.navbar-brand {
display: inline-block;
padding-top: .3125rem;
padding-bottom: .3125rem;
margin-right: 1rem;
font-size: 1.25rem;
line-height: inherit;
white-space: nowrap;
}
.navbar-dark .navbar-nav .nav-link {
color: rgba(255,255,255,.5);
}
.navbar-expand .navbar-nav .nav-link {
padding-right: .5rem;
padding-left: .5rem;
}
.navbar-nav .nav-link {
padding-right: 0;
padding-left: 0;
}
.nav-link {
display: block;
padding: .5rem 1rem;
}
.navbar-dark .navbar-nav .active>.nav-link, .navbar-dark .navbar-nav .nav-link.active, .navbar-dark .navbar-nav .nav-link.show, .navbar-dark .navbar-nav .show>.nav-link {
color: #fff;
}
.badge {
display: inline-block;
padding: .25em .4em;
font-size: 75%;
font-weight: 700;
line-height: 1;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: .25rem;
transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
.badge-secondary {
color: #fff;
background-color: #6c757d;
}
.badge-success {
color: #fff;
background-color: #28a745;
}
.badge-warning {
color: #212529;
background-color: #ffc107;
}
.badge-danger {
color: #fff;
background-color: #dc3545;
}
.alert {
position: relative;
padding: .75rem 1.25rem;
margin-bottom: 1rem;
border: 1px solid transparent;
border-radius: .25rem;
}
.alert-warning {
color: #856404;
background-color: #fff3cd;
border-color: #ffeeba;
}
.form-group {
margin-bottom: 1rem;
}
@@ -256,6 +373,55 @@ input[type="radio"], input[type="checkbox"] {
box-sizing: border-box;
padding: 0;
}
.input-group {
position: relative;
display: -ms-flexbox;
display: flex;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
-ms-flex-align: stretch;
align-items: stretch;
width: 100%;
}
.input-group-append {
margin-left: -1px;
}
.input-group-append, .input-group-prepend {
display: -ms-flexbox;
display: flex;
}
.input-group>.input-group-append>.btn, .input-group>.input-group-append>.input-group-text, .input-group>.input-group-prepend:first-child>.btn:not(:first-child), .input-group>.input-group-prepend:first-child>.input-group-text:not(:first-child), .input-group>.input-group-prepend:not(:first-child)>.btn, .input-group>.input-group-prepend:not(:first-child)>.input-group-text {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.input-group-text {
display: -ms-flexbox;
display: flex;
-ms-flex-align: center;
align-items: center;
padding: .375rem .75rem;
margin-bottom: 0;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #495057;
text-align: center;
white-space: nowrap;
background-color: #e9ecef;
border: 1px solid #ced4da;
border-radius: .25rem;
}
.input-group>.custom-select:not(:last-child), .input-group>.form-control:not(:last-child) {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.input-group>.custom-file, .input-group>.custom-select, .input-group>.form-control, .input-group>.form-control-plaintext {
position: relative;
-ms-flex: 1 1 0%;
flex: 1 1 0%;
min-width: 0;
margin-bottom: 0;
}
hr {
margin-top: 1rem;
margin-bottom: 1rem;
@@ -265,6 +431,23 @@ hr {
height: 0;
overflow: visible;
}
ul {
display: block;
list-style-type: disc;
margin-block-start: 1em;
margin-block-end: 1em;
margin-inline-start: 0px;
margin-inline-end: 0px;
padding-inline-start: 40px;
}
li {
display: list-item;
text-align: -webkit-match-parent;
}
dl, ol, ul {
margin-top: 0;
margin-bottom: 1rem;
}
@media (min-width: 576px) {
.container, .container-sm {
@@ -275,6 +458,11 @@ hr {
.container, .container-md, .container-sm {
max-width: 720px;
}
.col-md-3 {
-ms-flex: 0 0 25%;
flex: 0 0 25%;
max-width: 25%;
}
.col-md-4 {
-ms-flex: 0 0 33.333333%;
flex: 0 0 33.333333%;
@@ -285,6 +473,17 @@ hr {
flex: 0 0 50%;
max-width: 50%;
}
.d-md-flex {
display: -ms-flexbox!important;
display: flex!important;
}
.flex-md-row {
-ms-flex-direction: row!important;
flex-direction: row!important;
}
.ml-md-auto, .mx-md-auto {
margin-left: auto!important;
}
}
@media (min-width: 992px) {
.container, .container-lg, .container-md, .container-sm {

106
web/configmeter.html Normal file
View File

@@ -0,0 +1,106 @@
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AMS reader - Meter configuration</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" type="text/css" href="boot.css"/>
</head>
<body class="bg-light">
<main role="main" class="container">
<header class="navbar navbar-expand navbar-dark flex-column flex-md-row bg-purple rounded mt-2 mb-4" style="background-color: var(--purple);">
<a href="/" class=""><h6 class="navbar-brand">AMS reader <small>${version}</small></h6></a>
<div class="navbar-nav-scroll">
<ul class="navbar-nav bd-navbar-nav flex-row">
<li class="nav-item">
<a class="nav-link active" href="/config-meter">Meter</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-wifi">WiFi</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-mqtt">MQTT</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-web">Web</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-system">System</a>
</li>
</ul>
</div>
<ul class="navbar-nav flex-row ml-md-auto d-none d-md-flex">
<li class="nav-item">
<a class="nav-link p-2" href="https://github.com/gskjold/AmsToMqttBridge" target="_blank" rel="noopener" aria-label="GitHub">
<svg class="d-inline-block align-text-top" style="width: 2rem; height: 2rem;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 499.36" focusable="false"><title>GitHub</title><path d="M256 0C114.64 0 0 114.61 0 256c0 113.09 73.34 209 175.08 242.9 12.8 2.35 17.47-5.56 17.47-12.34 0-6.08-.22-22.18-.35-43.54-71.2 15.49-86.2-34.34-86.2-34.34-11.64-29.57-28.42-37.45-28.42-37.45-23.27-15.84 1.73-15.55 1.73-15.55 25.69 1.81 39.21 26.38 39.21 26.38 22.84 39.12 59.92 27.82 74.5 21.27 2.33-16.54 8.94-27.82 16.25-34.22-56.84-6.43-116.6-28.43-116.6-126.49 0-27.95 10-50.8 26.35-68.69-2.63-6.48-11.42-32.5 2.51-67.75 0 0 21.49-6.88 70.4 26.24a242.65 242.65 0 0 1 128.18 0c48.87-33.13 70.33-26.24 70.33-26.24 14 35.25 5.18 61.27 2.55 67.75 16.41 17.9 26.31 40.75 26.31 68.69 0 98.35-59.85 120-116.88 126.32 9.19 7.9 17.38 23.53 17.38 47.41 0 34.22-.31 61.83-.31 70.23 0 6.85 4.61 14.81 17.6 12.31C438.72 464.97 512 369.08 512 256.02 512 114.62 397.37 0 256 0z" fill="currentColor" fill-rule="evenodd"></path></svg>
</a>
</li>
</ul>
</header>
<form method="post" action="/save">
<input type="hidden" name="meterConfig" value="true"/>
<div class="my-3 p-3 bg-white rounded shadow">
<div class="row">
<div class="col-md-4">
<div class="row form-group">
<label class="col-6">Meter type</label>
<div class="col-6">
<select class="form-control" name="meterType">
<option value="0" ${config.meterType0}>Autodetect</option>
<option value="1" ${config.meterType1}>Kaifa</option>
<option value="2" ${config.meterType2}>Aidon</option>
<option value="3" ${config.meterType3}>Kamstrup</option>
</select>
</div>
</div>
<div class="row form-group">
<label class="col-6">Distribution system</label>
<div class="col-6">
<select class="form-control" name="distributionSystem">
<option value="0" ${config.distributionSystem0}></option>
<option value="1" ${config.distributionSystem1}>IT (230V)</option>
<option value="2" ${config.distributionSystem2}>TN (400V)</option>
</select>
</div>
</div>
</div>
<div class="col-md-4">
<div class="row form-group">
<label class="col-6">Main fuse</label>
<div class="col-6">
<select class="form-control" name="mainFuse">
<option value="0" ${config.mainFuse0}></option>
<option value="25" ${config.mainFuse25}>25A</option>
<option value="32" ${config.mainFuse32}>32A</option>
<option value="35" ${config.mainFuse32}>35A</option>
<option value="40" ${config.mainFuse40}>40A</option>
<option value="50" ${config.mainFuse50}>50A</option>
<option value="63" ${config.mainFuse63}>63A</option>
</select>
</div>
</div>
<div class="row form-group">
<label class="col-6">Production capacity</label>
<div class="col-6">
<div class="input-group">
<input class="form-control" name="productionCapacity" type="number" min="0" max="50" value="${config.productionCapacity}"/>
<div class="input-group-append"><span class="input-group-text">kWp</span></div>
</div>
</div>
</div>
</div>
</div>
</div>
<hr/>
<div class="row form-group">
<div class="col-6">
<a href="/" class="btn btn-outline-secondary">Back</a>
</div>
<div class="col-6 text-right">
<button class="btn btn-primary">Save</button>
</div>
</div>
</form>
</main>
</body>
</html>

128
web/configmqtt.html Normal file
View File

@@ -0,0 +1,128 @@
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AMS reader - WiFi configuration</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" type="text/css" href="boot.css"/>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body class="bg-light">
<main role="main" class="container">
<header class="navbar navbar-expand navbar-dark flex-column flex-md-row bg-purple rounded mt-2 mb-4" style="background-color: var(--purple);">
<a href="/" class=""><h6 class="navbar-brand">AMS reader <small>${version}</small></h6></a>
<div class="navbar-nav-scroll">
<ul class="navbar-nav bd-navbar-nav flex-row">
<li class="nav-item">
<a class="nav-link" href="/config-meter">Meter</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-wifi">WiFi</a>
</li>
<li class="nav-item">
<a class="nav-link active" href="/config-mqtt">MQTT</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-web">Web</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-system">System</a>
</li>
</ul>
</div>
<ul class="navbar-nav flex-row ml-md-auto d-none d-md-flex">
<li class="nav-item">
<a class="nav-link p-2" href="https://github.com/gskjold/AmsToMqttBridge" target="_blank" rel="noopener" aria-label="GitHub">
<svg class="d-inline-block align-text-top" style="width: 2rem; height: 2rem;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 499.36" focusable="false"><title>GitHub</title><path d="M256 0C114.64 0 0 114.61 0 256c0 113.09 73.34 209 175.08 242.9 12.8 2.35 17.47-5.56 17.47-12.34 0-6.08-.22-22.18-.35-43.54-71.2 15.49-86.2-34.34-86.2-34.34-11.64-29.57-28.42-37.45-28.42-37.45-23.27-15.84 1.73-15.55 1.73-15.55 25.69 1.81 39.21 26.38 39.21 26.38 22.84 39.12 59.92 27.82 74.5 21.27 2.33-16.54 8.94-27.82 16.25-34.22-56.84-6.43-116.6-28.43-116.6-126.49 0-27.95 10-50.8 26.35-68.69-2.63-6.48-11.42-32.5 2.51-67.75 0 0 21.49-6.88 70.4 26.24a242.65 242.65 0 0 1 128.18 0c48.87-33.13 70.33-26.24 70.33-26.24 14 35.25 5.18 61.27 2.55 67.75 16.41 17.9 26.31 40.75 26.31 68.69 0 98.35-59.85 120-116.88 126.32 9.19 7.9 17.38 23.53 17.38 47.41 0 34.22-.31 61.83-.31 70.23 0 6.85 4.61 14.81 17.6 12.31C438.72 464.97 512 369.08 512 256.02 512 114.62 397.37 0 256 0z" fill="currentColor" fill-rule="evenodd"></path></svg>
</a>
</li>
</ul>
</header>
<form method="post" action="/save">
<input type="hidden" name="mqttConfig" value="true"/>
<div class="my-3 p-3 bg-white rounded shadow">
<div class="row">
<div class="col-md-3">
<div class="row form-group">
<label class="col-4">Enable</label>
<div class="col-8">
<input id="mqttEnable" type="checkbox" name="mqtt" value="true" ${config.mqtt}/>
</div>
</div>
<div class="row form-group">
<label class="col-4">Payload</label>
<div class="col-8">
<select class="form-control mqtt-config" name="mqttPayloadFormat">
<option value="0" ${config.mqttPayloadFormat0}>JSON</option>
<option value="1" ${config.mqttPayloadFormat1}>Raw</option>
</select>
</div>
</div>
</div>
<div class="col-md-3">
<div class="row form-group">
<label class="col-4">Hostname</label>
<div class="col-8">
<input type="text" class="form-control mqtt-config" name="mqttHost" value="${config.mqttHost}"/>
</div>
</div>
<div class="row form-group">
<label class="col-4">Port</label>
<div class="col-8">
<input type="text" class="form-control mqtt-config" name="mqttPort" value="${config.mqttPort}"/>
</div>
</div>
</div>
<div class="col-md-3">
<div class="row form-group">
<label class="col-4">Client ID</label>
<div class="col-8">
<input type="text" class="form-control mqtt-config" name="mqttClientId" value="${config.mqttClientId}"/>
</div>
</div>
<div class="row form-group">
<label class="col-4">Topic</label>
<div class="col-8">
<input type="text" class="form-control mqtt-config" name="mqttPublishTopic" value="${config.mqttPublishTopic}"/>
</div>
</div>
</div>
<div class="col-md-3">
<div class="row form-group">
<label class="col-4">Username</label>
<div class="col-8">
<input type="text" class="form-control mqtt-config" name="mqttUser" value="${config.mqttUser}"/>
</div>
</div>
<div class="row form-group">
<label class="col-4">Password</label>
<div class="col-8">
<input type="password" class="form-control mqtt-config" name="mqttPassword" value="${config.mqttPassword}"/>
</div>
</div>
</div>
</div>
</div>
<hr/>
<div class="row form-group">
<div class="col-6">
<a href="/" class="btn btn-outline-secondary">Back</a>
</div>
<div class="col-6 text-right">
<button class="btn btn-primary">Save</button>
</div>
</div>
</form>
</main>
<script>
$('#mqttEnable').on('change', function() {
var inputs = $('.mqtt-config');
inputs.prop('disabled', !$(this).is(':checked'));
});
$(function() {
$('#mqttEnable').trigger('change');
});
</script>
</body>
</html>

99
web/configsystem.html Normal file
View File

@@ -0,0 +1,99 @@
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AMS reader - System configuration</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" type="text/css" href="boot.css"/>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css"/>
</head>
<body class="bg-light">
<main role="main" class="container">
<header class="navbar navbar-expand navbar-dark flex-column flex-md-row bg-purple rounded mt-2 mb-4" style="background-color: var(--purple);">
<a href="/" class=""><h6 class="navbar-brand">AMS reader <small>${version}</small></h6></a>
<div class="navbar-nav-scroll">
<ul class="navbar-nav bd-navbar-nav flex-row">
<li class="nav-item">
<a class="nav-link" href="/config-meter">Meter</a>
</li>
<li class="nav-item">
<a class="nav-link " href="/config-wifi">WiFi</a>
</li>
<li class="nav-item">
<a class="nav-link " href="/config-mqtt">MQTT</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-web">Web</a>
</li>
<li class="nav-item">
<a class="nav-link active" href="/config-system">System</a>
</li>
</ul>
</div>
<ul class="navbar-nav flex-row ml-md-auto d-none d-md-flex">
<li class="nav-item">
<a class="nav-link p-2" href="https://github.com/gskjold/AmsToMqttBridge" target="_blank" rel="noopener" aria-label="GitHub">
<svg class="d-inline-block align-text-top" style="width: 2rem; height: 2rem;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 499.36" focusable="false"><title>GitHub</title><path d="M256 0C114.64 0 0 114.61 0 256c0 113.09 73.34 209 175.08 242.9 12.8 2.35 17.47-5.56 17.47-12.34 0-6.08-.22-22.18-.35-43.54-71.2 15.49-86.2-34.34-86.2-34.34-11.64-29.57-28.42-37.45-28.42-37.45-23.27-15.84 1.73-15.55 1.73-15.55 25.69 1.81 39.21 26.38 39.21 26.38 22.84 39.12 59.92 27.82 74.5 21.27 2.33-16.54 8.94-27.82 16.25-34.22-56.84-6.43-116.6-28.43-116.6-126.49 0-27.95 10-50.8 26.35-68.69-2.63-6.48-11.42-32.5 2.51-67.75 0 0 21.49-6.88 70.4 26.24a242.65 242.65 0 0 1 128.18 0c48.87-33.13 70.33-26.24 70.33-26.24 14 35.25 5.18 61.27 2.55 67.75 16.41 17.9 26.31 40.75 26.31 68.69 0 98.35-59.85 120-116.88 126.32 9.19 7.9 17.38 23.53 17.38 47.41 0 34.22-.31 61.83-.31 70.23 0 6.85 4.61 14.81 17.6 12.31C438.72 464.97 512 369.08 512 256.02 512 114.62 397.37 0 256 0z" fill="currentColor" fill-rule="evenodd"></path></svg>
</a>
</li>
</ul>
</header>
<form method="post" action="/save">
<input type="hidden" name="sysConfig" value="true"/>
<div class="my-3 p-3 bg-white rounded shadow">
<div class="row">
<div class="col-md-3">
<label><input type="checkbox" name="debugTelnet" value="true" ${config.debugTelnet}/> Telnet debugger</label>
</div>
<div class="col-md-3">
<label><input type="checkbox" name="debugSerial" value="true" ${config.debugSerial}/> Serial debugger</label>
</div>
<div class="col-md-5">
<div class="row form-group">
<label class="col-6">Debug level</label>
<div class="col-6">
<select class="form-control" name="debugLevel">
<option value="2" ${config.debugLevel2}>Debug</option>
<option value="3" ${config.debugLevel3}>Info</option>
<option value="4" ${config.debugLevel4}>Warning</option>
<option value="5" ${config.debugLevel5}>Error</option>
</select>
</div>
</div>
</div>
<div class="col-md-1 text-right">
<button class="btn btn-primary">Save</button>
</div>
</div>
</div>
</form>
<form method="post" enctype="multipart/form-data">
<div class="my-3 p-3 bg-white rounded shadow">
<div class="alert alert-warning">!!WARNING!!<br/>Do not use this unless you know what you are doing. Uploading the wrong image could cause your device to stop working. Use with extreme caution!</div>
<div class="row">
<div class="col-md-4">
<div class="row form-group">
<label class="col-4">Firmware</label>
<div class="col-8">
<input type="file" name="file"/>
</div>
</div>
</div>
<div class="col-md-8 text-right">
<button class="btn btn-primary">Upload</button>
</div>
</div>
</div>
<hr/>
<div class="row form-group">
<div class="col-6">
<a href="/" class="btn btn-outline-secondary">Back</a>
</div>
<div class="col-6 text-right">
</div>
</div>
</form>
</main>
</body>
</html>

View File

@@ -1,184 +0,0 @@
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AMS reader - configuration</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" type="text/css" href="boot.css"/>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css"/>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<style>
.bg-purple {
background-color: var(--purple);
}
</style>
</head>
<body class="bg-light">
<main role="main" class="container">
<div class="d-flex align-items-center p-3 my-2 text-white-50 bg-purple rounded shadow">
<div class="lh-100">
<h6 class="mb-0 text-white lh-100">AMS reader - configuration</h6>
<small>${version}</small>
</div>
</div>
<form method="post" action="/save">
<div class="row">
<div class="col-md-6 col-lg-4">
<div class="my-2 p-3 bg-white rounded shadow">
<h6 class="border-bottom border-gray pb-2 mb-4">WiFi</h6>
<div class="row form-group">
<label class="col-3">SSID</label>
<div class="col-9">
<input type="text" class="form-control" name="ssid" value="${config.ssid}"/>
</div>
</div>
<div class="row form-group">
<label class="col-3">Password</label>
<div class="col-9">
<input type="password" class="form-control" name="ssidPassword" value="${config.ssidPassword}"/>
</div>
</div>
</div>
<div class="my-3 p-3 bg-white rounded shadow">
<h6 class="border-bottom border-gray pb-2 mb-4">AMS meter</h6>
<div class="row form-group">
<label class="col-6">Distribution system</label>
<div class="col-6">
<select class="form-control" name="distSys">
<option value="" ${config.distSys0}></option>
<option value="1" ${config.distSys1}>IT (230V)</option>
<option value="2" ${config.distSys2}>TN (400V)</option>
</select>
</div>
</div>
<div class="row form-group">
<label class="col-6">Meter type</label>
<div class="col-6">
<select class="form-control" name="meterType">
<option value="0" ${config.meterType0} disabled></option>
<option value="1" ${config.meterType1}>Kaifa</option>
<option value="2" ${config.meterType2}>Aidon</option>
<option value="3" ${config.meterType3}>Kamstrup</option>
</select>
</div>
</div>
<div class="row form-group">
<label class="col-6">Main fuse</label>
<div class="col-6">
<select class="form-control" name="fuseSize">
<option value="" ${config.fuseSize0}></option>
<option value="25" ${config.fuseSize25}>25A</option>
<option value="32" ${config.fuseSize32}>32A</option>
<option value="35" ${config.fuseSize32}>35A</option>
<option value="40" ${config.fuseSize40}>40A</option>
<option value="50" ${config.fuseSize50}>50A</option>
<option value="63" ${config.fuseSize63}>63A</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-6 col-lg-4">
<div class="my-2 p-3 bg-white rounded shadow">
<h6 class="border-bottom border-gray pb-2 mb-4">MQTT</h6>
<div class="row form-group">
<label class="col-4">Enable</label>
<div class="col-8">
<input id="mqttEnable" type="checkbox" name="mqtt" value="true" ${config.mqtt}/>
</div>
</div>
<div class="row form-group">
<label class="col-4">Hostname</label>
<div class="col-8">
<input type="text" class="form-control mqtt-config" name="mqttHost" value="${config.mqttHost}"/>
</div>
</div>
<div class="row form-group">
<label class="col-4">Port</label>
<div class="col-8">
<input type="text" class="form-control mqtt-config" name="mqttPort" value="${config.mqttPort}"/>
</div>
</div>
<div class="row form-group">
<label class="col-4">Client ID</label>
<div class="col-8">
<input type="text" class="form-control mqtt-config" name="mqttClientID" value="${config.mqttClientID}"/>
</div>
</div>
<div class="row form-group">
<label class="col-4">Topic</label>
<div class="col-8">
<input type="text" class="form-control mqtt-config" name="mqttPublishTopic" value="${config.mqttPublishTopic}"/>
</div>
</div>
<div class="row form-group">
<label class="col-4">Username</label>
<div class="col-8">
<input type="text" class="form-control mqtt-config" name="mqttUser" value="${config.mqttUser}"/>
</div>
</div>
<div class="row form-group">
<label class="col-4">Password</label>
<div class="col-8">
<input type="password" class="form-control mqtt-config" name="mqttPass" value="${config.mqttPass}"/>
</div>
</div>
</div>
</div>
<div class="col-md-6 col-lg-4">
<div class="my-2 p-3 bg-white rounded shadow">
<h6 class="border-bottom border-gray pb-2 mb-4">Web server</h6>
<div class="row form-group">
<label class="col-4">Security</label>
<div class="col-8">
<select id="authSecurity" class="form-control" name="authSecurity">
<option value="0" ${config.authSecurity0}>None</option>
<option value="1" ${config.authSecurity1}>Only configuration</option>
<option value="2" ${config.authSecurity2}>Everything</option>
</select>
</div>
</div>
<div class="row form-group">
<label class="col-4">Username</label>
<div class="col-8">
<input type="text" class="form-control auth-config" name="authUser" value="${config.authUser}"/>
</div>
</div>
<div class="row form-group">
<label class="col-4">Password</label>
<div class="col-8">
<input type="password" class="form-control auth-config" name="authPass" value="${config.authPass}"/>
</div>
</div>
</div>
</div>
</div>
<hr/>
<div class="row form-group">
<div class="col-6">
<a href="/" class="btn btn-outline-secondary">Back</a>
</div>
<div class="col-6 text-right">
<button class="btn btn-primary">Save</button>
</div>
</div>
</form>
</main>
<script>
$('#mqttEnable').on('change', function() {
var inputs = $('.mqtt-config');
inputs.prop('disabled', !$(this).is(':checked'));
});
$('#authSecurity').on('change', function() {
var inputs = $('.auth-config');
inputs.prop('disabled', $(this).val() == 0);
});
$(function() {
$('#mqttEnable').trigger('change');
$('#authSecurity').trigger('change');
});
</script>
</body>
</html>

97
web/configweb.html Normal file
View File

@@ -0,0 +1,97 @@
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AMS reader - Meter configuration</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" type="text/css" href="boot.css"/>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body class="bg-light">
<main role="main" class="container">
<header class="navbar navbar-expand navbar-dark flex-column flex-md-row bg-purple rounded mt-2 mb-4" style="background-color: var(--purple);">
<a href="/" class=""><h6 class="navbar-brand">AMS reader <small>${version}</small></h6></a>
<div class="navbar-nav-scroll">
<ul class="navbar-nav bd-navbar-nav flex-row">
<li class="nav-item">
<a class="nav-link" href="/config-meter">Meter</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-wifi">WiFi</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-mqtt">MQTT</a>
</li>
<li class="nav-item">
<a class="nav-link active" href="/config-web">Web</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-system">System</a>
</li>
</ul>
</div>
<ul class="navbar-nav flex-row ml-md-auto d-none d-md-flex">
<li class="nav-item">
<a class="nav-link p-2" href="https://github.com/gskjold/AmsToMqttBridge" target="_blank" rel="noopener" aria-label="GitHub">
<svg class="d-inline-block align-text-top" style="width: 2rem; height: 2rem;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 499.36" focusable="false"><title>GitHub</title><path d="M256 0C114.64 0 0 114.61 0 256c0 113.09 73.34 209 175.08 242.9 12.8 2.35 17.47-5.56 17.47-12.34 0-6.08-.22-22.18-.35-43.54-71.2 15.49-86.2-34.34-86.2-34.34-11.64-29.57-28.42-37.45-28.42-37.45-23.27-15.84 1.73-15.55 1.73-15.55 25.69 1.81 39.21 26.38 39.21 26.38 22.84 39.12 59.92 27.82 74.5 21.27 2.33-16.54 8.94-27.82 16.25-34.22-56.84-6.43-116.6-28.43-116.6-126.49 0-27.95 10-50.8 26.35-68.69-2.63-6.48-11.42-32.5 2.51-67.75 0 0 21.49-6.88 70.4 26.24a242.65 242.65 0 0 1 128.18 0c48.87-33.13 70.33-26.24 70.33-26.24 14 35.25 5.18 61.27 2.55 67.75 16.41 17.9 26.31 40.75 26.31 68.69 0 98.35-59.85 120-116.88 126.32 9.19 7.9 17.38 23.53 17.38 47.41 0 34.22-.31 61.83-.31 70.23 0 6.85 4.61 14.81 17.6 12.31C438.72 464.97 512 369.08 512 256.02 512 114.62 397.37 0 256 0z" fill="currentColor" fill-rule="evenodd"></path></svg>
</a>
</li>
</ul>
</header>
<form method="post" action="/save">
<input type="hidden" name="authConfig" value="true"/>
<div class="my-3 p-3 bg-white rounded shadow">
<div class="row">
<div class="col-md-4">
<div class="row form-group">
<label class="col-4">Security</label>
<div class="col-8">
<select id="authSecurity" class="form-control" name="authSecurity">
<option value="0" ${config.authSecurity0}>None</option>
<option value="1" ${config.authSecurity1}>Only configuration</option>
<option value="2" ${config.authSecurity2}>Everything</option>
</select>
</div>
</div>
</div>
<div class="col-md-4">
<div class="row form-group">
<label class="col-4">Username</label>
<div class="col-8">
<input type="text" class="form-control auth-config" name="authUser" value="${config.authUser}"/>
</div>
</div>
</div>
<div class="col-md-4">
<div class="row form-group">
<label class="col-4">Password</label>
<div class="col-8">
<input type="password" class="form-control auth-config" name="authPassword" value="${config.authPassword}"/>
</div>
</div>
</div>
</div>
</div>
<hr/>
<div class="row form-group">
<div class="col-6">
<a href="/" class="btn btn-outline-secondary">Back</a>
</div>
<div class="col-6 text-right">
<button class="btn btn-primary">Save</button>
</div>
</div>
</form>
</main>
<script>
$('#authSecurity').on('change', function() {
var inputs = $('.auth-config');
inputs.prop('disabled', $(this).val() == 0);
});
$(function() {
$('#authSecurity').trigger('change');
});
</script>
</body>
</html>

132
web/configwifi.html Normal file
View File

@@ -0,0 +1,132 @@
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AMS reader - WiFi configuration</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" type="text/css" href="boot.css"/>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body class="bg-light">
<main role="main" class="container">
<header class="navbar navbar-expand navbar-dark flex-column flex-md-row bg-purple rounded mt-2 mb-4" style="background-color: var(--purple);">
<a href="/" class=""><h6 class="navbar-brand">AMS reader <small>${version}</small></h6></a>
<div class="navbar-nav-scroll">
<ul class="navbar-nav bd-navbar-nav flex-row">
<li class="nav-item">
<a class="nav-link" href="/config-meter">Meter</a>
</li>
<li class="nav-item">
<a class="nav-link active" href="/config-wifi">WiFi</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-mqtt">MQTT</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-web">Web</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-system">System</a>
</li>
</ul>
</div>
<ul class="navbar-nav flex-row ml-md-auto d-none d-md-flex">
<li class="nav-item">
<a class="nav-link p-2" href="https://github.com/gskjold/AmsToMqttBridge" target="_blank" rel="noopener" aria-label="GitHub">
<svg class="d-inline-block align-text-top" style="width: 2rem; height: 2rem;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 499.36" focusable="false"><title>GitHub</title><path d="M256 0C114.64 0 0 114.61 0 256c0 113.09 73.34 209 175.08 242.9 12.8 2.35 17.47-5.56 17.47-12.34 0-6.08-.22-22.18-.35-43.54-71.2 15.49-86.2-34.34-86.2-34.34-11.64-29.57-28.42-37.45-28.42-37.45-23.27-15.84 1.73-15.55 1.73-15.55 25.69 1.81 39.21 26.38 39.21 26.38 22.84 39.12 59.92 27.82 74.5 21.27 2.33-16.54 8.94-27.82 16.25-34.22-56.84-6.43-116.6-28.43-116.6-126.49 0-27.95 10-50.8 26.35-68.69-2.63-6.48-11.42-32.5 2.51-67.75 0 0 21.49-6.88 70.4 26.24a242.65 242.65 0 0 1 128.18 0c48.87-33.13 70.33-26.24 70.33-26.24 14 35.25 5.18 61.27 2.55 67.75 16.41 17.9 26.31 40.75 26.31 68.69 0 98.35-59.85 120-116.88 126.32 9.19 7.9 17.38 23.53 17.38 47.41 0 34.22-.31 61.83-.31 70.23 0 6.85 4.61 14.81 17.6 12.31C438.72 464.97 512 369.08 512 256.02 512 114.62 397.37 0 256 0z" fill="currentColor" fill-rule="evenodd"></path></svg>
</a>
</li>
</ul>
</header>
<form method="post" action="/save">
<input type="hidden" name="wifiConfig" value="true"/>
<div class="my-3 p-3 bg-white rounded shadow">
<div class="row">
<div class="col-md-4">
<div class="row form-group">
<label class="col-3">SSID</label>
<div class="col-9">
<input type="text" class="form-control" name="wifiSsid" value="${config.wifiSsid}"/>
</div>
</div>
<div class="row form-group">
<label class="col-3">Password</label>
<div class="col-9">
<input type="password" class="form-control" name="wifiPassword" value="${config.wifiPassword}"/>
</div>
</div>
<div class="row form-group">
<label class="col-3">Hostname</label>
<div class="col-9">
<input type="text" class="form-control" name="wifiHostname" value="${config.wifiHostname}"/>
</div>
</div>
</div>
<div class="col-md-4">
<div class="row form-group">
<label class="col-6">IP configuration</label>
<div class="col-6">
<select id="wifiIpType" class="form-control" name="wifiIpType">
<option value="0" ${config.wifiIpType0}>DHCP</option>
<option value="1" ${config.wifiIpType1}>Static</option>
</select>
</div>
</div>
<div class="row form-group">
<label class="col-6">IP</label>
<div class="col-6">
<input type="text" class="form-control wifiip-config" name="wifiIp" value="${config.wifiIp}"/>
</div>
</div>
<div class="row form-group">
<label class="col-6">Subnet</label>
<div class="col-6">
<input type="text" class="form-control wifiip-config" name="wifiSubnet" value="${config.wifiSubnet}"/>
</div>
</div>
</div>
<div class="col-md-4">
<div class="row form-group">
<label class="col-6">Gateway</label>
<div class="col-6">
<input type="text" class="form-control wifiip-config" name="wifiGw" value="${config.wifiGw}"/>
</div>
</div>
<div class="row form-group">
<label class="col-6">Primary DNS</label>
<div class="col-6">
<input type="text" class="form-control wifiip-config" name="wifiDns1" value="${config.wifiDns1}"/>
</div>
</div>
<div class="row form-group">
<label class="col-6">Secondary DNS</label>
<div class="col-6">
<input type="text" class="form-control wifiip-config" name="wifiDns2" value="${config.wifiDns2}"/>
</div>
</div>
</div>
</div>
</div>
<hr/>
<div class="row form-group">
<div class="col-6">
<a href="/" class="btn btn-outline-secondary">Back</a>
</div>
<div class="col-6 text-right">
<button class="btn btn-primary">Save</button>
</div>
</div>
</form>
</main>
<script>
$('#wifiIpType').on('change', function() {
var inputs = $('.wifiip-config');
inputs.prop('disabled', $(this).val() != 1);
});
$(function() {
$('#wifiIpType').trigger('change');
});
</script>
</body>
</html>

View File

@@ -5,14 +5,10 @@
<title>AMS reader</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" type="text/css" href="boot.css"/>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css"/>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="gaugemeter.js"></script>
<style>
.bg-purple {
background-color: var(--purple);
}
.GaugeMeter {
position: Relative;
text-align: Center;
@@ -56,94 +52,260 @@
</head>
<body class="bg-light">
<main role="main" class="container">
<div class="d-flex align-items-center p-3 my-2 text-white-50 bg-purple rounded shadow">
<div class="lh-100">
<h6 class="mb-0 text-white lh-100">AMS reader</h6>
<small>${version}</small>
<header class="navbar navbar-expand navbar-dark flex-column flex-md-row rounded mt-2 mb-4" style="background-color: var(--purple);">
<a href="/" class=""><h6 class="navbar-brand">AMS reader <small>${version}</small></h6></a>
<div class="navbar-nav-scroll">
<ul class="navbar-nav bd-navbar-nav flex-row">
<li class="nav-item">
<a class="nav-link" href="/config-meter">Meter</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-wifi">WiFi</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-mqtt">MQTT</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-web">Web</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-system">System</a>
</li>
</ul>
</div>
</div>
<div class="flex-row ml-md-auto d-md-flex">
<div id="esp" class="d-none m-2">ESP</div>
<div id="han" class="d-none m-2">HAN</div>
<div id="wifi" class="d-none m-2">WiFi</div>
<div id="mqtt" class="d-none m-2">MQTT</div>
</div>
<ul class="navbar-nav flex-row ml-md-auto d-none d-md-flex">
<li class="nav-item">
<a class="nav-link p-2" href="https://github.com/gskjold/AmsToMqttBridge" target="_blank" rel="noopener" aria-label="GitHub">
<svg class="d-inline-block align-text-top" style="width: 2rem; height: 2rem;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 499.36" focusable="false"><title>GitHub</title><path d="M256 0C114.64 0 0 114.61 0 256c0 113.09 73.34 209 175.08 242.9 12.8 2.35 17.47-5.56 17.47-12.34 0-6.08-.22-22.18-.35-43.54-71.2 15.49-86.2-34.34-86.2-34.34-11.64-29.57-28.42-37.45-28.42-37.45-23.27-15.84 1.73-15.55 1.73-15.55 25.69 1.81 39.21 26.38 39.21 26.38 22.84 39.12 59.92 27.82 74.5 21.27 2.33-16.54 8.94-27.82 16.25-34.22-56.84-6.43-116.6-28.43-116.6-126.49 0-27.95 10-50.8 26.35-68.69-2.63-6.48-11.42-32.5 2.51-67.75 0 0 21.49-6.88 70.4 26.24a242.65 242.65 0 0 1 128.18 0c48.87-33.13 70.33-26.24 70.33-26.24 14 35.25 5.18 61.27 2.55 67.75 16.41 17.9 26.31 40.75 26.31 68.69 0 98.35-59.85 120-116.88 126.32 9.19 7.9 17.38 23.53 17.38 47.41 0 34.22-.31 61.83-.31 70.23 0 6.85 4.61 14.81 17.6 12.31C438.72 464.97 512 369.08 512 256.02 512 114.62 397.37 0 256 0z" fill="currentColor" fill-rule="evenodd"></path></svg>
</a>
</li>
</ul>
</header>
<div class="my-3 p-3 bg-white rounded shadow">
<h6 class="border-bottom border-gray pb-2 mb-4">Current meter values</h6>
<div class="row">
<div class="col-md-4">
<div class="col-md-3">
<div class="text-center">
<div id="P" class="SimpleMeter">
<div id="P" class="SimpleMeter" style="display: inline;">
${data.P} W
</div>
<div class="GaugeMeter rounded"
<div id="importMeter" class="GaugeMeter rounded"
style="display: none;"
data-size="200px"
data-text_size="0.11"
data-width="25"
data-style="Arch"
data-theme="Green-Gold-Red"
data-animationstep="0"
data-animate_gauge_colors="1"
data-percent="0"
data-text="-"
data-label="Consumption"
data-append="W"
data-size="200px"
data-text_size="0.11"
data-width="25"
data-style="Arch"
data-theme="Green-Gold-Red"
data-animationstep="0"
data-label="${text.import}"
></div>
</div>
</div>
<div class="col-md-4">
<div id="P1" class="row" style="display: ${display.P1}">
<div class="col-md-3">
<div id="U1-row" class="row" style="display: ${display.P1};">
<div class="col-2">P1</div>
<div class="col-5 text-right"><span id="U1">${data.U1}</span> V</div>
<div class="col-5 text-right"><span id="I1">${data.I1}</span> A</div>
</div>
<div id="P2" class="row" style="display: ${display.P2}">
<div id="U2-row" class="row" style="display: ${display.P2};">
<div class="col-2">P2</div>
<div class="col-5 text-right"><span id="U2">${data.U2}</span> V</div>
<div class="col-5 text-right"><span id="I2">${data.I2}</span> A</div>
</div>
<div id="P3" class="row" style="display: ${display.P3}">
<div id="U3-row" class="row" style="display: ${display.P3};">
<div class="col-2">P3</div>
<div class="col-5 text-right"><span id="U3">${data.U3}</span> V</div>
<div class="col-5 text-right"><span id="I3">${data.I3}</span> A</div>
</div>
<hr/>
<div id="tPI-row" class="row" style="display: ${display.accumulative};">
<div class="col-6">Active in</div>
<div class="col-6 text-right"><span id="tPI">${data.tPI}</span> kWh</div>
</div>
<div id="tPO-row" class="row" style="display: ${display.accumulative};">
<div class="col-6">Active out</div>
<div class="col-6 text-right"><span id="tPO">${data.tPO}</span> kWh</div>
</div>
<div id="tQI-row" class="row" style="display: ${display.accumulative};">
<div class="col-6">Reactive in</div>
<div class="col-6 text-right"><span id="tQI">${data.tQI}</span> kvarh</div>
</div>
<div id="tQO-row" class="row" style="display: ${display.accumulative};">
<div class="col-6">Reactive out</div>
<div class="col-6 text-right"><span id="tQO">${data.tQO}</span> kvarh</div>
</div>
</div>
<div class="col-md-3">
<div class="text-center" style="display: ${display.export};">
<div id="P" class="SimpleMeter" style="display: inline;">
${data.PO} W
</div>
<div id="exportMeter" class="GaugeMeter rounded"
style="display: none;"
data-size="200px"
data-text_size="0.11"
data-width="25"
data-style="Arch"
data-theme="DarkGreen-LightGreen"
data-animationstep="0"
data-label="Export"
></div>
</div>
</div>
</div>
<hr/>
<div class="row form-group">
<div class="col-6">
<a href="https://github.com/gskjold/AmsToMqttBridge/releases" class="btn btn-outline-secondary">Release notes</a>
</div>
<div class="col-6 text-right">
<a href="configuration" class="btn btn-primary">Configuration</a>
<div class="col-md-3">
<hr class="d-md-inline"/>
<div class="row">
<div class="col-6">Vcc</div>
<div class="col-6 text-right"><span id="vcc">${vcc}</span> V</div>
</div>
<div class="row" style="display: ${display.temp};">
<div class="col-6">Temperature</div>
<div class="col-6 text-right"><span id="temp">${temp}</span> °C</div>
</div>
<div class="row" style="display: none;">
<div class="col-6">Uptime</div>
<div class="col-6 text-right"><span id="currentMillis">${currentMillis}</span></div>
</div>
<hr/>
<div class="row">
<div class="col-6">SSID</div>
<div class="col-6 text-right"><span id="ssid">${wifi.ssid}</span></div>
</div>
<div class="row">
<div class="col-6">Channel</div>
<div class="col-6 text-right"><span id="channel">${wifi.channel}</span></div>
</div>
<div class="row">
<div class="col-6">RSSI</div>
<div class="col-6 text-right"><span id="rssi">${wifi.rssi}</span> dBm</div>
</div>
<hr class="d-none mqtt-error mqtt-error-1 mqtt-error-2 mqtt-error-3 mqtt-error-4 mqtt-error-5 mqtt-error-6 mqtt-error-7 mqtt-error-8 mqtt-error-9 mqtt-error-10 mqtt-error-11 mqtt-error-12 mqtt-error-13"/>
<div class="d-none badge badge-danger mqtt-error mqtt-error-1 mqtt-error-2 mqtt-error-5 mqtt-error-6 mqtt-error-7 mqtt-error-8 mqtt-error-9 mqtt-error-12">MQTT communication error (<span id="mqtt-lastError">-</span>)</div>
<div class="d-none badge badge-danger mqtt-error mqtt-error-3">MQTT failed to connect</div>
<div class="d-none badge badge-danger mqtt-error mqtt-error-4">MQTT network timeout</div>
<div class="d-none badge badge-danger mqtt-error mqtt-error-10">MQTT connection denied</div>
<div class="d-none badge badge-danger mqtt-error mqtt-error-11">MQTT failed to subscribe</div>
<div class="d-none badge badge-danger mqtt-error mqtt-error-13">MQTT lost connection</div>
</div>
</div>
</div>
</main>
<script>
$(".GaugeMeter").gaugeMeter();
var im = $("#importMeter")
im.gaugeMeter({
percent: 0,
text: "-",
append: "W"
});
var wait = 500;
var nextrefresh = wait;
var em = $("#exportMeter")
em.gaugeMeter({
percent: 0,
text: "-",
append: "W"
});
var setStatus = function(id, status) {
var item = $('#'+id);
item.removeClass('d-none');
item.removeClass (function (index, className) {
return (className.match (/(^|\s)badge-\S+/g) || []).join(' ');
});
item.addClass('badge badge-' + status);
};
var interval = 5000;
var fetch = function() {
$.ajax({
url: '/data.json',
timeout: 10000,
dataType: 'json',
}).done(function(json) {
$(".SimpleMeter").hide();
var el = $(".GaugeMeter");
el.show();
var rate = 2500;
if(json.data) {
el.data('percent', json.pct);
if(json.data.P) {
var num = parseFloat(json.data.P);
if(num > 1000) {
num = num / 1000;
el.data('text', num.toFixed(1));
el.data('append','kW');
im.show();
em.show();
for(var id in json) {
var str = json[id];
if(typeof str === "object")
continue;
if(isNaN(str)) {
$('#'+id).html(str);
} else {
var num = parseFloat(str);
$('#'+id).html(num.toFixed(num < 0 ? 0 : num < 10 ? 2 : 1));
}
}
if(window.moment) {
$('#currentMillis').html(moment.duration(parseInt(json.uptime_seconds), 'seconds').humanize());
$('#currentMillis').closest('.row').show();
}
if(json.status) {
for(var id in json.status) {
setStatus(id, json.status[id]);
}
}
if(json.mqtt) {
$('.mqtt-error').addClass('d-none');
$('.mqtt-error'+json.mqtt.lastError).removeClass('d-none');
$('#mqtt-lastError').html(json.mqtt.lastError);
}
if(json.wifi) {
for(var id in json.wifi) {
var str = json.wifi[id];
dst = $('#'+id);
if(isNaN(str)) {
dst.html(str);
} else {
el.data('text', num);
el.data('append','W');
var num = parseFloat(str);
dst.html(num.toFixed(0));
$('#'+id+'-row').show();
}
}
el.gaugeMeter();
}
if(json.data) {
var p = 0;
var p_pct = parseInt(json.p_pct);
var p_append = "W";
if(json.data.P) {
p = parseFloat(json.data.P);
if(p > 1000) {
p = (p/1000).toFixed(1);
p_append = "kW";
}
}
im.gaugeMeter({
percent: p_pct,
text: p,
append: p_append
});
var po = 0;
var po_pct = parseInt(json.po_pct);
var po_append = "W";
if(json.data.PO) {
po = parseFloat(json.data.PO);
if(po > 1000) {
po = (po/1000).toFixed(1);
po_append = "kW";
}
}
em.gaugeMeter({
percent: po_pct,
text: po,
append: po_append
});
for(var id in json.data) {
var str = json.data[id];
@@ -152,48 +314,45 @@ var fetch = function() {
} else {
var num = parseFloat(str);
$('#'+id).html(num.toFixed(1));
$('#'+id+'-row').show();
}
}
if(json.data.U1 > 0) {
$('#P1').show();
}
if(json.data.U2 > 0) {
$('#P2').show();
}
if(json.data.U3 > 0) {
$('#P3').show();
}
if(json.meterType == 3) {
rate = 10000;
}
if(json.currentMillis && json.up) {
nextrefresh = rate - ((json.currentMillis - json.up) % rate) + wait;
} else {
nextrefresh = 2500;
}
} else {
el.data('percent', 0);
el.data('text', '-');
el.gaugeMeter();
nextrefresh = 2500;
im.gaugeMeter({
percent: 0,
text: "-",
append: "W"
});
em.gaugeMeter({
percent: 0,
text: "-",
append: "W"
});
}
if(!nextrefresh || nextrefresh < 500) {
nextrefresh = 2500;
}
setTimeout(fetch, nextrefresh);
setTimeout(fetch, interval);
}).fail(function() {
el.data('percent', 0);
el.data('text', '-');
el.gaugeMeter();
nextrefresh = 10000;
setTimeout(fetch, nextrefresh);
setTimeout(fetch, interval*4);
im.gaugeMeter({
percent: 0,
text: "-",
append: "W"
});
em.gaugeMeter({
percent: 0,
text: "-",
append: "W"
});
setStatus("mqtt", "secondary");
setStatus("wifi", "secondary");
setStatus("han", "secondary");
setStatus("esp", "danger");
});
}
setTimeout(fetch, nextrefresh);
fetch();
</script>
</body>
</html>

76
web/restartwait.html Normal file
View File

@@ -0,0 +1,76 @@
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AMS reader - Meter configuration</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" type="text/css" href="boot.css"/>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body class="bg-light">
<main role="main" class="container">
<header class="navbar navbar-expand navbar-dark flex-column flex-md-row bg-purple rounded mt-2 mb-4" style="background-color: var(--purple);">
<a href="/" class=""><h6 class="navbar-brand">AMS reader <small>${version}</small></h6></a>
<div class="navbar-nav-scroll">
<ul class="navbar-nav bd-navbar-nav flex-row">
<li class="nav-item">
<a class="nav-link" href="/config-meter">Meter</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-wifi">WiFi</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-mqtt">MQTT</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-web">Web</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/config-system">System</a>
</li>
</ul>
</div>
<ul class="navbar-nav flex-row ml-md-auto d-none d-md-flex">
<li class="nav-item">
<a class="nav-link p-2" href="https://github.com/gskjold/AmsToMqttBridge" target="_blank" rel="noopener" aria-label="GitHub">
<svg class="d-inline-block align-text-top" style="width: 2rem; height: 2rem;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 499.36" focusable="false"><title>GitHub</title><path d="M256 0C114.64 0 0 114.61 0 256c0 113.09 73.34 209 175.08 242.9 12.8 2.35 17.47-5.56 17.47-12.34 0-6.08-.22-22.18-.35-43.54-71.2 15.49-86.2-34.34-86.2-34.34-11.64-29.57-28.42-37.45-28.42-37.45-23.27-15.84 1.73-15.55 1.73-15.55 25.69 1.81 39.21 26.38 39.21 26.38 22.84 39.12 59.92 27.82 74.5 21.27 2.33-16.54 8.94-27.82 16.25-34.22-56.84-6.43-116.6-28.43-116.6-126.49 0-27.95 10-50.8 26.35-68.69-2.63-6.48-11.42-32.5 2.51-67.75 0 0 21.49-6.88 70.4 26.24a242.65 242.65 0 0 1 128.18 0c48.87-33.13 70.33-26.24 70.33-26.24 14 35.25 5.18 61.27 2.55 67.75 16.41 17.9 26.31 40.75 26.31 68.69 0 98.35-59.85 120-116.88 126.32 9.19 7.9 17.38 23.53 17.38 47.41 0 34.22-.31 61.83-.31 70.23 0 6.85 4.61 14.81 17.6 12.31C438.72 464.97 512 369.08 512 256.02 512 114.62 397.37 0 256 0z" fill="currentColor" fill-rule="evenodd"></path></svg>
</a>
</li>
</ul>
</header>
<div class="my-3 p-3 bg-white rounded shadow">
Device is rebooting. You will be redirected to the main page when it is available again.
</div>
</main>
<script>
var tries = 0;
var ip = "${ip}";
var hostname = "${hostname}";
var url;
var fetch = function() {
tries++;
if(ip && tries%3 == 0) {
url = "http://" + ip;
} else if(hostname && tries%3 == 1) {
url = "http://" + hostname;
} else if(hostname && tries%3 == 2) {
url = "http://" + hostname + ".local";
} else {
url = "";
}
if(console) console.log("Trying url " + url)
$.ajax({
url: url + '/is-alive',
timeout: 5000
}).done(function(json) {
window.location.href = url ? url : "/";
}).fail(function() {
setTimeout(fetch, 1000);
});
};
setTimeout(fetch, 10000);
</script>
</body>
</html>

BIN
webui.jpg

Binary file not shown.

Before

Width:  |  Height:  |  Size: 336 KiB

After

Width:  |  Height:  |  Size: 333 KiB