bdew-api 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bdew_api/__init__.py +10 -0
- bdew_api/__main__.py +67 -0
- bdew_api/answer_state_handler.py +141 -0
- bdew_api/answer_state_server.py +95 -0
- bdew_api/bdew.py +133 -0
- bdew_api/control_demand_handler.py +92 -0
- bdew_api/control_demand_server.py +124 -0
- bdew_api/id_generator.py +159 -0
- bdew_api/tls_config.py +89 -0
- bdew_api/utils.py +148 -0
- bdew_api-0.1.1.dist-info/METADATA +171 -0
- bdew_api-0.1.1.dist-info/RECORD +16 -0
- bdew_api-0.1.1.dist-info/WHEEL +5 -0
- bdew_api-0.1.1.dist-info/entry_points.txt +2 -0
- bdew_api-0.1.1.dist-info/licenses/LICENSE +201 -0
- bdew_api-0.1.1.dist-info/top_level.txt +1 -0
bdew_api/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
2
|
+
|
|
3
|
+
from bdew_api import bdew
|
|
4
|
+
from bdew_api import answer_state_handler
|
|
5
|
+
from bdew_api import answer_state_server
|
|
6
|
+
from bdew_api import control_demand_handler
|
|
7
|
+
from bdew_api import control_demand_server
|
|
8
|
+
from bdew_api import id_generator
|
|
9
|
+
from bdew_api import tls_config
|
|
10
|
+
from bdew_api import utils
|
bdew_api/__main__.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import argparse
|
|
3
|
+
import socket
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
from bdew_api.bdew import BDEW
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _wait_until_listening(host: str, port: int, timeout: float = 5.0) -> bool:
|
|
10
|
+
"""Wait until a server accepts TCP connections (servers start in background threads)."""
|
|
11
|
+
deadline = time.monotonic() + timeout
|
|
12
|
+
while time.monotonic() < deadline:
|
|
13
|
+
try:
|
|
14
|
+
with socket.create_connection((host, port), timeout=0.5):
|
|
15
|
+
return True
|
|
16
|
+
except OSError:
|
|
17
|
+
time.sleep(0.1)
|
|
18
|
+
return False
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
#aemt_id: str, aemt_host: str, aemt_port: int, pemt_id:str, pemt_host: str, pemt_port: int
|
|
22
|
+
def main():
|
|
23
|
+
parser = argparse.ArgumentParser(description='establish bdew api communication')
|
|
24
|
+
parser.add_argument('aemt_id',
|
|
25
|
+
metavar='aemt_id',
|
|
26
|
+
type=str,
|
|
27
|
+
help='id of the aemt component')
|
|
28
|
+
parser.add_argument('aemt_host',
|
|
29
|
+
metavar='aemt_host',
|
|
30
|
+
type=str,
|
|
31
|
+
help='host of the aemt component')
|
|
32
|
+
parser.add_argument('aemt_port',
|
|
33
|
+
metavar='aemt_port',
|
|
34
|
+
type=int,
|
|
35
|
+
help='port of the aemt component')
|
|
36
|
+
parser.add_argument('pemt_id',
|
|
37
|
+
metavar='pemt_id',
|
|
38
|
+
type=str,
|
|
39
|
+
help='id of the pemt component')
|
|
40
|
+
parser.add_argument('pemt_host',
|
|
41
|
+
metavar='pemt_host',
|
|
42
|
+
type=str,
|
|
43
|
+
help='host of the pemt component')
|
|
44
|
+
parser.add_argument('pemt_port',
|
|
45
|
+
metavar='pemt_port',
|
|
46
|
+
type=int,
|
|
47
|
+
help='port of the pemt component')
|
|
48
|
+
|
|
49
|
+
argvs = sys.argv
|
|
50
|
+
aemt_id = argvs[1]
|
|
51
|
+
aemt_host = argvs[2]
|
|
52
|
+
aemt_port = int(argvs[3])
|
|
53
|
+
pemt_id = argvs[4]
|
|
54
|
+
pemt_host = argvs[5]
|
|
55
|
+
pemt_port = int(argvs[6])
|
|
56
|
+
bdew = BDEW(aemt_id,aemt_host,aemt_port,pemt_id,pemt_host,pemt_port)
|
|
57
|
+
# Demo of both sides in one process: wait for the servers that did start
|
|
58
|
+
# (a side without TLS material stays inactive and only logs warnings).
|
|
59
|
+
for server, host, port in ((bdew.control_demand_server, aemt_host, aemt_port),
|
|
60
|
+
(bdew.answer_state_server, pemt_host, pemt_port)):
|
|
61
|
+
if server.ssl_context is not None and not _wait_until_listening(host, port):
|
|
62
|
+
print(f"server on {host}:{port} did not come up", file=sys.stderr)
|
|
63
|
+
bdew.send_control_request(None,None)
|
|
64
|
+
bdew.send_control_status("positive")
|
|
65
|
+
|
|
66
|
+
if __name__ == "__main__":
|
|
67
|
+
main()
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
from bdew_api.utils import setup_logger
|
|
2
|
+
from bdew_api import id_generator as id_gen
|
|
3
|
+
#formerly PEMTHandler
|
|
4
|
+
# API between aEMT and pEMT:
|
|
5
|
+
# the pEMT reports the need for a regulation command to the aEMT
|
|
6
|
+
# (the aEMT requests the regulation command, sends the request to the GWA;
|
|
7
|
+
# the SMGW establishes the CLS channel to the controlbox).
|
|
8
|
+
# The aEMT answers with the delivery status of the command request
|
|
9
|
+
# (delivered successfully or not delivered).
|
|
10
|
+
# The API implements BNetzA-Beschluss BK6-22-128.
|
|
11
|
+
# Specs: openapi 3.0.0, version 1.0.0, title: EDI@Energy API-Webdienste zur
|
|
12
|
+
# prozessualen Abwicklung von Steuerungshandlungen in Verbindung mit
|
|
13
|
+
# intelligenten Messsystemen (iMS) - Universalbestellprozess
|
|
14
|
+
|
|
15
|
+
class AnswerStateHandler:
|
|
16
|
+
def __init__(self, aemt_id: str, pemt_id:str, pemt_host: str, pemt_port: int, logic_callback,
|
|
17
|
+
session=None):
|
|
18
|
+
self.aemt_id = aemt_id
|
|
19
|
+
self.pemt_id = pemt_id
|
|
20
|
+
# Answers go to the pEMT's IP — BDEW MP-IDs are not resolvable
|
|
21
|
+
# hostnames, so the pEMT id cannot be used as the URL host.
|
|
22
|
+
self.pemt_host = pemt_host
|
|
23
|
+
self.pemt_port = pemt_port
|
|
24
|
+
# Setup logging
|
|
25
|
+
self.logger = setup_logger("PEMT", aemt_id)
|
|
26
|
+
self.logic_callback = logic_callback
|
|
27
|
+
# Mutual-TLS client session (tls_config.requests_session); None = TLS setup failed
|
|
28
|
+
self.session = session
|
|
29
|
+
|
|
30
|
+
def send_answer(self,result: object):
|
|
31
|
+
if self.session is None:
|
|
32
|
+
self.logger.warning("Answer not sent — no TLS session (TLS setup failed).")
|
|
33
|
+
return None
|
|
34
|
+
self.logger.info("━" * 100)
|
|
35
|
+
self.logger.info(" " * 44 + "PEMT Handler")
|
|
36
|
+
self.logger.info("━" * 100)
|
|
37
|
+
|
|
38
|
+
self.logger.info(
|
|
39
|
+
f"Sending answer to {self.pemt_id}:{self.pemt_port} - Control Signal status")
|
|
40
|
+
|
|
41
|
+
id_generator = id_gen.IDGenerator
|
|
42
|
+
# ID format: string($UUID RFC4122)
|
|
43
|
+
# transactionId: external, unique — information about the control
|
|
44
|
+
# command confirmed by the GWA
|
|
45
|
+
transaction_id = id_generator.generate_transaction_id()
|
|
46
|
+
# Time of this call
|
|
47
|
+
creation_date_time = id_generator.generate_datetimestamp()
|
|
48
|
+
# In case of a retry, the idempotency key
|
|
49
|
+
initial_transaction_id = transaction_id
|
|
50
|
+
# External, previous reference (the original control command);
|
|
51
|
+
# value taken from transactionId of step 1 of the use case
|
|
52
|
+
# "control command from NB/LF to MSB"
|
|
53
|
+
reference_id = transaction_id
|
|
54
|
+
# locationId: identifies the resource the control command acts on
|
|
55
|
+
# (e.g. "C1234848431" — a control box)
|
|
56
|
+
location_id = id_generator.generate_location_id()
|
|
57
|
+
partner_id = id_generator.generate_partner_id()
|
|
58
|
+
|
|
59
|
+
if result == "positive":
|
|
60
|
+
result_json = {"statePositive": "succeeded"}
|
|
61
|
+
self.logger.info(
|
|
62
|
+
f"Sending positive answer to {self.pemt_id}:{self.pemt_port} - Control Signal arrived at Control Box.")
|
|
63
|
+
elif result == "preliminary_positive":
|
|
64
|
+
result_json = {"preliminaryResultPositive": "possible"}
|
|
65
|
+
# Positive answer: the control command can in principle be executed.
|
|
66
|
+
self.logger.info(
|
|
67
|
+
f"Sending preliminary positive answer to {self.pemt_id}:{self.pemt_port} - Control Signal is able to "
|
|
68
|
+
f"arrive at Control Box.")
|
|
69
|
+
elif result == "preliminary_negative":
|
|
70
|
+
# Negative answer: the control command cannot be executed.
|
|
71
|
+
# reasonNegative gives the reason: communicationFailure = link to
|
|
72
|
+
# the control box disrupted, overload = MSB backend overloaded,
|
|
73
|
+
# unable = MSB procedurally unable to fulfil the request
|
|
74
|
+
# (e.g. maintenance).
|
|
75
|
+
result_json = {"stateNegative": "failed",
|
|
76
|
+
"reasonNegative": "communicationFailure"}
|
|
77
|
+
self.logger.info(
|
|
78
|
+
f"Sending preliminary negative answer to {self.pemt_id}:{self.pemt_port} - Control Signal failed to "
|
|
79
|
+
f"arrive at Control Box.")
|
|
80
|
+
elif result == "negative":
|
|
81
|
+
result_json = {
|
|
82
|
+
"stateNegative": "failed",
|
|
83
|
+
"reasonNegative": "communicationFailure"}
|
|
84
|
+
self.logger.info(
|
|
85
|
+
f"Sending negative answer to {self.pemt_id}:{self.pemt_port} - Control Signal did not arrive at Control"
|
|
86
|
+
f" Box.")
|
|
87
|
+
elif result == "unknown":
|
|
88
|
+
result_json = {
|
|
89
|
+
"stateUnknown": "unknown"
|
|
90
|
+
}
|
|
91
|
+
self.logger.info(
|
|
92
|
+
f"Sending unknown answer to {self.pemt_id}:{self.pemt_port} - Final status of Control Signal unknown.")
|
|
93
|
+
else:
|
|
94
|
+
command_control = {
|
|
95
|
+
"maximumPowerValue": "24.123",
|
|
96
|
+
"executionTimeFrom": "2023-08-01T12:30:00Z",
|
|
97
|
+
"executionTimeUntil": "2023-08-01T12:30:00Z"
|
|
98
|
+
}
|
|
99
|
+
command_regular = {
|
|
100
|
+
"executionTimeFrom": "2023-08-01T12:30:00Z"
|
|
101
|
+
}
|
|
102
|
+
self.logger.info(
|
|
103
|
+
f"Sending information about answer to {self.pemt_id}:{self.pemt_port} - Begin and End of Control.")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
try:
|
|
107
|
+
#build header and query for http request
|
|
108
|
+
headers = {'transactionId':transaction_id, 'creationDateTime':creation_date_time,
|
|
109
|
+
'initialTransactionId':initial_transaction_id}
|
|
110
|
+
if result == "positive":
|
|
111
|
+
query = {'referenceId':reference_id,'locationId':location_id,'resultPositive':result_json}
|
|
112
|
+
url = f"https://{self.pemt_host}:{self.pemt_port}/positive-answer"
|
|
113
|
+
elif result == "preliminary_positive":
|
|
114
|
+
query = {'referenceId':reference_id,'locationId':location_id,'preliminaryResultPositive':result_json}
|
|
115
|
+
url = f"https://{self.pemt_host}:{self.pemt_port}/preliminary-positive-answer"
|
|
116
|
+
elif result == "preliminary_negative":
|
|
117
|
+
query = {'referenceId':reference_id,'locationId':location_id,'preliminaryResultNegative':result_json}
|
|
118
|
+
url = f"https://{self.pemt_host}:{self.pemt_port}/preliminary-negative-answer"
|
|
119
|
+
elif result == "negative":
|
|
120
|
+
query = {'referenceId': reference_id, 'locationId': location_id, 'resultNegative': result_json}
|
|
121
|
+
url = f"https://{self.pemt_host}:{self.pemt_port}/negative-answer"
|
|
122
|
+
elif result == "unknown":
|
|
123
|
+
query = {'referenceId': reference_id, 'locationId': location_id, 'stateUnknown': result_json}
|
|
124
|
+
url = f"https://{self.pemt_host}:{self.pemt_port}/unknown-answer"
|
|
125
|
+
else:
|
|
126
|
+
query = {'referenceId': reference_id, 'locationId': location_id, "partnerId": partner_id,
|
|
127
|
+
'commandControl': command_control, 'commandRegular': command_regular}
|
|
128
|
+
url = f"https://{self.pemt_host}:{self.pemt_port}/information-control-signal"
|
|
129
|
+
|
|
130
|
+
# POST to the pEMT (HTTPS)
|
|
131
|
+
response = self.session.post(
|
|
132
|
+
url,
|
|
133
|
+
headers=headers,
|
|
134
|
+
json=query,
|
|
135
|
+
timeout=5,
|
|
136
|
+
)
|
|
137
|
+
self.logger.info(f"Answer sent to pEMT ({url}), HTTP {response.status_code}.")
|
|
138
|
+
|
|
139
|
+
except Exception as e:
|
|
140
|
+
self.logger.error(f"PEMT-Answer error: {e}")
|
|
141
|
+
return None
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
from bdew_api.utils import setup_logger
|
|
2
|
+
from flask import Flask, request, jsonify
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
import threading
|
|
5
|
+
|
|
6
|
+
#formerly AnswerServer
|
|
7
|
+
# Answer endpoint of the pEMT (EDI@Energy Universalbestellprozess,
|
|
8
|
+
# BNetzA-Beschluss BK6-22-128).
|
|
9
|
+
#
|
|
10
|
+
# After the pEMT reported a control demand via the aEMT's BDEW API, the aEMT
|
|
11
|
+
# answers here with the delivery status of the control command:
|
|
12
|
+
# POST /preliminary-positive-answer — command can be executed
|
|
13
|
+
# POST /preliminary-negative-answer — command cannot be executed
|
|
14
|
+
# POST /positive-answer — command arrived at the controlbox
|
|
15
|
+
# POST /negative-answer — command did not arrive
|
|
16
|
+
# POST /unknown-answer — final status unknown
|
|
17
|
+
# POST /information-control-signal — begin/end of the control action
|
|
18
|
+
|
|
19
|
+
_ANSWER_ROUTES = (
|
|
20
|
+
"positive-answer",
|
|
21
|
+
"preliminary-positive-answer",
|
|
22
|
+
"preliminary-negative-answer",
|
|
23
|
+
"negative-answer",
|
|
24
|
+
"unknown-answer",
|
|
25
|
+
"information-control-signal",
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class AnswerStateServer:
|
|
30
|
+
def __init__(self, pemt_id: str, host: str, port: int, logic_callback=None,
|
|
31
|
+
ssl_context=None) -> None:
|
|
32
|
+
"""
|
|
33
|
+
Args:
|
|
34
|
+
pemt_id: ID of this pEMT (13-digit BDEW MP-ID)
|
|
35
|
+
host: bind address
|
|
36
|
+
port: HTTPS port for the aEMT's answers (pEMT range, :8202)
|
|
37
|
+
logic_callback: optional, called as logic_callback(route, body)
|
|
38
|
+
for every received answer
|
|
39
|
+
ssl_context: mutual-TLS server context (tls_config.server_context);
|
|
40
|
+
without one the server does not start
|
|
41
|
+
"""
|
|
42
|
+
self.pemt_id = pemt_id
|
|
43
|
+
self.host = host
|
|
44
|
+
self.port = port
|
|
45
|
+
self.logic_callback = logic_callback
|
|
46
|
+
self.ssl_context = ssl_context
|
|
47
|
+
|
|
48
|
+
self.logger = setup_logger("AnswerStateServer", pemt_id)
|
|
49
|
+
|
|
50
|
+
self.app = Flask(__name__)
|
|
51
|
+
self._setup_flask_routes()
|
|
52
|
+
|
|
53
|
+
def start(self):
|
|
54
|
+
if self.ssl_context is None:
|
|
55
|
+
self.logger.warning("Answer state server not started — no TLS context (TLS setup failed).")
|
|
56
|
+
return
|
|
57
|
+
flask_thread = threading.Thread(target=self._run_https_server, daemon=True)
|
|
58
|
+
flask_thread.start()
|
|
59
|
+
self.logger.info(f"BDEW answer endpoint listening on {self.host}:{self.port} (HTTPS)")
|
|
60
|
+
|
|
61
|
+
def _setup_flask_routes(self):
|
|
62
|
+
def _make_handler(route: str):
|
|
63
|
+
def handler():
|
|
64
|
+
body = request.get_json(silent=True) or {}
|
|
65
|
+
self.logger.info(
|
|
66
|
+
f"aEMT answer '{route}' received "
|
|
67
|
+
f"(referenceId={body.get('referenceId')}, locationId={body.get('locationId')})"
|
|
68
|
+
)
|
|
69
|
+
self.logger.debug(f"Answer body: {body}")
|
|
70
|
+
if self.logic_callback is not None:
|
|
71
|
+
self.logic_callback(route, body)
|
|
72
|
+
return jsonify({"status": "received"}), 200
|
|
73
|
+
return handler
|
|
74
|
+
|
|
75
|
+
for route in _ANSWER_ROUTES:
|
|
76
|
+
self.app.add_url_rule(
|
|
77
|
+
f"/{route}", endpoint=route, view_func=_make_handler(route), methods=["POST"]
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
@self.app.route("/health", methods=["GET"])
|
|
81
|
+
def health():
|
|
82
|
+
return jsonify({"status": "HEALTHY", "timestamp": datetime.now().isoformat()}), 200
|
|
83
|
+
|
|
84
|
+
def _run_https_server(self):
|
|
85
|
+
try:
|
|
86
|
+
self.app.run(
|
|
87
|
+
host=self.host,
|
|
88
|
+
port=self.port,
|
|
89
|
+
ssl_context=self.ssl_context,
|
|
90
|
+
debug=False,
|
|
91
|
+
use_reloader=False,
|
|
92
|
+
threaded=True,
|
|
93
|
+
)
|
|
94
|
+
except Exception as e:
|
|
95
|
+
self.logger.error(f"Answer state server failure: {e}")
|
bdew_api/bdew.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
from bdew_api import answer_state_handler
|
|
2
|
+
from bdew_api import answer_state_server
|
|
3
|
+
from bdew_api import control_demand_handler
|
|
4
|
+
from bdew_api import control_demand_server
|
|
5
|
+
from bdew_api import id_generator
|
|
6
|
+
from bdew_api import tls_config
|
|
7
|
+
from bdew_api import utils
|
|
8
|
+
|
|
9
|
+
ROLE_AEMT = "aemt"
|
|
10
|
+
ROLE_PEMT = "pemt"
|
|
11
|
+
ROLE_BOTH = "both"
|
|
12
|
+
_ROLES = (ROLE_AEMT, ROLE_PEMT, ROLE_BOTH)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class BDEW:
|
|
16
|
+
"""BDEW API between pEMT and aEMT (Universalbestellprozess, BK6-22-128).
|
|
17
|
+
|
|
18
|
+
Each side only runs its own half of the API:
|
|
19
|
+
|
|
20
|
+
* ``role="aemt"`` — serves control demands on ``aemt_host:aemt_port`` and
|
|
21
|
+
sends the delivery-status answers to ``pemt_host:pemt_port``.
|
|
22
|
+
* ``role="pemt"`` — serves the answers on ``pemt_host:pemt_port`` and sends
|
|
23
|
+
control demands to ``aemt_host:aemt_port``.
|
|
24
|
+
* ``role="both"`` — both halves in one process (local demo / tests).
|
|
25
|
+
|
|
26
|
+
So for the own side the host is the bind address, for the other side it is
|
|
27
|
+
the address to send to.
|
|
28
|
+
|
|
29
|
+
Callbacks:
|
|
30
|
+
control_demand_callback(location_id, command, kind, remote_addr) — aEMT
|
|
31
|
+
side, for every validated control demand (kind: "control" | "regular").
|
|
32
|
+
answer_callback(route, body) — pEMT side, for every answer of the aEMT.
|
|
33
|
+
|
|
34
|
+
With ``answer_to_sender=True`` (aEMT side) the answers go to the address
|
|
35
|
+
the last control demand came from instead of the fixed ``pemt_host``, so
|
|
36
|
+
the aEMT does not need to know the pEMT's IP up front.
|
|
37
|
+
|
|
38
|
+
TLS (both legs, see :mod:`bdew_api.tls_config`): mutually authenticated
|
|
39
|
+
TLS 1.2 with the TR-03116-3 profile. Each side uses its own certificate —
|
|
40
|
+
``aemt_certfile``/``aemt_keyfile`` and ``pemt_certfile``/``pemt_keyfile``,
|
|
41
|
+
by default ``aemt-cert.pem``/``aemt-key.pem`` and ``pemt-cert.pem``/
|
|
42
|
+
``pemt-key.pem`` in the working directory — and both verify the peer
|
|
43
|
+
against ``cafile`` (default ``wan-ca.pem``). If a side's TLS material
|
|
44
|
+
cannot be loaded, a warning is logged and that side stays inactive: its
|
|
45
|
+
server does not start and its requests are not sent (each logs why).
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, aemt_id: str, aemt_host: str, aemt_port: int, pemt_id: str, pemt_host: str, pemt_port: int,
|
|
49
|
+
role: str = ROLE_BOTH, control_demand_callback=None, answer_callback=None,
|
|
50
|
+
answer_to_sender: bool = False, autostart: bool = True,
|
|
51
|
+
aemt_certfile: str = None, aemt_keyfile: str = None,
|
|
52
|
+
pemt_certfile: str = None, pemt_keyfile: str = None, cafile: str = None):
|
|
53
|
+
if role not in _ROLES:
|
|
54
|
+
raise ValueError(f"role must be one of {_ROLES}, not {role!r}")
|
|
55
|
+
|
|
56
|
+
self.aemt_id = aemt_id
|
|
57
|
+
self.aemt_host = aemt_host
|
|
58
|
+
self.aemt_port = aemt_port
|
|
59
|
+
self.pemt_id = pemt_id
|
|
60
|
+
self.pemt_host = pemt_host
|
|
61
|
+
self.pemt_port = pemt_port
|
|
62
|
+
self.role = role
|
|
63
|
+
self.control_demand_callback = control_demand_callback
|
|
64
|
+
self.answer_callback = answer_callback
|
|
65
|
+
self.answer_to_sender = answer_to_sender
|
|
66
|
+
self.logger = utils.setup_logger("BDEW", pemt_id if role == ROLE_PEMT else aemt_id)
|
|
67
|
+
|
|
68
|
+
self.control_demand_server = None
|
|
69
|
+
self.answer_state_handler = None
|
|
70
|
+
self.answer_state_server = None
|
|
71
|
+
self.control_demand_handler = None
|
|
72
|
+
|
|
73
|
+
if role in (ROLE_AEMT, ROLE_BOTH):
|
|
74
|
+
aemt_ctx, aemt_session = self._load_tls("aemt", aemt_certfile, aemt_keyfile, cafile)
|
|
75
|
+
self.control_demand_server = control_demand_server.ControlDemandServer(
|
|
76
|
+
aemt_id=self.aemt_id, host=self.aemt_host, port=self.aemt_port,
|
|
77
|
+
logic_callback=self._on_control_demand, ssl_context=aemt_ctx)
|
|
78
|
+
self.answer_state_handler = answer_state_handler.AnswerStateHandler(
|
|
79
|
+
aemt_id=self.aemt_id, pemt_id=self.pemt_id, pemt_host=self.pemt_host, pemt_port=self.pemt_port,
|
|
80
|
+
logic_callback=None, session=aemt_session)
|
|
81
|
+
if role in (ROLE_PEMT, ROLE_BOTH):
|
|
82
|
+
pemt_ctx, pemt_session = self._load_tls("pemt", pemt_certfile, pemt_keyfile, cafile)
|
|
83
|
+
self.answer_state_server = answer_state_server.AnswerStateServer(
|
|
84
|
+
pemt_id=self.pemt_id, host=self.pemt_host, port=self.pemt_port,
|
|
85
|
+
logic_callback=self._on_answer, ssl_context=pemt_ctx)
|
|
86
|
+
self.control_demand_handler = control_demand_handler.ControlDemandHandler(
|
|
87
|
+
pemt_id=self.pemt_id, aemt_id=self.aemt_id, aemt_host=self.aemt_host, aemt_port=self.aemt_port,
|
|
88
|
+
logic_callback=None, session=pemt_session)
|
|
89
|
+
|
|
90
|
+
if autostart:
|
|
91
|
+
self.start()
|
|
92
|
+
|
|
93
|
+
def _load_tls(self, side: str, certfile: str, keyfile: str, cafile: str):
|
|
94
|
+
"""(server context, client session) of one side, or (None, None) with a warning."""
|
|
95
|
+
try:
|
|
96
|
+
return tls_config.load_side(side, certfile, keyfile, cafile)
|
|
97
|
+
except OSError as e: # includes ssl.SSLError
|
|
98
|
+
self.logger.warning(
|
|
99
|
+
f"TLS setup of the {side} side failed ({e}) — BDEW API {side} side inactive: "
|
|
100
|
+
"its server will not start and its requests will not be sent."
|
|
101
|
+
)
|
|
102
|
+
return None, None
|
|
103
|
+
|
|
104
|
+
def start(self):
|
|
105
|
+
"""Start the server(s) of this side (background threads)."""
|
|
106
|
+
if self.control_demand_server is not None:
|
|
107
|
+
self.control_demand_server.start()
|
|
108
|
+
if self.answer_state_server is not None:
|
|
109
|
+
self.answer_state_server.start()
|
|
110
|
+
|
|
111
|
+
# server callbacks
|
|
112
|
+
def _on_control_demand(self, location_id: str, command: dict, kind: str, remote_addr: str = None):
|
|
113
|
+
if self.answer_to_sender and remote_addr:
|
|
114
|
+
self.answer_state_handler.pemt_host = remote_addr
|
|
115
|
+
if self.control_demand_callback is not None:
|
|
116
|
+
self.control_demand_callback(location_id, command, kind, remote_addr)
|
|
117
|
+
|
|
118
|
+
def _on_answer(self, route: str, body: dict):
|
|
119
|
+
if self.answer_callback is not None:
|
|
120
|
+
self.answer_callback(route, body)
|
|
121
|
+
|
|
122
|
+
# logic of api
|
|
123
|
+
def send_control_request(self, command_control: dict, location_id: str):
|
|
124
|
+
"""pEMT side: report a control demand to the aEMT."""
|
|
125
|
+
if self.control_demand_handler is None:
|
|
126
|
+
raise RuntimeError(f"send_control_request is not available for role {self.role!r}")
|
|
127
|
+
self.control_demand_handler.send_demand_control(command_control, location_id)
|
|
128
|
+
|
|
129
|
+
def send_control_status(self, result: object):
|
|
130
|
+
"""aEMT side: answer the pEMT with the delivery status of a control command."""
|
|
131
|
+
if self.answer_state_handler is None:
|
|
132
|
+
raise RuntimeError(f"send_control_status is not available for role {self.role!r}")
|
|
133
|
+
self.answer_state_handler.send_answer(result)
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
from bdew_api.utils import setup_logger
|
|
2
|
+
from bdew_api import id_generator as id_gen
|
|
3
|
+
|
|
4
|
+
#formerly AEMTHandler
|
|
5
|
+
#api between pemt and aemt
|
|
6
|
+
#pemt sends message with need for regulation command to aemt
|
|
7
|
+
#(aemt requests regulation command, sends request to gwa, smgw: establish cls channel to controlbox)
|
|
8
|
+
#aemt answers with command request delivered successfully or not delivered
|
|
9
|
+
#API (Application Programming Interface) implements BNetzA ruling BK6-22-128
|
|
10
|
+
#specs: openapi 3.0.0, version 1.0.0. Official title (German): "EDI@Energy
|
|
11
|
+
#API-Webdienste zur prozessualen Abwicklung von Steuerungshandlungen in
|
|
12
|
+
#Verbindung mit intelligenten Messsystemen (iMS) - Universalbestellprozess"
|
|
13
|
+
|
|
14
|
+
class ControlDemandHandler:
|
|
15
|
+
def __init__(self, pemt_id: str, aemt_id: str, aemt_host: str, aemt_port: int, logic_callback=None,
|
|
16
|
+
session=None):
|
|
17
|
+
self.pemt_id = pemt_id
|
|
18
|
+
self.aemt_id = aemt_id
|
|
19
|
+
self.aemt_host = aemt_host
|
|
20
|
+
self.aemt_port = aemt_port
|
|
21
|
+
# Setup logging
|
|
22
|
+
self.logger = setup_logger("AEMT", pemt_id)
|
|
23
|
+
self.logic_callback = logic_callback
|
|
24
|
+
# Mutual-TLS client session (tls_config.requests_session); None = TLS setup failed
|
|
25
|
+
self.session = session
|
|
26
|
+
|
|
27
|
+
def send_demand_control(self, command_control: dict = None, location_id: str = None):
|
|
28
|
+
"""Report control demand to the aEMT (universal ordering process).
|
|
29
|
+
|
|
30
|
+
Triggered by the pEMT when the grid-state estimation reports a
|
|
31
|
+
congestion. Without ``command_control`` a default control command
|
|
32
|
+
(power limitation) is sent; a dict with only ``executionTimeFrom``
|
|
33
|
+
triggers ``command-regular`` instead (return to normal state).
|
|
34
|
+
|
|
35
|
+
``location_id`` identifies the affected device (mME ID from the routing
|
|
36
|
+
table), so the aEMT can resolve the household group and controlbox;
|
|
37
|
+
without it, a generated location ID is sent.
|
|
38
|
+
"""
|
|
39
|
+
if self.session is None:
|
|
40
|
+
self.logger.warning("Control demand not sent — no TLS session (TLS setup failed).")
|
|
41
|
+
return None
|
|
42
|
+
self.logger.info("━" * 100)
|
|
43
|
+
self.logger.info(" " * 44 + "Control Demand Handler")
|
|
44
|
+
self.logger.info("━" * 100)
|
|
45
|
+
|
|
46
|
+
self.logger.info(
|
|
47
|
+
f"Sending control demand to {self.aemt_host}:{self.aemt_port} - Control Signal needs to be send to Control Box.")
|
|
48
|
+
|
|
49
|
+
id_generator = id_gen.IDGenerator
|
|
50
|
+
#ID format: string($UUID RFC9562)
|
|
51
|
+
#transactionId: external, unique, info about a control command confirmed by the GWA?
|
|
52
|
+
transaction_id = id_generator.generate_transaction_id()
|
|
53
|
+
#timestamp of (this?) call
|
|
54
|
+
creation_date_time = id_generator.generate_datetimestamp()
|
|
55
|
+
#idempotency key, provided in case of a retry
|
|
56
|
+
initial_transaction_id = transaction_id
|
|
57
|
+
#locationId: identifies the resource the control command acts on
|
|
58
|
+
if location_id is None:
|
|
59
|
+
location_id = id_generator.generate_location_id()
|
|
60
|
+
|
|
61
|
+
#commandControl: default control command (power limitation)
|
|
62
|
+
if command_control is None:
|
|
63
|
+
command_control = {
|
|
64
|
+
"maximumPowerValue": "24.123",
|
|
65
|
+
"executionTimeFrom": id_generator.generate_datetimestamp(),
|
|
66
|
+
"executionTimeUntil": id_generator.generate_datetimestamp(),
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
try:
|
|
70
|
+
#build header and query for http request
|
|
71
|
+
headers = {'transactionId':transaction_id, 'creationDateTime':creation_date_time,
|
|
72
|
+
'initialTransactionId':initial_transaction_id}
|
|
73
|
+
if len(command_control.keys()) > 1:
|
|
74
|
+
query = {'locationId':location_id,'commandControl':command_control}
|
|
75
|
+
url = f"https://{self.aemt_host}:{self.aemt_port}/command-control"
|
|
76
|
+
else:
|
|
77
|
+
#command: set to initial state
|
|
78
|
+
query = {'locationId': location_id, 'commandRegular': command_control}
|
|
79
|
+
url = f"https://{self.aemt_host}:{self.aemt_port}/command-regular"
|
|
80
|
+
|
|
81
|
+
# Attempt POST to the aEMT (HTTPS)
|
|
82
|
+
response = self.session.post(
|
|
83
|
+
url,
|
|
84
|
+
headers=headers,
|
|
85
|
+
json=query,
|
|
86
|
+
timeout=5,
|
|
87
|
+
)
|
|
88
|
+
self.logger.info(f"Control demand sent to aEMT ({url}), HTTP {response.status_code}.")
|
|
89
|
+
|
|
90
|
+
except Exception as e:
|
|
91
|
+
self.logger.error(f"AEMT-Answer error: {e}")
|
|
92
|
+
return None
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
from bdew_api.utils import setup_logger
|
|
2
|
+
from flask import Flask, request, jsonify
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
import threading
|
|
5
|
+
|
|
6
|
+
#formerly BDEW API Server
|
|
7
|
+
# BDEW API server of the aEMT (EDI@Energy Universalbestellprozess,
|
|
8
|
+
# BNetzA ruling BK6-22-128).
|
|
9
|
+
#
|
|
10
|
+
# The pEMT reports a control demand here when the grid-state estimation
|
|
11
|
+
# detects a grid congestion:
|
|
12
|
+
# POST /command-control — power limitation (commandControl)
|
|
13
|
+
# POST /command-regular — return to the normal state (commandRegular)
|
|
14
|
+
#
|
|
15
|
+
# Required headers: transactionId, creationDateTime, initialTransactionId.
|
|
16
|
+
# Required body: locationId + commandControl / commandRegular.
|
|
17
|
+
# locationId identifies the resource the control command acts on — the
|
|
18
|
+
# affected device (mME) as listed in the routing table, so the aEMT can
|
|
19
|
+
# resolve the household group and its controlbox.
|
|
20
|
+
|
|
21
|
+
_REQUIRED_HEADERS = ("transactionId", "creationDateTime", "initialTransactionId")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ControlDemandServer:
|
|
25
|
+
def __init__(self, aemt_id: str, host: str, port: int, logic_callback,
|
|
26
|
+
ssl_context=None) -> None:
|
|
27
|
+
"""
|
|
28
|
+
Args:
|
|
29
|
+
aemt_id: ID of this aEMT (13-digit BDEW MP-ID)
|
|
30
|
+
host: bind address
|
|
31
|
+
port: HTTPS port of the BDEW API (aEMT range, :8301)
|
|
32
|
+
logic_callback: called as logic_callback(location_id, command, kind)
|
|
33
|
+
with kind in {"control", "regular"} after a request
|
|
34
|
+
passed validation
|
|
35
|
+
ssl_context: mutual-TLS server context (tls_config.server_context);
|
|
36
|
+
without one the server does not start
|
|
37
|
+
"""
|
|
38
|
+
self.aemt_id = aemt_id
|
|
39
|
+
self.host = host
|
|
40
|
+
self.port = port
|
|
41
|
+
self.logic_callback = logic_callback
|
|
42
|
+
self.ssl_context = ssl_context
|
|
43
|
+
|
|
44
|
+
self.logger = setup_logger("ControlDemandServer", aemt_id)
|
|
45
|
+
|
|
46
|
+
self.app = Flask(__name__)
|
|
47
|
+
self._setup_flask_routes()
|
|
48
|
+
|
|
49
|
+
def start(self):
|
|
50
|
+
if self.ssl_context is None:
|
|
51
|
+
self.logger.warning("Control Demand Server not started — no TLS context (TLS setup failed).")
|
|
52
|
+
return
|
|
53
|
+
self.logger.info("━" * 100)
|
|
54
|
+
self.logger.info(" " * 42 + "Control Demand Server")
|
|
55
|
+
self.logger.info("━" * 100)
|
|
56
|
+
flask_thread = threading.Thread(target=self._run_https_server, daemon=True)
|
|
57
|
+
flask_thread.start()
|
|
58
|
+
self.logger.info(f"BDEW control demand endpoint listening on {self.host}:{self.port} (HTTPS)")
|
|
59
|
+
|
|
60
|
+
def _validate(self, body: dict, command_key: str):
|
|
61
|
+
"""Validate headers and body of a Universalbestellprozess request.
|
|
62
|
+
|
|
63
|
+
Returns (error_response, status) on failure, (None, None) on success.
|
|
64
|
+
"""
|
|
65
|
+
missing = [h for h in _REQUIRED_HEADERS if not request.headers.get(h)]
|
|
66
|
+
if missing:
|
|
67
|
+
return jsonify({"error": f"missing headers: {', '.join(missing)}"}), 400
|
|
68
|
+
if not isinstance(body, dict):
|
|
69
|
+
return jsonify({"error": "request body must be a JSON object"}), 400
|
|
70
|
+
if not body.get("locationId"):
|
|
71
|
+
return jsonify({"error": "missing locationId"}), 400
|
|
72
|
+
command = body.get(command_key)
|
|
73
|
+
if not isinstance(command, dict) or not command.get("executionTimeFrom"):
|
|
74
|
+
return jsonify(
|
|
75
|
+
{"error": f"missing or invalid {command_key} (executionTimeFrom required)"}
|
|
76
|
+
), 400
|
|
77
|
+
return None, None
|
|
78
|
+
|
|
79
|
+
def _setup_flask_routes(self):
|
|
80
|
+
@self.app.route("/command-control", methods=["POST"])
|
|
81
|
+
def handle_command_control():
|
|
82
|
+
body = request.get_json(silent=True)
|
|
83
|
+
error, status = self._validate(body, "commandControl")
|
|
84
|
+
if error is not None:
|
|
85
|
+
self.logger.warning(f"Rejected /command-control request: {error.get_json()}")
|
|
86
|
+
return error, status
|
|
87
|
+
self.logger.info(
|
|
88
|
+
f"Control demand received (locationId={body['locationId']}, "
|
|
89
|
+
f"transactionId={request.headers['transactionId']})"
|
|
90
|
+
)
|
|
91
|
+
if self.logic_callback is not None:
|
|
92
|
+
self.logic_callback(body["locationId"], body["commandControl"], "control", request.remote_addr)
|
|
93
|
+
return jsonify({"status": "accepted"}), 202
|
|
94
|
+
|
|
95
|
+
@self.app.route("/command-regular", methods=["POST"])
|
|
96
|
+
def handle_command_regular():
|
|
97
|
+
body = request.get_json(silent=True)
|
|
98
|
+
error, status = self._validate(body, "commandRegular")
|
|
99
|
+
if error is not None:
|
|
100
|
+
self.logger.warning(f"Rejected /command-regular request: {error.get_json()}")
|
|
101
|
+
return error, status
|
|
102
|
+
self.logger.info(
|
|
103
|
+
f"Regular-state command received (locationId={body['locationId']})"
|
|
104
|
+
)
|
|
105
|
+
if self.logic_callback is not None:
|
|
106
|
+
self.logic_callback(body["locationId"], body["commandRegular"], "regular", request.remote_addr)
|
|
107
|
+
return jsonify({"status": "accepted"}), 202
|
|
108
|
+
|
|
109
|
+
@self.app.route("/health", methods=["GET"])
|
|
110
|
+
def health():
|
|
111
|
+
return jsonify({"status": "HEALTHY", "timestamp": datetime.now().isoformat()}), 200
|
|
112
|
+
|
|
113
|
+
def _run_https_server(self):
|
|
114
|
+
try:
|
|
115
|
+
self.app.run(
|
|
116
|
+
host=self.host,
|
|
117
|
+
port=self.port,
|
|
118
|
+
ssl_context=self.ssl_context,
|
|
119
|
+
debug=False,
|
|
120
|
+
use_reloader=False,
|
|
121
|
+
threaded=True,
|
|
122
|
+
)
|
|
123
|
+
except Exception as e:
|
|
124
|
+
self.logger.error(f"Control Demand Server failure: {e}")
|