| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- from __future__ import annotations
- import struct
- from typing import Any
- def byte_size_for_type(point_type: str) -> int:
- if point_type in {"bool", "byte", "int8"}:
- return 1
- if point_type in {"int16", "uint16"}:
- return 2
- if point_type in {"int64", "uint64", "float64"}:
- return 8
- return 4
- def bytes_to_hex(data: bytes | bytearray) -> str:
- return " ".join(f"{value:02X}" for value in data)
- def convert_s7_value(data: bytes | bytearray, point_type: str, bit: int | None) -> Any:
- payload = bytes(data)
- if point_type == "bool":
- value = payload[0]
- if bit is None:
- return value != 0
- return ((value >> bit) & 1) == 1
- if point_type == "byte":
- return payload[0]
- if point_type == "int8":
- return int.from_bytes(payload, byteorder="big", signed=True)
- if point_type == "int16":
- return int.from_bytes(payload, byteorder="big", signed=True)
- if point_type == "uint16":
- return int.from_bytes(payload, byteorder="big", signed=False)
- if point_type == "int32":
- return int.from_bytes(payload, byteorder="big", signed=True)
- if point_type == "uint32":
- return int.from_bytes(payload, byteorder="big", signed=False)
- if point_type == "int64":
- return int.from_bytes(payload, byteorder="big", signed=True)
- if point_type == "uint64":
- return int.from_bytes(payload, byteorder="big", signed=False)
- if point_type == "float32":
- return struct.unpack(">f", payload)[0]
- if point_type == "float64":
- return struct.unpack(">d", payload)[0]
- raise ValueError(f"unsupported point type: {point_type}")
|