Skip to content

sensorB_simulator_v2

SensorB Modbus TCP Simulator

  • Logs every client poll (READ) and simulator write (WRITE) at DEBUG.
  • Also prints a concise [SEND] trace with tag name, dtype, eng value, and raw registers.
  • Console/file logging is deterministic (handlers reset on each run).
  • Endianness and update interval come from sim/config files.

USAGE python3 sensorB_simulator_v1.py [--debug]

CONFIG FILES (expected relative paths, override as needed) emsConfig/sensorB_modbus_config.json simulator_config/sensorB_register.json simulator_config/sensorB_register_values.json simulator_config/sensorB_sim_par.json

LoggingDataBlock

Bases: ModbusSequentialDataBlock

DataBlock that logs reads (polls) and writes when DEBUG is enabled.

Source code in EMS_template_codes/sensorB_simulator_v2.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
class LoggingDataBlock(ModbusSequentialDataBlock):
    """DataBlock that logs reads (polls) and writes when DEBUG is enabled."""
    def __init__(self, address, values, log: logging.Logger):
        super().__init__(address, values)
        self._log = log

    def setValues(self, address, values):
        super().setValues(address, values)
        if self._log.isEnabledFor(logging.DEBUG):
            self._log.debug("[WRITE] HR[%d..%d] <= %s",
                            address, address + len(values) - 1, list(values))

    def getValues(self, address, count=1):
        vals = super().getValues(address, count)
        if self._log.isEnabledFor(logging.DEBUG):
            self._log.debug("[READ ] HR[%d..%d] => %s",
                            address, address + count - 1, list(vals))
        return vals

_coerce_meta(name_hint: str, meta: dict) -> Dict[str, Any]

Coerce a raw meta dict into the canonical shape used by the simulator.

Source code in EMS_template_codes/sensorB_simulator_v2.py
46
47
48
49
50
51
52
53
54
55
56
def _coerce_meta(name_hint: str, meta: dict) -> Dict[str, Any]:
    """Coerce a raw meta dict into the canonical shape used by the simulator."""
    return {
        "address": int(meta.get("address", 3000)),
        "dtype": str(meta.get("dtype", "FLOAT32")),
        "registers": int(meta.get("registers", 2)),
        "min": meta.get("min"),
        "max": meta.get("max"),
        "unit": meta.get("unit", ""),
        "name": meta.get("name", name_hint),
    }

flatten_reg_map(reg_map_any: Any) -> Dict[str, Dict[str, Any]]

Accepts multiple JSON shapes and returns {name: meta}.

Supported
  • Dict[name]->meta
  • Dict[category]->Dict[name]->meta
  • List[meta with "name"]
Source code in EMS_template_codes/sensorB_simulator_v2.py
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def flatten_reg_map(reg_map_any: Any) -> Dict[str, Dict[str, Any]]:
    """
    Accepts multiple JSON shapes and returns {name: meta}.

    Supported:
      - Dict[name]->meta
      - Dict[category]->Dict[name]->meta
      - List[meta with "name"]
    """
    out: Dict[str, Dict[str, Any]] = {}

    def add_pair(n: str, m: dict):
        try:
            cm = _coerce_meta(n, m)
            key = cm.get("name") or n
            out[key] = cm
        except Exception as e:
            logger.warning("Skipping bad meta for '%s': %s (raw=%r)", n, e, m)

    def walk(node: Any, name_ctx: str = ""):
        if isinstance(node, dict):
            # Heuristic: if dict has 'address', treat as a single meta
            if "address" in node and ("dtype" in node or "registers" in node or "min" in node or "max" in node):
                add_pair(node.get("name") or name_ctx or f"tag_{len(out)+1}", node)
                return
            # Otherwise iterate keys
            for k, v in node.items():
                if isinstance(v, dict):
                    if "address" in v:
                        add_pair(k, v)
                    else:
                        # could be a category; recurse
                        walk(v, k)
                elif isinstance(v, list):
                    for i, item in enumerate(v):
                        if isinstance(item, dict):
                            nm = item.get("name") or f"{k}_{i}"
                            add_pair(nm, item)
                        else:
                            logger.warning("Skipping non-dict item at %s[%d]: %r", k, i, item)
                else:
                    logger.warning("Skipping non-dict value at key '%s': %r", k, v)
        elif isinstance(node, list):
            for i, item in enumerate(node):
                if isinstance(item, dict):
                    nm = item.get("name") or f"tag_{len(out)+1}"
                    add_pair(nm, item)
                else:
                    logger.warning("Skipping non-dict list item[%d]: %r", i, item)
        else:
            logger.warning("Unknown register map shape: %r", type(node))

    walk(reg_map_any)
    if not out:
        raise ValueError("No valid register definitions found in sensorB_register.json")
    return out

get_values() -> Dict[str, Any]

Optional static overrides map: {name: value}

Source code in EMS_template_codes/sensorB_simulator_v2.py
257
258
259
260
def get_values() -> Dict[str, Any]:
    """Optional static overrides map: {name: value}"""
    vals = read_json(REG_VALUES_FILE, {})
    return vals if isinstance(vals, dict) else {}

jitter(val, span, scale=0.3)

A gentle jitter around val within ± span*scale.

Source code in EMS_template_codes/sensorB_simulator_v2.py
221
222
223
def jitter(val, span, scale=0.3):
    """A gentle jitter around val within +/- span*scale."""
    return val + (random.random() - 0.5) * span * scale

make_eng_value(meta: Dict[str, Any], static_vals: Dict[str, Any]) -> Any

Produce an engineering value either from static override or from range.

Source code in EMS_template_codes/sensorB_simulator_v2.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def make_eng_value(meta: Dict[str, Any], static_vals: Dict[str, Any]) -> Any:
    """Produce an engineering value either from static override or from range."""
    name = meta.get("name")
    if name and name in static_vals:
        return static_vals[name]
    vmin = meta.get("min")
    vmax = meta.get("max")
    dtype = meta.get("dtype", "FLOAT32").upper()

    if vmin is not None and vmax is not None:
        base = (vmin + vmax) / 2.0
        eng = clamp(jitter(base, vmax - vmin), vmin, vmax)
        if dtype.startswith("UINT"):
            return int(max(0, round(eng)))
        else:
            return round(eng, 3)
    # fallback deterministic
    return 0 if dtype.startswith("UINT") else 0.0

pack_float32_to_words(value: float, endian: str) -> Tuple[int, int]

Pack float into two 16-bit registers.

Source code in EMS_template_codes/sensorB_simulator_v2.py
155
156
157
158
159
160
def pack_float32_to_words(value: float, endian: str) -> Tuple[int, int]:
    """Pack float into two 16-bit registers."""
    # endian: 'big' means register order [high, low]; 'little' means [low, high]
    b = struct.pack(">f", float(value))  # network float
    hi, lo = struct.unpack(">HH", b)
    return (hi, lo) if endian == "big" else (lo, hi)

🔁 Simulation Flow

flowchart TD
    A[Start main()] --> B[...]

⚙️ Flow with Conditional Checks

flowchart TD
    A[Start main()] --> B{Check something?}
    B -- Yes --> C[Do X]
    B -- No --> D[Exit]