Skip to main content

GitHub Release Language grade: Python License

Project Maintenance buy me a coffee

AMSHAN

Package to help decode smart power meter data stream of IEC 62056-21 Mode D P1 or DLMS/Cosem HDLC frames used by MBUS (Meter Bus). The package can both help reading frames of meter data and/or decoding them.

The package has special support for DLMS formats used by Aidon, Kaifa and Kamstrup smart meteres (HAN) in Norway (See https://www.nek.no/info-ams-han-utviklere/) and Sweden. The Swedish P1 format format is also supported.

Reading asynchronous from a stream of data

SmartMeterMessagePayloadProtocol can be used to read smart meter P1 date readout (ascii) or MBUS HDLC (binary) frames asynchronous. The content of each mdssage (no headers and control characters) is passed as bytes to a Queue. Headers are checked and checksum validated, and only content from non empty frames with expected length (only DLMS) and checksum is passed to the queue.

SmartMeterMessageProtocol can be used to read smart meter P1 data readout (ascii) or MBUS HDLC frames asynchronous. The complete message is sent to a Queue as an instance of as subclass of MeterReaderBase. Frames are not validated. This class is a more low level alternative to SmartMeterMessagePayloadProtocol. This type has to be used to get the meter type from P1 readouts as this is part of the message "header".

Both SmartMeterMessagePayloadProtocol and SmartMeterMessageProtocol is a Python asyncio protocol. Protocols support different types of transports like network and serial.

It is recommended to use provided ConnectionManager and connection factories to read the data stream.

Create protocol using transport

Pass a factory for the selected protocol (SmartMeterMessagePayloadProtocol or SmartMeterMessageProtocol) to a utility function of your selected transport (e.g., EventLoop.create_connection() for TCP/IP or serial_asyncio.create_serial_connection() for serial).

Serial example:

transport, protocol = await serial_asyncio.create_serial_connection(loop, lambda: SmartMeterMessagePayloadProtocol(queue, [ModeDReader]), url = "/dev/tty01")

Serial example:

transport, protocol = await serial_asyncio.create_serial_connection(loop, lambda: SmartMeterMessagePayloadProtocol(queue, [ModeDReader]), url = "/dev/tty01")

Create protocol using provided factories

Multiple factories are provided to create a protocol as an alternative to using selected transports create function as above. Use serial_connection_factory for serial and tcp_connection_factory for TCP/IP.

Factory module SmartMeterMessageProtocol SmartMeterMessagePayloadProtocol
serial_connection_factory create_serial_message_payload_connection() create_serial_message_connection()
tcp_connection_factory create_tcp_message_connection() create_tcp_message_payload_connection()

Example of creating a SmartMeterMessagePayloadProtocol serial connection on device /dev/ttyUSB0:

queue = Queue()
loop = asyncio.get_event_loop()
transport, protocol = await create_serial_frame_content_connection(queue, loop, None, url="/dev/ttyUSB0", baudrate=2400, parity=N)

Example of creating a SmartMeterMessageProtocol protocol TCP/IP connection to host 192.168.1.1 on port 1234:

queue = Queue()
loop = asyncio.get_event_loop()
transport, protocol = await create_tcp_frame_connection(queue, loop, None, "192.168.1.1", 1234)

See reader_async.py for a complete example.

Create resilient connection with ConnectionManager

ConnectionManager maintain connection and reconnect if connection is lost. A back-off retry strategy is used when reconnecting, and a simple circuit breaker is used for lost connection.

queue = Queue()
loop = asyncio.get_event_loop()
connection_manager = ConnectionManager(lambda: create_serial_message_connection(queue, loop, None, url="/dev/ttyUSB0", baudrate=2400, parity=N))
await connection_manager.connect_loop()

See reader_async.py for a complete example.

Parse P1 readouts directly from raw bytes

dlde.ModeDReader can be used to read readout by readout from bytes. Call read() to read readouts as more bytes become available. The function takes bytes as an argument and returns a list of DataReadout (the list can be empty). The function can receive incomplete readout in the buffer input and add incomplete data to an internal buffer. The buffer is schrinked when complete readout are found and returned. You should check if returned readouts are valid with readout.is_valid before using them.

Parse frames directly from raw bytes

hdlc.HdlcFrameReader can be used to read frame by frame from bytes. Call read() to read frames as more bytes become available. The function takes bytes as an argument and returns a list of HdlcFrame (the list can be empty). The function can receive incomplete frames in the buffer input and add incomplete data to an internal buffer. The buffer is schrinked when complete frames are found and returned. You should check if returned frames are valid with frame.is_valid before using them.

HDLC framing, octet stuffing and the abort sequence

HDLC frames start and end with the flag octet 0x7E. Many HDLC links use octet stuffing: the sender replaces 0x7E and 0x7D in the data with 0x7D followed by the octet XOR 0x20, so a flag can only appear at frame boundaries. In that scheme 0x7D directly before a flag can never be data, and it is used as the abort sequence (the sender aborts a frame with 0x7D 0x7E).

The meters this package has been tested with on the Norwegian and Swedish HAN port (Aidon, Kaifa and Kamstrup) send frames without octet stuffing: 0x7E and 0x7D occur as ordinary data octets, and the end of a frame is given by the length in the frame format field. No requirement has been found that rules out octet stuffing, and other meters or new firmware may behave differently. HdlcFrameReader(use_octet_stuffing=False) is the default because it matches the meters seen so far; use use_octet_stuffing=True for a meter that escapes 0x7E and 0x7D in the data.

The abort sequence is part of octet stuffing. With use_octet_stuffing=True, use_abort_sequence=True a frame aborted with 0x7D 0x7E is silently discarded; with use_abort_sequence=False the dangling 0x7D is dropped and the frame goes through the normal length and frame check (an aborted frame normally fails them). Without octet stuffing there is no abort sequence, because a valid frame may end with 0x7D (for example as the last octet of the frame check sequence), so use_abort_sequence has no effect and a warning is issued.

Without octet stuffing a truncated frame reads the opening flag of the next frame as data. When the reader finds that a frame is broken (it has passed the length in its frame format field, or ends at that length with a bad frame check sequence), it reads the octets of the broken frame again from the first flag inside it. Frames that the broken frame had swallowed are therefore returned, a little later, instead of being lost.

Decode norwegian and swedish messages

P1 readout and MBUS frames using the norwegian or swedish DMLS AMS format can be parsed into meter specific objects or decoded into a common dictionary. Modules exists for P1 (generic format), Aidon, Kaifa and Kamstrup meters, but the easiest is to use autodecoder.AutoDecode to automatically detect meter type and decode the frame into a dictionary. The dictionay content is as far as possible common between meters. Possible dictionary keys kan be found as constants in obis_map.py.

Example:

decoder = AutoDecoder()
frame = bytes.fromhex("e6e700" "0f" "40000000" "00" "0101" "020309060100010700ff060000011802020f00161b")
decoded = decoder.decode_frame_content(frame)

Metadata

Release files for amshan 2.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for amshan 2.2.0
File Size Uploaded Provenance Actions
amshan-2.2.0.tar.gz 66.3 kB With provenance Details for amshan-2.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for amshan 2.2.0
File Interpreter ABI Platform Actions
amshan-2.2.0-py3-none-any.whl Python 3 none any Details for amshan-2.2.0-py3-none-any.whl

Total release size: 101.5 kB

Release files / amshan-2.2.0.tar.gz

Download URL amshan-2.2.0.tar.gz
Size 66.3 kB
Tags Source
SHA-256 checksum
How to use checksums
82c4de537b970eb81f2a529eb4fdf54e486a1e7cc018fd8459cb6e4d440b3968
BLAKE2b-256 checksum
How to use checksums
9044889c0f59cc6a6f7980a27ea6245a81bb04260887cdd9a0a33fac44b1b079
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Release files / amshan-2.2.0-py3-none-any.whl

Download URL amshan-2.2.0-py3-none-any.whl
Size 35.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4e6c223246b89238a023273695d898bc1ece9bbf3f306a209d9685ed44a2f54a
BLAKE2b-256 checksum
How to use checksums
6ef13df8293878cc737262e82b6b9f6f3015536b3a9776f617712499ee7ca20d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Security for amshan 2.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for amshan-2.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page