Skip to content

Connectors

Talking to the device underneath.

py20305.connectors.base

Base connector class with async no-op defaults for all DER control modes.

Connectors inherit from BaseConnector and selectively override the methods they support. Unsupported modes are silent no-ops, matching the physical reality that not every device supports every IEEE 2030.5 control mode.

ConnectorConnectionError

Bases: ConnectorError

Raised when the connector cannot reach the target device.

The optional permanent flag signals that the failure won't change on retry without operator intervention -- e.g. Modbus protocol exception codes 1-4 (illegal function/address/value, server failure), which typically mean the configured device is missing models the connector was told to scan for.

Source code in src/py20305/connectors/errors.py
class ConnectorConnectionError(ConnectorError):
    """Raised when the connector cannot reach the target device.

    The optional ``permanent`` flag signals that the failure won't change
    on retry without operator intervention -- e.g. Modbus protocol
    exception codes 1-4 (illegal function/address/value, server failure),
    which typically mean the configured device is missing models the
    connector was told to scan for.
    """

    def __init__(self, *args: object, permanent: bool = False) -> None:
        super().__init__(*args)
        self.permanent = permanent

ConnectorError

Bases: Exception

Base exception for connector operations.

Source code in src/py20305/connectors/errors.py
class ConnectorError(Exception):
    """Base exception for connector operations."""

ConnectorTimeoutError

Bases: ConnectorError

Raised when a connector operation exceeds its deadline.

Source code in src/py20305/connectors/errors.py
class ConnectorTimeoutError(ConnectorError):
    """Raised when a connector operation exceeds its deadline."""

ConnectorValueError

Bases: ConnectorError

Raised when a control parameter is outside the range the profile allows.

Distinct from :class:ConnectorWriteError: nothing was attempted. The parameter itself is invalid, so no device could have accepted it and a retry with the same value cannot succeed. The register is left untouched, including any mode-enable point -- a lever must not be raised for a write that will not happen.

Reported to the head-end as IEEE 2030.5 Table 31 status 253 (Invalid), because the fault is in the event's data rather than in what the device can do. Adapters translate accordingly at their own boundary.

Source code in src/py20305/connectors/errors.py
class ConnectorValueError(ConnectorError):
    """Raised when a control parameter is outside the range the profile allows.

    Distinct from :class:`ConnectorWriteError`: nothing was attempted. The
    parameter itself is invalid, so no device could have accepted it and a retry
    with the same value cannot succeed. The register is left untouched, including
    any mode-enable point -- a lever must not be raised for a write that will not
    happen.

    Reported to the head-end as IEEE 2030.5 Table 31 status 253 (Invalid),
    because the fault is in the event's data rather than in what the device can
    do. Adapters translate accordingly at their own boundary.
    """

ConnectorWriteError

Bases: ConnectorError

Raised when a control write fails or is rejected by the device.

Source code in src/py20305/connectors/errors.py
class ConnectorWriteError(ConnectorError):
    """Raised when a control write fails or is rejected by the device."""

Reading dataclass

One measured value and the IEEE 2030.5 ReadingType that describes it.

value is in engineering units (W, var, VA, V, A, Hz, Wh, or a power factor between -1 and 1). Real and reactive power are signed in the frame of the device's role:

  • A DER and a DER meter report positive real power for power the DER delivers and negative for power it absorbs; positive reactive power for reactive power it injects (over-excited) and negative for reactive power it absorbs (under-excited).
  • A site meter reports positive real and reactive power for import, from the area EPS to the premises, which IEEE 2030.5 FlowDirectionType calls Forward.

A power factor carries the sign of its reactive power. Every other quantity is posted as a magnitude.

The remaining fields are IEEE 2030.5 ReadingType codes:

  • uom: UomType, for example 38 W, 63 var, 61 VA, 29 V, 5 A, 33 Hz, 65 cos(theta), 72 Wh.
  • phase: PhaseCode, for example 0 not applicable, 128 A, 129 AN, 132 AB, 224 ABC.
  • kind: KindType, 37 power, 12 energy, 0 not applicable.
  • data_qualifier: DataQualifierType, 12 normal, 2 average, 8 maximum, 9 minimum.
  • accumulation_behaviour: 12 instantaneous, 9 summation.
  • flow_direction: set only when the reading is direction-specific, such as an energy total delivered forward (1) or in reverse (19). None lets the reading profile choose (see py20305.telemetry.mup).
  • multiplier: the powerOfTenMultiplier to post with. None takes the library default for the unit.
  • quality_flags: this sample's qualityFlags (16 bits). None posts valid.
Source code in src/py20305/connectors/reading.py
@dataclass(frozen=True, slots=True)
class Reading:
    """One measured value and the IEEE 2030.5 ReadingType that describes it.

    ``value`` is in engineering units (W, var, VA, V, A, Hz, Wh, or a power
    factor between -1 and 1). Real and reactive power are signed in the frame of
    the device's role:

    - A DER and a DER meter report positive real power for power the DER
      delivers and negative for power it absorbs; positive reactive power for
      reactive power it injects (over-excited) and negative for reactive power
      it absorbs (under-excited).
    - A site meter reports positive real and reactive power for import, from the
      area EPS to the premises, which IEEE 2030.5 FlowDirectionType calls
      Forward.

    A power factor carries the sign of its reactive power. Every other quantity
    is posted as a magnitude.

    The remaining fields are IEEE 2030.5 ReadingType codes:

    - ``uom``: UomType, for example 38 W, 63 var, 61 VA, 29 V, 5 A, 33 Hz,
      65 cos(theta), 72 Wh.
    - ``phase``: PhaseCode, for example 0 not applicable, 128 A, 129 AN,
      132 AB, 224 ABC.
    - ``kind``: KindType, 37 power, 12 energy, 0 not applicable.
    - ``data_qualifier``: DataQualifierType, 12 normal, 2 average, 8 maximum,
      9 minimum.
    - ``accumulation_behaviour``: 12 instantaneous, 9 summation.
    - ``flow_direction``: set only when the reading is direction-specific, such
      as an energy total delivered forward (1) or in reverse (19). None lets the
      reading profile choose (see ``py20305.telemetry.mup``).
    - ``multiplier``: the powerOfTenMultiplier to post with. None takes the
      library default for the unit.
    - ``quality_flags``: this sample's qualityFlags (16 bits). None posts
      ``valid``.
    """

    uom: int
    value: float
    phase: int = 0
    kind: int = KIND_POWER
    data_qualifier: int = DATA_QUALIFIER_NORMAL
    accumulation_behaviour: int = ACCUMULATION_INSTANTANEOUS
    flow_direction: int | None = None
    multiplier: int | None = None
    quality_flags: int | None = None

ScheduleNotification dataclass

A relayed, forward-looking schedule event for a connector.

Pushed by the core on every change to a relayed schedule -- a control, baseline, DOE or price -- so a downstream optimizer stays current without polling for it. Informational only: it does not apply setpoints, which remains the job of the update_* methods.

Source code in src/py20305/connectors/base.py
@dataclass(frozen=True)
class ScheduleNotification:
    """A relayed, forward-looking schedule event for a connector.

    Pushed by the core on every *change* to a relayed schedule -- a control,
    baseline, DOE or price -- so a downstream optimizer stays current without
    polling for it. Informational only: it does not apply setpoints, which
    remains the job of the ``update_*`` methods.
    """

    #: "control" | "default_baseline" | "doe" | "price".
    #: "drlc" | "flow_reservation" are reserved for later.
    stream: str
    #: event streams: "scheduled"|"updated"|"active"|"superseded"|"cancelled"|"completed";
    #: default_baseline: "default_added"|"default_updated".
    transition: str
    #: EventState value (scheduled/active/superseded/cancelled/completed); None for baseline.
    status: str | None
    #: Raw IEEE 2030.5-2018 §11.2.4 EventStatus.currentStatus (0-5); None for baseline.
    current_status: int | None
    #: DERControl / DefaultDERControl mRID, hex.
    mrid: str
    program_href: str
    #: Program primacy.
    primacy: int
    #: Effective (post-randomization) epoch seconds / seconds; None for baseline.
    start: int | None
    duration: int | None
    end: int | None
    #: Hex LFDIs this event scopes to, resolved by the core.
    affected_lfdis: list[str]
    #: (randomizeStart, randomizeDuration) seconds -- carried so optimizers time
    #: dispatch correctly (the update_* path drops it). None when unset.
    randomization: tuple[int | None, int | None]
    #: Stream-specific typed body (DERControlBase / DefaultDERControl / envelope limits).
    payload: dict[str, Any]

BaseConnector

Base connector with async no-op defaults for all DER methods.

Subclasses override only the methods their device supports. All methods are async to allow blocking I/O to be wrapped in executors.

Source code in src/py20305/connectors/base.py
 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
class BaseConnector:
    """Base connector with async no-op defaults for all DER methods.

    Subclasses override only the methods their device supports.
    All methods are async to allow blocking I/O to be wrapped in executors.
    """

    connector_name: str = "BaseConnector"

    #: IEEE 2030.5 DER type code (see sep.Dertype).
    #: Common values: 4=PV, 81=EV, 82=EVSE, 83=Combined PV+Storage.
    der_type: int = 83

    #: What this connector speaks to its device, as reported in southbound
    #: telemetry. Defaults to "generic" — the consumer contract's catch-all —
    #: because the base class makes no claim about a wire: a connector that
    #: talks Modbus says so, and one that prints to a log should not be
    #: recorded as though it reached hardware.
    telemetry_protocol: str = "generic"

    # ------------------------------------------------------------------
    # Telemetry
    # ------------------------------------------------------------------

    async def fetch_monitoring(self) -> list[Reading]:
        """Return the device's measurements, one :class:`Reading` each.

        Each reading states its IEEE 2030.5 ReadingType (``uom``, ``phase``,
        ``kind``, ``data_qualifier``, ...) and its value in engineering units.
        Real and reactive power are signed in the frame of the device's role
        (see :class:`~py20305.connectors.reading.Reading`); a reading profile
        that posts another convention converts them. A quantity the device does
        not measure is left out. Give each reading a distinct ReadingType,
        multiplier included: a second reading with the same one is dropped and
        a warning is logged.
        """
        return []

    def supported_modes2(self) -> int | None:
        """Optional: the DERControlType2 bits this device can apply.

        DERCapability ``modesSupported2`` and DERControlResponse
        ``modesResponded2`` report these, limited to what the server profile
        permits. Return ``None`` (the default) to derive them from the controls
        the connector implements: ``update_op_mod_max_lim_w_absorb`` sets bit 7,
        ``update_op_mod_max_lim_w_inject`` bit 8, and so on. Return an integer
        for a connector that implements a control method it cannot honor on this
        device, so the device never advertises a mode it cannot apply.
        """
        return None

    def declared_readings(self) -> frozenset[ReadingIdentity] | None:
        """Optional: the readings this device provides, fixed for its life.

        Each is a :class:`~py20305.connectors.reading.ReadingIdentity` (uom,
        phase, kind, data qualifier, accumulation behaviour, flow direction and
        multiplier), or a :class:`~py20305.connectors.reading.Reading` standing
        for its identity. Under the ``SIGNED_AS_REPORTED`` reading profile the
        MirrorUsagePoint registers exactly these readings, from the first
        cycle, even one with no values (a charger with no vehicle plugged in),
        so it is posted once and never re-posted for a reading that appears
        later. A reading returned by ``fetch_monitoring`` but not declared is
        not posted. Return ``None`` (the default) to register the readings as
        they appear. Other profiles ignore it.
        """
        return None

    async def fetch_nameplate(self) -> dict[str, Any]:
        """Return DER ratings keyed by IEEE 2030.5 DERCapability element name.

        A value is a number, ``{"value": ..., "multiplier": ...}``, or for a
        power factor ``{"displacement": ..., "multiplier": ...}``. ``rtgMaxW``
        is required. ``modesSupported`` is the DERControlType bitmap;
        ``doeModesSupported`` is the CSIP-AUS extension bitmap and defaults to
        all four limits. An absent or ``None`` key is not reported; an explicit
        0 is.
        """
        return {
            "rtgMaxW": None,
            "rtgMaxVA": None,
            "rtgMaxVar": None,
            "rtgMaxVarNeg": None,
            "rtgMaxA": None,
            "rtgOverExcitedW": None,
            "rtgOverExcitedPF": None,
            "rtgUnderExcitedW": None,
            "rtgUnderExcitedPF": None,
            "rtgMaxChargeRateW": None,
            "rtgMaxChargeRateVA": None,
            "rtgMaxDischargeRateW": None,
            "rtgMaxDischargeRateVA": None,
            "rtgMaxWh": None,
            "rtgMaxAh": None,
            "rtgVNom": None,
            "rtgMaxV": None,
            "rtgMinV": None,
            "rtgReactiveSusceptance": None,
            "rtgNormalCategory": None,
            "rtgAbnormalCategory": None,
            "modesSupported": None,
            "doeModesSupported": None,
        }

    async def fetch_configuration(self) -> dict[str, Any]:
        """Return DER settings keyed by IEEE 2030.5 DERSettings element name.

        Values take the shapes :meth:`fetch_nameplate` describes. ``setMaxW``
        is required. ``modesEnabled`` is the DERControlType bitmap;
        ``doeModesEnabled`` is the CSIP-AUS extension bitmap and defaults to
        the export and import limits.
        """
        return {
            "setMaxW": None,
            "setMaxVA": None,
            "setMaxVar": None,
            "setMaxVarNeg": None,
            "setMinPFOverExcited": None,
            "setMinPFUnderExcited": None,
            "setMaxChargeRateW": None,
            "setMaxChargeRateVA": None,
            "setMaxDischargeRateW": None,
            "setMaxDischargeRateVA": None,
            "setMaxWh": None,
            "setMaxAh": None,
            "setVNom": None,
            "setMaxV": None,
            "setMinV": None,
            "setGradW": None,
            "modesEnabled": None,
            "doeModesEnabled": None,
        }

    async def fetch_availability(self) -> dict[str, Any]:
        """Return DER availability / reserve status."""
        return {
            "availabilityDuration": None,
            "maxChargeDuration": None,
            "readingTime": None,
            "reserveChargePercent": None,
            "reservePercent": None,
            "statVarAvail": None,
            "statWAvail": None,
        }

    async def fetch_status(self) -> dict[str, Any]:
        """Return DER operational status."""
        return {
            "alarmStatus": 0,
            "connectStatus": {"dateTime": None, "value": None},
            "genConnectStatus": {"dateTime": None, "value": None},
            "inverterStatus": {"dateTime": None, "value": None},
            "manufacturerStatus": {"dateTime": None, "value": None},
            "operationalModeStatus": {"dateTime": None, "value": None},
            "stateOfChargeStatus": {"dateTime": None, "value": None},
            "localControlModeStatus": None,
            "storageModeStatus": None,
            "storConnectStatus": None,
            "readingTime": None,
        }

    # Controls. Each method receives one IEEE 2030.5 control element; see
    # py20305.connectors.modes for the parameter dict. A connector overrides
    # the methods for the functions its device has.

    # ------------------------------------------------------------------
    # DERControlBase elements
    # ------------------------------------------------------------------

    async def update_op_mod_connect(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModConnect."""
        return None

    async def update_op_mod_energize(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModEnergize."""
        return None

    async def update_op_mod_delta_var(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModDeltaVar."""
        return None

    async def update_op_mod_delta_w(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModDeltaW."""
        return None

    async def update_op_mod_fixed_pf_absorb_w(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModFixedPFAbsorbW."""
        return None

    async def update_op_mod_fixed_pf_inject_w(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModFixedPFInjectW."""
        return None

    async def update_op_mod_fixed_v(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModFixedV."""
        return None

    async def update_op_mod_fixed_var(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModFixedVar."""
        return None

    async def update_op_mod_fixed_w(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModFixedW."""
        return None

    async def update_op_mod_freq_droop(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModFreqDroop."""
        return None

    async def update_op_mod_freq_watt(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModFreqWatt."""
        return None

    async def update_op_mod_grid_connect_permit(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModGridConnectPermit."""
        return None

    async def update_op_mod_hfrt_may_trip(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModHFRTMayTrip."""
        return None

    async def update_op_mod_hfrt_must_trip(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModHFRTMustTrip."""
        return None

    async def update_op_mod_hvrt_may_trip(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModHVRTMayTrip."""
        return None

    async def update_op_mod_hvrt_momentary_cessation(
        self, params: dict[str, Any]
    ) -> ConnectorPayload:
        """Apply or withdraw opModHVRTMomentaryCessation."""
        return None

    async def update_op_mod_hvrt_must_trip(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModHVRTMustTrip."""
        return None

    async def update_op_mod_island_permit(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModIslandPermit."""
        return None

    async def update_op_mod_lfrt_may_trip(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModLFRTMayTrip."""
        return None

    async def update_op_mod_lfrt_must_trip(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModLFRTMustTrip."""
        return None

    async def update_op_mod_lvrt_may_trip(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModLVRTMayTrip."""
        return None

    async def update_op_mod_lvrt_momentary_cessation(
        self, params: dict[str, Any]
    ) -> ConnectorPayload:
        """Apply or withdraw opModLVRTMomentaryCessation."""
        return None

    async def update_op_mod_lvrt_must_trip(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModLVRTMustTrip."""
        return None

    async def update_op_mod_max_lim_pct_va_absorb(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModMaxLimPctVAAbsorb."""
        return None

    async def update_op_mod_max_lim_pct_va_inject(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModMaxLimPctVAInject."""
        return None

    async def update_op_mod_max_lim_pct_var_absorb(
        self, params: dict[str, Any]
    ) -> ConnectorPayload:
        """Apply or withdraw opModMaxLimPctVarAbsorb."""
        return None

    async def update_op_mod_max_lim_pct_var_inject(
        self, params: dict[str, Any]
    ) -> ConnectorPayload:
        """Apply or withdraw opModMaxLimPctVarInject."""
        return None

    async def update_op_mod_max_lim_pct_w_absorb(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModMaxLimPctWAbsorb."""
        return None

    async def update_op_mod_max_lim_var_absorb(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModMaxLimVarAbsorb."""
        return None

    async def update_op_mod_max_lim_var_inject(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModMaxLimVarInject."""
        return None

    async def update_op_mod_max_lim_w(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModMaxLimW."""
        return None

    async def update_op_mod_max_lim_w_absorb(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModMaxLimWAbsorb."""
        return None

    async def update_op_mod_max_lim_w_inject(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModMaxLimWInject."""
        return None

    async def update_op_mod_target_v(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModTargetV."""
        return None

    async def update_op_mod_target_var(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModTargetVar."""
        return None

    async def update_op_mod_target_w(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModTargetW."""
        return None

    async def update_op_mod_volt_var(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModVoltVar."""
        return None

    async def update_op_mod_volt_watt(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModVoltWatt."""
        return None

    async def update_op_mod_watt_pf(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModWattPF."""
        return None

    async def update_op_mod_watt_var(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModWattVar."""
        return None

    # ------------------------------------------------------------------
    # CSIP-AUS dynamic operating envelope limits
    # ------------------------------------------------------------------

    async def update_op_mod_exp_lim_w(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModExpLimW."""
        return None

    async def update_op_mod_imp_lim_w(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModImpLimW."""
        return None

    async def update_op_mod_gen_lim_w(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModGenLimW."""
        return None

    async def update_op_mod_load_lim_w(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply or withdraw opModLoadLimW."""
        return None

    # ------------------------------------------------------------------
    # DefaultDERControl settings
    # ------------------------------------------------------------------

    async def update_set_es_delay(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply setESDelay. IEEE 2030.5 updates the setting; it is never withdrawn."""
        return None

    async def update_set_es_high_freq(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply setESHighFreq. IEEE 2030.5 updates the setting; it is never withdrawn."""
        return None

    async def update_set_es_high_volt(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply setESHighVolt. IEEE 2030.5 updates the setting; it is never withdrawn."""
        return None

    async def update_set_es_low_freq(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply setESLowFreq. IEEE 2030.5 updates the setting; it is never withdrawn."""
        return None

    async def update_set_es_low_volt(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply setESLowVolt. IEEE 2030.5 updates the setting; it is never withdrawn."""
        return None

    async def update_set_es_ramp_tms(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply setESRampTms. IEEE 2030.5 updates the setting; it is never withdrawn."""
        return None

    async def update_set_es_random_delay(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply setESRandomDelay. IEEE 2030.5 updates the setting; it is never withdrawn."""
        return None

    async def update_set_grad_w(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply setGradW. IEEE 2030.5 updates the setting; it is never withdrawn."""
        return None

    async def update_set_soft_grad_w(self, params: dict[str, Any]) -> ConnectorPayload:
        """Apply setSoftGradW. IEEE 2030.5 updates the setting; it is never withdrawn."""
        return None

    # ------------------------------------------------------------------
    # Schedule notifications (informational push; see ScheduleNotification)
    # ------------------------------------------------------------------

    async def on_schedule_notification(self, notification: ScheduleNotification) -> None:
        """Single transport for all relayed schedule streams.

        Called by the core on every change to a control/baseline affecting this
        connector, so downstream logic has current schedule state without
        polling. The default fans out to the per-stream ``notification_*``
        convenience methods; override either this transport or the specific
        stream methods. Informational only -- exceptions are logged and
        swallowed by the core, never affecting dispatch.
        """
        handler = getattr(self, f"notification_{notification.stream}", None)
        if handler is not None:
            await handler(notification)

    async def notification_control(self, notification: ScheduleNotification) -> None:
        """A scheduled DERControl was added/updated/activated/superseded/etc."""
        return None

    async def notification_default_baseline(self, notification: ScheduleNotification) -> None:
        """The program's DefaultDERControl baseline was added or changed."""
        return None

    async def notification_doe(self, notification: ScheduleNotification) -> None:
        """A Dynamic Operating Envelope (export/import/gen/load W-limit) changed."""
        return None

    async def notification_price(self, notification: ScheduleNotification) -> None:
        """The active pricing interval (TimeTariffInterval) changed. Relay-only:
        the connector decides whether to act on the price.

        Transition ``active`` carries the new interval's prices. Transition
        ``completed`` or ``cancelled`` reports that the active interval ended
        with no interval after it; its payload is the ended interval's."""
        return None

    async def notification_drlc(self, notification: ScheduleNotification) -> None:
        """A demand-response (EndDeviceControl) schedule changed (future stream)."""
        return None

    async def notification_flow_reservation(self, notification: ScheduleNotification) -> None:
        """A flow-reservation window changed (future stream)."""
        return None
fetch_monitoring async
fetch_monitoring() -> list[Reading]

Return the device's measurements, one :class:Reading each.

Each reading states its IEEE 2030.5 ReadingType (uom, phase, kind, data_qualifier, ...) and its value in engineering units. Real and reactive power are signed in the frame of the device's role (see :class:~py20305.connectors.reading.Reading); a reading profile that posts another convention converts them. A quantity the device does not measure is left out. Give each reading a distinct ReadingType, multiplier included: a second reading with the same one is dropped and a warning is logged.

Source code in src/py20305/connectors/base.py
async def fetch_monitoring(self) -> list[Reading]:
    """Return the device's measurements, one :class:`Reading` each.

    Each reading states its IEEE 2030.5 ReadingType (``uom``, ``phase``,
    ``kind``, ``data_qualifier``, ...) and its value in engineering units.
    Real and reactive power are signed in the frame of the device's role
    (see :class:`~py20305.connectors.reading.Reading`); a reading profile
    that posts another convention converts them. A quantity the device does
    not measure is left out. Give each reading a distinct ReadingType,
    multiplier included: a second reading with the same one is dropped and
    a warning is logged.
    """
    return []
supported_modes2
supported_modes2() -> int | None

Optional: the DERControlType2 bits this device can apply.

DERCapability modesSupported2 and DERControlResponse modesResponded2 report these, limited to what the server profile permits. Return None (the default) to derive them from the controls the connector implements: update_op_mod_max_lim_w_absorb sets bit 7, update_op_mod_max_lim_w_inject bit 8, and so on. Return an integer for a connector that implements a control method it cannot honor on this device, so the device never advertises a mode it cannot apply.

Source code in src/py20305/connectors/base.py
def supported_modes2(self) -> int | None:
    """Optional: the DERControlType2 bits this device can apply.

    DERCapability ``modesSupported2`` and DERControlResponse
    ``modesResponded2`` report these, limited to what the server profile
    permits. Return ``None`` (the default) to derive them from the controls
    the connector implements: ``update_op_mod_max_lim_w_absorb`` sets bit 7,
    ``update_op_mod_max_lim_w_inject`` bit 8, and so on. Return an integer
    for a connector that implements a control method it cannot honor on this
    device, so the device never advertises a mode it cannot apply.
    """
    return None
declared_readings
declared_readings() -> frozenset[ReadingIdentity] | None

Optional: the readings this device provides, fixed for its life.

Each is a :class:~py20305.connectors.reading.ReadingIdentity (uom, phase, kind, data qualifier, accumulation behaviour, flow direction and multiplier), or a :class:~py20305.connectors.reading.Reading standing for its identity. Under the SIGNED_AS_REPORTED reading profile the MirrorUsagePoint registers exactly these readings, from the first cycle, even one with no values (a charger with no vehicle plugged in), so it is posted once and never re-posted for a reading that appears later. A reading returned by fetch_monitoring but not declared is not posted. Return None (the default) to register the readings as they appear. Other profiles ignore it.

Source code in src/py20305/connectors/base.py
def declared_readings(self) -> frozenset[ReadingIdentity] | None:
    """Optional: the readings this device provides, fixed for its life.

    Each is a :class:`~py20305.connectors.reading.ReadingIdentity` (uom,
    phase, kind, data qualifier, accumulation behaviour, flow direction and
    multiplier), or a :class:`~py20305.connectors.reading.Reading` standing
    for its identity. Under the ``SIGNED_AS_REPORTED`` reading profile the
    MirrorUsagePoint registers exactly these readings, from the first
    cycle, even one with no values (a charger with no vehicle plugged in),
    so it is posted once and never re-posted for a reading that appears
    later. A reading returned by ``fetch_monitoring`` but not declared is
    not posted. Return ``None`` (the default) to register the readings as
    they appear. Other profiles ignore it.
    """
    return None
fetch_nameplate async
fetch_nameplate() -> dict[str, Any]

Return DER ratings keyed by IEEE 2030.5 DERCapability element name.

A value is a number, {"value": ..., "multiplier": ...}, or for a power factor {"displacement": ..., "multiplier": ...}. rtgMaxW is required. modesSupported is the DERControlType bitmap; doeModesSupported is the CSIP-AUS extension bitmap and defaults to all four limits. An absent or None key is not reported; an explicit 0 is.

Source code in src/py20305/connectors/base.py
async def fetch_nameplate(self) -> dict[str, Any]:
    """Return DER ratings keyed by IEEE 2030.5 DERCapability element name.

    A value is a number, ``{"value": ..., "multiplier": ...}``, or for a
    power factor ``{"displacement": ..., "multiplier": ...}``. ``rtgMaxW``
    is required. ``modesSupported`` is the DERControlType bitmap;
    ``doeModesSupported`` is the CSIP-AUS extension bitmap and defaults to
    all four limits. An absent or ``None`` key is not reported; an explicit
    0 is.
    """
    return {
        "rtgMaxW": None,
        "rtgMaxVA": None,
        "rtgMaxVar": None,
        "rtgMaxVarNeg": None,
        "rtgMaxA": None,
        "rtgOverExcitedW": None,
        "rtgOverExcitedPF": None,
        "rtgUnderExcitedW": None,
        "rtgUnderExcitedPF": None,
        "rtgMaxChargeRateW": None,
        "rtgMaxChargeRateVA": None,
        "rtgMaxDischargeRateW": None,
        "rtgMaxDischargeRateVA": None,
        "rtgMaxWh": None,
        "rtgMaxAh": None,
        "rtgVNom": None,
        "rtgMaxV": None,
        "rtgMinV": None,
        "rtgReactiveSusceptance": None,
        "rtgNormalCategory": None,
        "rtgAbnormalCategory": None,
        "modesSupported": None,
        "doeModesSupported": None,
    }
fetch_configuration async
fetch_configuration() -> dict[str, Any]

Return DER settings keyed by IEEE 2030.5 DERSettings element name.

Values take the shapes :meth:fetch_nameplate describes. setMaxW is required. modesEnabled is the DERControlType bitmap; doeModesEnabled is the CSIP-AUS extension bitmap and defaults to the export and import limits.

Source code in src/py20305/connectors/base.py
async def fetch_configuration(self) -> dict[str, Any]:
    """Return DER settings keyed by IEEE 2030.5 DERSettings element name.

    Values take the shapes :meth:`fetch_nameplate` describes. ``setMaxW``
    is required. ``modesEnabled`` is the DERControlType bitmap;
    ``doeModesEnabled`` is the CSIP-AUS extension bitmap and defaults to
    the export and import limits.
    """
    return {
        "setMaxW": None,
        "setMaxVA": None,
        "setMaxVar": None,
        "setMaxVarNeg": None,
        "setMinPFOverExcited": None,
        "setMinPFUnderExcited": None,
        "setMaxChargeRateW": None,
        "setMaxChargeRateVA": None,
        "setMaxDischargeRateW": None,
        "setMaxDischargeRateVA": None,
        "setMaxWh": None,
        "setMaxAh": None,
        "setVNom": None,
        "setMaxV": None,
        "setMinV": None,
        "setGradW": None,
        "modesEnabled": None,
        "doeModesEnabled": None,
    }
fetch_availability async
fetch_availability() -> dict[str, Any]

Return DER availability / reserve status.

Source code in src/py20305/connectors/base.py
async def fetch_availability(self) -> dict[str, Any]:
    """Return DER availability / reserve status."""
    return {
        "availabilityDuration": None,
        "maxChargeDuration": None,
        "readingTime": None,
        "reserveChargePercent": None,
        "reservePercent": None,
        "statVarAvail": None,
        "statWAvail": None,
    }
fetch_status async
fetch_status() -> dict[str, Any]

Return DER operational status.

Source code in src/py20305/connectors/base.py
async def fetch_status(self) -> dict[str, Any]:
    """Return DER operational status."""
    return {
        "alarmStatus": 0,
        "connectStatus": {"dateTime": None, "value": None},
        "genConnectStatus": {"dateTime": None, "value": None},
        "inverterStatus": {"dateTime": None, "value": None},
        "manufacturerStatus": {"dateTime": None, "value": None},
        "operationalModeStatus": {"dateTime": None, "value": None},
        "stateOfChargeStatus": {"dateTime": None, "value": None},
        "localControlModeStatus": None,
        "storageModeStatus": None,
        "storConnectStatus": None,
        "readingTime": None,
    }
update_op_mod_connect async
update_op_mod_connect(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModConnect.

Source code in src/py20305/connectors/base.py
async def update_op_mod_connect(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModConnect."""
    return None
update_op_mod_energize async
update_op_mod_energize(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModEnergize.

Source code in src/py20305/connectors/base.py
async def update_op_mod_energize(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModEnergize."""
    return None
update_op_mod_delta_var async
update_op_mod_delta_var(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModDeltaVar.

Source code in src/py20305/connectors/base.py
async def update_op_mod_delta_var(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModDeltaVar."""
    return None
update_op_mod_delta_w async
update_op_mod_delta_w(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModDeltaW.

Source code in src/py20305/connectors/base.py
async def update_op_mod_delta_w(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModDeltaW."""
    return None
update_op_mod_fixed_pf_absorb_w async
update_op_mod_fixed_pf_absorb_w(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModFixedPFAbsorbW.

Source code in src/py20305/connectors/base.py
async def update_op_mod_fixed_pf_absorb_w(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModFixedPFAbsorbW."""
    return None
update_op_mod_fixed_pf_inject_w async
update_op_mod_fixed_pf_inject_w(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModFixedPFInjectW.

Source code in src/py20305/connectors/base.py
async def update_op_mod_fixed_pf_inject_w(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModFixedPFInjectW."""
    return None
update_op_mod_fixed_v async
update_op_mod_fixed_v(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModFixedV.

Source code in src/py20305/connectors/base.py
async def update_op_mod_fixed_v(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModFixedV."""
    return None
update_op_mod_fixed_var async
update_op_mod_fixed_var(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModFixedVar.

Source code in src/py20305/connectors/base.py
async def update_op_mod_fixed_var(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModFixedVar."""
    return None
update_op_mod_fixed_w async
update_op_mod_fixed_w(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModFixedW.

Source code in src/py20305/connectors/base.py
async def update_op_mod_fixed_w(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModFixedW."""
    return None
update_op_mod_freq_droop async
update_op_mod_freq_droop(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModFreqDroop.

Source code in src/py20305/connectors/base.py
async def update_op_mod_freq_droop(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModFreqDroop."""
    return None
update_op_mod_freq_watt async
update_op_mod_freq_watt(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModFreqWatt.

Source code in src/py20305/connectors/base.py
async def update_op_mod_freq_watt(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModFreqWatt."""
    return None
update_op_mod_grid_connect_permit async
update_op_mod_grid_connect_permit(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModGridConnectPermit.

Source code in src/py20305/connectors/base.py
async def update_op_mod_grid_connect_permit(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModGridConnectPermit."""
    return None
update_op_mod_hfrt_may_trip async
update_op_mod_hfrt_may_trip(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModHFRTMayTrip.

Source code in src/py20305/connectors/base.py
async def update_op_mod_hfrt_may_trip(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModHFRTMayTrip."""
    return None
update_op_mod_hfrt_must_trip async
update_op_mod_hfrt_must_trip(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModHFRTMustTrip.

Source code in src/py20305/connectors/base.py
async def update_op_mod_hfrt_must_trip(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModHFRTMustTrip."""
    return None
update_op_mod_hvrt_may_trip async
update_op_mod_hvrt_may_trip(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModHVRTMayTrip.

Source code in src/py20305/connectors/base.py
async def update_op_mod_hvrt_may_trip(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModHVRTMayTrip."""
    return None
update_op_mod_hvrt_momentary_cessation async
update_op_mod_hvrt_momentary_cessation(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModHVRTMomentaryCessation.

Source code in src/py20305/connectors/base.py
async def update_op_mod_hvrt_momentary_cessation(
    self, params: dict[str, Any]
) -> ConnectorPayload:
    """Apply or withdraw opModHVRTMomentaryCessation."""
    return None
update_op_mod_hvrt_must_trip async
update_op_mod_hvrt_must_trip(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModHVRTMustTrip.

Source code in src/py20305/connectors/base.py
async def update_op_mod_hvrt_must_trip(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModHVRTMustTrip."""
    return None
update_op_mod_island_permit async
update_op_mod_island_permit(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModIslandPermit.

Source code in src/py20305/connectors/base.py
async def update_op_mod_island_permit(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModIslandPermit."""
    return None
update_op_mod_lfrt_may_trip async
update_op_mod_lfrt_may_trip(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModLFRTMayTrip.

Source code in src/py20305/connectors/base.py
async def update_op_mod_lfrt_may_trip(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModLFRTMayTrip."""
    return None
update_op_mod_lfrt_must_trip async
update_op_mod_lfrt_must_trip(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModLFRTMustTrip.

Source code in src/py20305/connectors/base.py
async def update_op_mod_lfrt_must_trip(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModLFRTMustTrip."""
    return None
update_op_mod_lvrt_may_trip async
update_op_mod_lvrt_may_trip(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModLVRTMayTrip.

Source code in src/py20305/connectors/base.py
async def update_op_mod_lvrt_may_trip(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModLVRTMayTrip."""
    return None
update_op_mod_lvrt_momentary_cessation async
update_op_mod_lvrt_momentary_cessation(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModLVRTMomentaryCessation.

Source code in src/py20305/connectors/base.py
async def update_op_mod_lvrt_momentary_cessation(
    self, params: dict[str, Any]
) -> ConnectorPayload:
    """Apply or withdraw opModLVRTMomentaryCessation."""
    return None
update_op_mod_lvrt_must_trip async
update_op_mod_lvrt_must_trip(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModLVRTMustTrip.

Source code in src/py20305/connectors/base.py
async def update_op_mod_lvrt_must_trip(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModLVRTMustTrip."""
    return None
update_op_mod_max_lim_pct_va_absorb async
update_op_mod_max_lim_pct_va_absorb(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModMaxLimPctVAAbsorb.

Source code in src/py20305/connectors/base.py
async def update_op_mod_max_lim_pct_va_absorb(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModMaxLimPctVAAbsorb."""
    return None
update_op_mod_max_lim_pct_va_inject async
update_op_mod_max_lim_pct_va_inject(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModMaxLimPctVAInject.

Source code in src/py20305/connectors/base.py
async def update_op_mod_max_lim_pct_va_inject(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModMaxLimPctVAInject."""
    return None
update_op_mod_max_lim_pct_var_absorb async
update_op_mod_max_lim_pct_var_absorb(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModMaxLimPctVarAbsorb.

Source code in src/py20305/connectors/base.py
async def update_op_mod_max_lim_pct_var_absorb(
    self, params: dict[str, Any]
) -> ConnectorPayload:
    """Apply or withdraw opModMaxLimPctVarAbsorb."""
    return None
update_op_mod_max_lim_pct_var_inject async
update_op_mod_max_lim_pct_var_inject(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModMaxLimPctVarInject.

Source code in src/py20305/connectors/base.py
async def update_op_mod_max_lim_pct_var_inject(
    self, params: dict[str, Any]
) -> ConnectorPayload:
    """Apply or withdraw opModMaxLimPctVarInject."""
    return None
update_op_mod_max_lim_pct_w_absorb async
update_op_mod_max_lim_pct_w_absorb(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModMaxLimPctWAbsorb.

Source code in src/py20305/connectors/base.py
async def update_op_mod_max_lim_pct_w_absorb(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModMaxLimPctWAbsorb."""
    return None
update_op_mod_max_lim_var_absorb async
update_op_mod_max_lim_var_absorb(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModMaxLimVarAbsorb.

Source code in src/py20305/connectors/base.py
async def update_op_mod_max_lim_var_absorb(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModMaxLimVarAbsorb."""
    return None
update_op_mod_max_lim_var_inject async
update_op_mod_max_lim_var_inject(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModMaxLimVarInject.

Source code in src/py20305/connectors/base.py
async def update_op_mod_max_lim_var_inject(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModMaxLimVarInject."""
    return None
update_op_mod_max_lim_w async
update_op_mod_max_lim_w(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModMaxLimW.

Source code in src/py20305/connectors/base.py
async def update_op_mod_max_lim_w(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModMaxLimW."""
    return None
update_op_mod_max_lim_w_absorb async
update_op_mod_max_lim_w_absorb(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModMaxLimWAbsorb.

Source code in src/py20305/connectors/base.py
async def update_op_mod_max_lim_w_absorb(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModMaxLimWAbsorb."""
    return None
update_op_mod_max_lim_w_inject async
update_op_mod_max_lim_w_inject(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModMaxLimWInject.

Source code in src/py20305/connectors/base.py
async def update_op_mod_max_lim_w_inject(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModMaxLimWInject."""
    return None
update_op_mod_target_v async
update_op_mod_target_v(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModTargetV.

Source code in src/py20305/connectors/base.py
async def update_op_mod_target_v(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModTargetV."""
    return None
update_op_mod_target_var async
update_op_mod_target_var(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModTargetVar.

Source code in src/py20305/connectors/base.py
async def update_op_mod_target_var(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModTargetVar."""
    return None
update_op_mod_target_w async
update_op_mod_target_w(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModTargetW.

Source code in src/py20305/connectors/base.py
async def update_op_mod_target_w(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModTargetW."""
    return None
update_op_mod_volt_var async
update_op_mod_volt_var(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModVoltVar.

Source code in src/py20305/connectors/base.py
async def update_op_mod_volt_var(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModVoltVar."""
    return None
update_op_mod_volt_watt async
update_op_mod_volt_watt(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModVoltWatt.

Source code in src/py20305/connectors/base.py
async def update_op_mod_volt_watt(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModVoltWatt."""
    return None
update_op_mod_watt_pf async
update_op_mod_watt_pf(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModWattPF.

Source code in src/py20305/connectors/base.py
async def update_op_mod_watt_pf(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModWattPF."""
    return None
update_op_mod_watt_var async
update_op_mod_watt_var(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModWattVar.

Source code in src/py20305/connectors/base.py
async def update_op_mod_watt_var(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModWattVar."""
    return None
update_op_mod_exp_lim_w async
update_op_mod_exp_lim_w(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModExpLimW.

Source code in src/py20305/connectors/base.py
async def update_op_mod_exp_lim_w(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModExpLimW."""
    return None
update_op_mod_imp_lim_w async
update_op_mod_imp_lim_w(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModImpLimW.

Source code in src/py20305/connectors/base.py
async def update_op_mod_imp_lim_w(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModImpLimW."""
    return None
update_op_mod_gen_lim_w async
update_op_mod_gen_lim_w(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModGenLimW.

Source code in src/py20305/connectors/base.py
async def update_op_mod_gen_lim_w(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModGenLimW."""
    return None
update_op_mod_load_lim_w async
update_op_mod_load_lim_w(params: dict[str, Any]) -> ConnectorPayload

Apply or withdraw opModLoadLimW.

Source code in src/py20305/connectors/base.py
async def update_op_mod_load_lim_w(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply or withdraw opModLoadLimW."""
    return None
update_set_es_delay async
update_set_es_delay(params: dict[str, Any]) -> ConnectorPayload

Apply setESDelay. IEEE 2030.5 updates the setting; it is never withdrawn.

Source code in src/py20305/connectors/base.py
async def update_set_es_delay(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply setESDelay. IEEE 2030.5 updates the setting; it is never withdrawn."""
    return None
update_set_es_high_freq async
update_set_es_high_freq(params: dict[str, Any]) -> ConnectorPayload

Apply setESHighFreq. IEEE 2030.5 updates the setting; it is never withdrawn.

Source code in src/py20305/connectors/base.py
async def update_set_es_high_freq(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply setESHighFreq. IEEE 2030.5 updates the setting; it is never withdrawn."""
    return None
update_set_es_high_volt async
update_set_es_high_volt(params: dict[str, Any]) -> ConnectorPayload

Apply setESHighVolt. IEEE 2030.5 updates the setting; it is never withdrawn.

Source code in src/py20305/connectors/base.py
async def update_set_es_high_volt(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply setESHighVolt. IEEE 2030.5 updates the setting; it is never withdrawn."""
    return None
update_set_es_low_freq async
update_set_es_low_freq(params: dict[str, Any]) -> ConnectorPayload

Apply setESLowFreq. IEEE 2030.5 updates the setting; it is never withdrawn.

Source code in src/py20305/connectors/base.py
async def update_set_es_low_freq(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply setESLowFreq. IEEE 2030.5 updates the setting; it is never withdrawn."""
    return None
update_set_es_low_volt async
update_set_es_low_volt(params: dict[str, Any]) -> ConnectorPayload

Apply setESLowVolt. IEEE 2030.5 updates the setting; it is never withdrawn.

Source code in src/py20305/connectors/base.py
async def update_set_es_low_volt(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply setESLowVolt. IEEE 2030.5 updates the setting; it is never withdrawn."""
    return None
update_set_es_ramp_tms async
update_set_es_ramp_tms(params: dict[str, Any]) -> ConnectorPayload

Apply setESRampTms. IEEE 2030.5 updates the setting; it is never withdrawn.

Source code in src/py20305/connectors/base.py
async def update_set_es_ramp_tms(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply setESRampTms. IEEE 2030.5 updates the setting; it is never withdrawn."""
    return None
update_set_es_random_delay async
update_set_es_random_delay(params: dict[str, Any]) -> ConnectorPayload

Apply setESRandomDelay. IEEE 2030.5 updates the setting; it is never withdrawn.

Source code in src/py20305/connectors/base.py
async def update_set_es_random_delay(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply setESRandomDelay. IEEE 2030.5 updates the setting; it is never withdrawn."""
    return None
update_set_grad_w async
update_set_grad_w(params: dict[str, Any]) -> ConnectorPayload

Apply setGradW. IEEE 2030.5 updates the setting; it is never withdrawn.

Source code in src/py20305/connectors/base.py
async def update_set_grad_w(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply setGradW. IEEE 2030.5 updates the setting; it is never withdrawn."""
    return None
update_set_soft_grad_w async
update_set_soft_grad_w(params: dict[str, Any]) -> ConnectorPayload

Apply setSoftGradW. IEEE 2030.5 updates the setting; it is never withdrawn.

Source code in src/py20305/connectors/base.py
async def update_set_soft_grad_w(self, params: dict[str, Any]) -> ConnectorPayload:
    """Apply setSoftGradW. IEEE 2030.5 updates the setting; it is never withdrawn."""
    return None
on_schedule_notification async
on_schedule_notification(notification: ScheduleNotification) -> None

Single transport for all relayed schedule streams.

Called by the core on every change to a control/baseline affecting this connector, so downstream logic has current schedule state without polling. The default fans out to the per-stream notification_* convenience methods; override either this transport or the specific stream methods. Informational only -- exceptions are logged and swallowed by the core, never affecting dispatch.

Source code in src/py20305/connectors/base.py
async def on_schedule_notification(self, notification: ScheduleNotification) -> None:
    """Single transport for all relayed schedule streams.

    Called by the core on every change to a control/baseline affecting this
    connector, so downstream logic has current schedule state without
    polling. The default fans out to the per-stream ``notification_*``
    convenience methods; override either this transport or the specific
    stream methods. Informational only -- exceptions are logged and
    swallowed by the core, never affecting dispatch.
    """
    handler = getattr(self, f"notification_{notification.stream}", None)
    if handler is not None:
        await handler(notification)
notification_control async
notification_control(notification: ScheduleNotification) -> None

A scheduled DERControl was added/updated/activated/superseded/etc.

Source code in src/py20305/connectors/base.py
async def notification_control(self, notification: ScheduleNotification) -> None:
    """A scheduled DERControl was added/updated/activated/superseded/etc."""
    return None
notification_default_baseline async
notification_default_baseline(notification: ScheduleNotification) -> None

The program's DefaultDERControl baseline was added or changed.

Source code in src/py20305/connectors/base.py
async def notification_default_baseline(self, notification: ScheduleNotification) -> None:
    """The program's DefaultDERControl baseline was added or changed."""
    return None
notification_doe async
notification_doe(notification: ScheduleNotification) -> None

A Dynamic Operating Envelope (export/import/gen/load W-limit) changed.

Source code in src/py20305/connectors/base.py
async def notification_doe(self, notification: ScheduleNotification) -> None:
    """A Dynamic Operating Envelope (export/import/gen/load W-limit) changed."""
    return None
notification_price async
notification_price(notification: ScheduleNotification) -> None

The active pricing interval (TimeTariffInterval) changed. Relay-only: the connector decides whether to act on the price.

Transition active carries the new interval's prices. Transition completed or cancelled reports that the active interval ended with no interval after it; its payload is the ended interval's.

Source code in src/py20305/connectors/base.py
async def notification_price(self, notification: ScheduleNotification) -> None:
    """The active pricing interval (TimeTariffInterval) changed. Relay-only:
    the connector decides whether to act on the price.

    Transition ``active`` carries the new interval's prices. Transition
    ``completed`` or ``cancelled`` reports that the active interval ended
    with no interval after it; its payload is the ended interval's."""
    return None
notification_drlc async
notification_drlc(notification: ScheduleNotification) -> None

A demand-response (EndDeviceControl) schedule changed (future stream).

Source code in src/py20305/connectors/base.py
async def notification_drlc(self, notification: ScheduleNotification) -> None:
    """A demand-response (EndDeviceControl) schedule changed (future stream)."""
    return None
notification_flow_reservation async
notification_flow_reservation(notification: ScheduleNotification) -> None

A flow-reservation window changed (future stream).

Source code in src/py20305/connectors/base.py
async def notification_flow_reservation(self, notification: ScheduleNotification) -> None:
    """A flow-reservation window changed (future stream)."""
    return None

py20305.connectors.reading

The reading a connector returns from fetch_monitoring.

A :class:Reading is one measured value with the IEEE 2030.5 ReadingType that describes it. The library posts each reading as a MirrorMeterReading and derives its mRID from the reading's identity (see :func:reading_identity), so a reading whose ReadingType differs from another's always gets a different mRID (IEEE 2030.5-2023 §10.11.3 Rule n).

The module imports nothing from the rest of the package, so a connector can import it without loading the client.

Reading dataclass

One measured value and the IEEE 2030.5 ReadingType that describes it.

value is in engineering units (W, var, VA, V, A, Hz, Wh, or a power factor between -1 and 1). Real and reactive power are signed in the frame of the device's role:

  • A DER and a DER meter report positive real power for power the DER delivers and negative for power it absorbs; positive reactive power for reactive power it injects (over-excited) and negative for reactive power it absorbs (under-excited).
  • A site meter reports positive real and reactive power for import, from the area EPS to the premises, which IEEE 2030.5 FlowDirectionType calls Forward.

A power factor carries the sign of its reactive power. Every other quantity is posted as a magnitude.

The remaining fields are IEEE 2030.5 ReadingType codes:

  • uom: UomType, for example 38 W, 63 var, 61 VA, 29 V, 5 A, 33 Hz, 65 cos(theta), 72 Wh.
  • phase: PhaseCode, for example 0 not applicable, 128 A, 129 AN, 132 AB, 224 ABC.
  • kind: KindType, 37 power, 12 energy, 0 not applicable.
  • data_qualifier: DataQualifierType, 12 normal, 2 average, 8 maximum, 9 minimum.
  • accumulation_behaviour: 12 instantaneous, 9 summation.
  • flow_direction: set only when the reading is direction-specific, such as an energy total delivered forward (1) or in reverse (19). None lets the reading profile choose (see py20305.telemetry.mup).
  • multiplier: the powerOfTenMultiplier to post with. None takes the library default for the unit.
  • quality_flags: this sample's qualityFlags (16 bits). None posts valid.
Source code in src/py20305/connectors/reading.py
@dataclass(frozen=True, slots=True)
class Reading:
    """One measured value and the IEEE 2030.5 ReadingType that describes it.

    ``value`` is in engineering units (W, var, VA, V, A, Hz, Wh, or a power
    factor between -1 and 1). Real and reactive power are signed in the frame of
    the device's role:

    - A DER and a DER meter report positive real power for power the DER
      delivers and negative for power it absorbs; positive reactive power for
      reactive power it injects (over-excited) and negative for reactive power
      it absorbs (under-excited).
    - A site meter reports positive real and reactive power for import, from the
      area EPS to the premises, which IEEE 2030.5 FlowDirectionType calls
      Forward.

    A power factor carries the sign of its reactive power. Every other quantity
    is posted as a magnitude.

    The remaining fields are IEEE 2030.5 ReadingType codes:

    - ``uom``: UomType, for example 38 W, 63 var, 61 VA, 29 V, 5 A, 33 Hz,
      65 cos(theta), 72 Wh.
    - ``phase``: PhaseCode, for example 0 not applicable, 128 A, 129 AN,
      132 AB, 224 ABC.
    - ``kind``: KindType, 37 power, 12 energy, 0 not applicable.
    - ``data_qualifier``: DataQualifierType, 12 normal, 2 average, 8 maximum,
      9 minimum.
    - ``accumulation_behaviour``: 12 instantaneous, 9 summation.
    - ``flow_direction``: set only when the reading is direction-specific, such
      as an energy total delivered forward (1) or in reverse (19). None lets the
      reading profile choose (see ``py20305.telemetry.mup``).
    - ``multiplier``: the powerOfTenMultiplier to post with. None takes the
      library default for the unit.
    - ``quality_flags``: this sample's qualityFlags (16 bits). None posts
      ``valid``.
    """

    uom: int
    value: float
    phase: int = 0
    kind: int = KIND_POWER
    data_qualifier: int = DATA_QUALIFIER_NORMAL
    accumulation_behaviour: int = ACCUMULATION_INSTANTANEOUS
    flow_direction: int | None = None
    multiplier: int | None = None
    quality_flags: int | None = None

ReadingIdentity

Bases: NamedTuple

The ReadingType fields that identify a reading.

Two readings with the same identity are the same measurement. multiplier is the effective powerOfTenMultiplier, after the library default is applied, because it is part of the ReadingType too.

Source code in src/py20305/connectors/reading.py
class ReadingIdentity(NamedTuple):
    """The ReadingType fields that identify a reading.

    Two readings with the same identity are the same measurement. ``multiplier``
    is the effective powerOfTenMultiplier, after the library default is applied,
    because it is part of the ReadingType too.
    """

    uom: int
    phase: int
    kind: int
    data_qualifier: int
    accumulation_behaviour: int
    flow_direction: int | None
    multiplier: int

effective_multiplier

effective_multiplier(reading: Reading, defaults: dict[int, int] | None = None) -> int

Return the powerOfTenMultiplier a reading posts with.

Source code in src/py20305/connectors/reading.py
def effective_multiplier(reading: Reading, defaults: dict[int, int] | None = None) -> int:
    """Return the powerOfTenMultiplier a reading posts with."""
    if reading.multiplier is not None:
        return reading.multiplier
    table = DEFAULT_MULTIPLIER if defaults is None else defaults
    return table.get(reading.uom, 0)

reading_identity

reading_identity(reading: Reading, defaults: dict[int, int] | None = None) -> ReadingIdentity

Return the identity of reading with its effective multiplier.

Source code in src/py20305/connectors/reading.py
def reading_identity(reading: Reading, defaults: dict[int, int] | None = None) -> ReadingIdentity:
    """Return the identity of ``reading`` with its effective multiplier."""
    return ReadingIdentity(
        reading.uom,
        reading.phase,
        reading.kind,
        reading.data_qualifier,
        reading.accumulation_behaviour,
        reading.flow_direction,
        effective_multiplier(reading, defaults),
    )

reading_key

reading_key(reading: Reading) -> str

Return a stable text key for a reading's identity, for keying stores and logs.

The multiplier is left out: a store keys a measurement, and the multiplier only says how the value is posted.

Source code in src/py20305/connectors/reading.py
def reading_key(reading: Reading) -> str:
    """Return a stable text key for a reading's identity, for keying stores and logs.

    The multiplier is left out: a store keys a measurement, and the multiplier
    only says how the value is posted.
    """
    flow = "" if reading.flow_direction is None else f":flow{reading.flow_direction}"
    return (
        f"uom{reading.uom}:phase{reading.phase}:kind{reading.kind}"
        f":dq{reading.data_qualifier}:acc{reading.accumulation_behaviour}{flow}"
    )

is_valid_reading

is_valid_reading(reading: object) -> bool

Return True when reading is a :class:Reading the library can post.

The ReadingType codes must be ints in 0..255 (each is a UInt8 in the IEEE 2030.5 schema), the multiplier in -9..9, the quality flags 16 bits, and the value a finite number. A bool is not accepted where an int or a number is expected.

Source code in src/py20305/connectors/reading.py
def is_valid_reading(reading: object) -> bool:
    """Return True when ``reading`` is a :class:`Reading` the library can post.

    The ReadingType codes must be ints in 0..255 (each is a UInt8 in the IEEE
    2030.5 schema), the multiplier in -9..9, the quality flags 16 bits, and the
    value a finite number. A bool is not accepted where an int or a number is
    expected.
    """
    if not isinstance(reading, Reading):
        return False
    codes = (
        reading.uom,
        reading.phase,
        reading.kind,
        reading.data_qualifier,
        reading.accumulation_behaviour,
    )
    if not all(_is_uint8(c) for c in codes):
        return False
    if reading.flow_direction is not None and not _is_uint8(reading.flow_direction):
        return False
    mult = reading.multiplier
    if mult is not None and (isinstance(mult, bool) or not isinstance(mult, int)):
        return False
    if mult is not None and not -9 <= mult <= 9:
        return False
    flags = reading.quality_flags
    if flags is not None and (
        isinstance(flags, bool) or not isinstance(flags, int) or not 0 <= flags <= 0xFFFF
    ):
        return False
    value = reading.value
    if isinstance(value, bool) or not isinstance(value, int | float):
        return False
    return value == value and value not in (float("inf"), float("-inf"))

py20305.connectors.modes

Control dispatch table: DERControlBase elements to connector methods.

Each IEEE 2030.5 control element has one connector method, update_<element>, named after the element in snake case (opModVoltVar -> update_op_mod_volt_var). The method receives one parameter dict:

  • enabled: True when the control sets the element, False when the element is no longer commanded and the device should return to its own default for that function.
  • value: the element's value as IEEE 2030.5 defines it, present when enabled is True. Keys are the IEEE 2030.5 element names. A curve link is resolved to the DERCurve it references (curveType, xMultiplier, yMultiplier, yRefType, CurveData and the rest). A PerCent or SignedPerCent is the integer in hundredths of a percent. A power is {"value": ..., "multiplier": ...}. A boolean is a bool.
  • rampTms: the DERControlBase rampTms, in hundredths of a second, when the control sets it.

The table covers every DERControlBase element, the CSIP-AUS dynamic operating envelope limits and the DefaultDERControl settings.

ControlElement dataclass

One IEEE 2030.5 control element and the connector method that receives it.

Source code in src/py20305/connectors/modes.py
@dataclass(frozen=True)
class ControlElement:
    """One IEEE 2030.5 control element and the connector method that receives it."""

    #: The IEEE 2030.5 element name, for example ``opModVoltVar``.
    element: str
    #: The attribute on the parsed model, or "" for a CSIP-AUS limit.
    field: str
    #: How the value is read: ``CURVE``, ``VALUE`` or ``DOE_LIMIT``.
    kind: str = VALUE

    @property
    def method(self) -> str:
        """Return the connector method name, ``update_<element in snake case>``."""
        return f"update_{snake_case(self.element)}"

    @property
    def control(self) -> str:
        """Return the control name recorded for a write: the method without ``update_``."""
        return snake_case(self.element)
method property
method: str

Return the connector method name, update_<element in snake case>.

control property
control: str

Return the control name recorded for a write: the method without update_.

snake_case

snake_case(element: str) -> str

Return an IEEE 2030.5 element name in snake case.

A run of capitals is one word: opModHVRTMustTrip -> op_mod_hvrt_must_trip, opModFixedPFInjectW -> op_mod_fixed_pf_inject_w.

Source code in src/py20305/connectors/modes.py
def snake_case(element: str) -> str:
    """Return an IEEE 2030.5 element name in snake case.

    A run of capitals is one word: ``opModHVRTMustTrip`` ->
    ``op_mod_hvrt_must_trip``, ``opModFixedPFInjectW`` ->
    ``op_mod_fixed_pf_inject_w``.
    """
    spaced = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", element)
    spaced = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", spaced)
    return spaced.lower()

element_value

element_value(obj: Any) -> Any

Return a parsed IEEE 2030.5 value as plain data keyed by element name.

A model whose only content is value (a PerCent, an enumeration, a multiplier) becomes that value. Bytes become upper-case hex. None fields are left out.

Source code in src/py20305/connectors/modes.py
def element_value(obj: Any) -> Any:
    """Return a parsed IEEE 2030.5 value as plain data keyed by element name.

    A model whose only content is ``value`` (a PerCent, an enumeration, a
    multiplier) becomes that value. Bytes become upper-case hex. ``None``
    fields are left out.
    """
    if obj is None or isinstance(obj, bool | int | float | str):
        return obj
    if isinstance(obj, bytes):
        return obj.hex().upper()
    if isinstance(obj, list | tuple):
        return [element_value(item) for item in obj]
    if not hasattr(type(obj), "model_fields"):
        return obj
    out: dict[str, Any] = {}
    for attribute, name in _xml_names(type(obj)):
        value = getattr(obj, attribute, None)
        if value is None or value == []:
            continue
        out[name] = element_value(value)
    if set(out) == {"value"}:
        return out["value"]
    return out

translate_controls

translate_controls(base: DercontrolBase, curves: list[Dercurve1]) -> list[tuple[str, dict[str, Any]]]

Return (method, params) for every element base sets.

An absent element is skipped. An element marked disabled="true" is withdrawn ({"enabled": False}), as is a curve element whose curve the client does not hold. rampTms, when set, is added to every call that applies an element.

Source code in src/py20305/connectors/modes.py
def translate_controls(
    base: DercontrolBase,
    curves: list[Dercurve1],
) -> list[tuple[str, dict[str, Any]]]:
    """Return ``(method, params)`` for every element ``base`` sets.

    An absent element is skipped. An element marked ``disabled="true"`` is
    withdrawn (``{"enabled": False}``), as is a curve element whose curve the
    client does not hold. ``rampTms``, when set, is added to every call that
    applies an element.
    """
    results: list[tuple[str, dict[str, Any]]] = []
    for element in CONTROL_ELEMENTS + DOE_ELEMENTS:
        params = _element_params(element, base, curves)
        if params is None:
            continue
        if base.ramp_tms is not None and params.get("enabled"):
            params["rampTms"] = base.ramp_tms
        results.append((element.method, params))
    return results

translate_default_controls

translate_default_controls(dderc: DefaultDercontrol1, curves: list[Dercurve1]) -> list[tuple[str, dict[str, Any]]]

Return (method, params) for a DefaultDERControl.

The DERControlBase elements as :func:translate_controls returns them, then each DefaultDERControl setting it carries (setGradW, setSoftGradW and the enter-service settings).

Source code in src/py20305/connectors/modes.py
def translate_default_controls(
    dderc: DefaultDercontrol1,
    curves: list[Dercurve1],
) -> list[tuple[str, dict[str, Any]]]:
    """Return ``(method, params)`` for a DefaultDERControl.

    The DERControlBase elements as :func:`translate_controls` returns them,
    then each DefaultDERControl setting it carries (``setGradW``,
    ``setSoftGradW`` and the enter-service settings).
    """
    results = translate_controls(dderc.dercontrol_base, curves)
    for element in DEFAULT_CONTROL_ELEMENTS:
        value = getattr(dderc, element.field, None)
        if value is not None:
            results.append((element.method, {"enabled": True, "value": element_value(value)}))
    return results

modes_supported2

modes_supported2(connector: object) -> int

Return the DERControlType2 bits for the controls connector can apply.

A connector that defines supported_modes2() and returns an integer states the bitmap itself: for a connector that implements a control method but cannot honor it on this device. Otherwise a control counts as supported when the connector implements its update_<element> method. The base class declares every one as a no-op, so inheriting it is not support.

Source code in src/py20305/connectors/modes.py
def modes_supported2(connector: object) -> int:
    """Return the DERControlType2 bits for the controls ``connector`` can apply.

    A connector that defines ``supported_modes2()`` and returns an integer
    states the bitmap itself: for a connector that implements a control method
    but cannot honor it on this device. Otherwise a control counts as supported
    when the connector implements its ``update_<element>`` method. The base
    class declares every one as a no-op, so inheriting it is not support.
    """
    stated = getattr(connector, "supported_modes2", None)
    if callable(stated):
        try:
            value = stated()
        except Exception:
            logger.warning("supported_modes2() raised; deriving from the control methods")
        else:
            if isinstance(value, int) and not isinstance(value, bool):
                return value & 0x3FF
    return implemented_modes2(connector)

implemented_modes2

implemented_modes2(connector: object) -> int

Return the DERControlType2 bits of the update_<element> methods connector has.

The base class declares every method as a no-op, so inheriting it is not support. A connector's own supported_modes2() can start from this and clear the bits its device cannot apply.

Source code in src/py20305/connectors/modes.py
def implemented_modes2(connector: object) -> int:
    """Return the DERControlType2 bits of the ``update_<element>`` methods ``connector`` has.

    The base class declares every method as a no-op, so inheriting it is not
    support. A connector's own ``supported_modes2()`` can start from this and
    clear the bits its device cannot apply.
    """
    from py20305.connectors.dispatcher import ConnectorDispatcher
    from py20305.events.modes_bitmask import MODES2_BIT_OF_ELEMENT

    bits = 0
    for element, bit in MODES2_BIT_OF_ELEMENT.items():
        method, _reason = ConnectorDispatcher.control_support(
            connector, f"update_{snake_case(element)}"
        )
        if method is not None:
            bits |= 1 << bit
    return bits

implemented_doe_modes

implemented_doe_modes(connector: object) -> int

Return the CSIP-AUS DOE control bitmap of the limits connector implements.

Bit 0 is opModExpLimW, bit 1 opModImpLimW, bit 2 opModGenLimW and bit 3 opModLoadLimW (the DOEControlType bitmap in csipaus-ext.xsd). A limit counts when the dispatcher would deliver it to the connector, so inheriting the base class's no-op is not support, and a plugin-backed connector counts the limits its live offer carries.

Source code in src/py20305/connectors/modes.py
def implemented_doe_modes(connector: object) -> int:
    """Return the CSIP-AUS DOE control bitmap of the limits ``connector`` implements.

    Bit 0 is opModExpLimW, bit 1 opModImpLimW, bit 2 opModGenLimW and bit 3
    opModLoadLimW (the ``DOEControlType`` bitmap in ``csipaus-ext.xsd``). A limit
    counts when the dispatcher would deliver it to the connector, so inheriting
    the base class's no-op is not support, and a plugin-backed connector counts
    the limits its live offer carries.
    """
    from py20305.connectors.dispatcher import ConnectorDispatcher

    bits = 0
    for bit, element in enumerate(DOE_ELEMENTS):
        method, _reason = ConnectorDispatcher.control_support(connector, element.method)
        if method is not None:
            bits |= 1 << bit
    return bits

py20305.connectors.config

Typed configuration for the devices a connector talks to.

One model per connector type, discriminated on type, so a configuration file naming a connector gets that connector's fields validated and nothing else. :data:DeviceConfig is the union to annotate with; :class:~py20305.connectors.registry.ConnectorConfigRegistry consumes it.

To add a connector type, subclass :class:_DeviceConfigBase with a literal type and add it to the union below and to the registry's class map.

SunSpecDeviceConfig

Bases: _DeviceConfigBase

SunSpec Modbus device configuration.

Covers the three transports the connector speaks: plain Modbus TCP, Modbus RTU over a serial port, and Modbus TCP wrapped in TLS. Fields for the transports not in use are ignored, so one shape covers all three.

Source code in src/py20305/connectors/sunspec/config.py
class SunSpecDeviceConfig(_DeviceConfigBase):
    """SunSpec Modbus device configuration.

    Covers the three transports the connector speaks: plain Modbus TCP,
    Modbus RTU over a serial port, and Modbus TCP wrapped in TLS. Fields for
    the transports not in use are ignored, so one shape covers all three.
    """

    type: Literal["sunspec"] = "sunspec"
    transport: Literal["tcp", "rtu", "tcp+tls"] = "tcp"
    host: str = "127.0.0.1"
    port: int = 8502
    serial_port: str = "/dev/ttyUSB0"
    baudrate: int = 9600
    parity: str = "N"
    ca_path: str | None = None
    cert_path: str | None = None
    key_path: str | None = None
    insecure: bool = False
    unit_id: int = 1
    timeout: int = 5
    scan_retries: int = 3
    scan_retry_delay: float = 2.0
    der_type: int = 83
    power_sign: Literal["auto", "import_positive", "export_positive"] = Field(
        default="auto",
        description=(
            "Meters only: which sign of the meter's real power is import. 'auto' "
            "learns it from which of the meter's import and export energy totals "
            "rises while real power is not zero, and reports no real or reactive "
            "power until it has."
        ),
    )

    @model_validator(mode="after")
    def _power_sign_needs_a_meter(self) -> Self:
        """Reject ``power_sign`` on a device that is not a meter."""
        if "power_sign" in self.model_fields_set and self.role == "der":
            raise ValueError("power_sign applies to role site_meter or der_meter only")
        return self

    def connector_kwargs(self) -> dict[str, Any]:
        """Return the connector's keyword arguments, with the role it reads the device as."""
        return {**super().connector_kwargs(), "role": self.role}
connector_kwargs
connector_kwargs() -> dict[str, Any]

Return the connector's keyword arguments, with the role it reads the device as.

Source code in src/py20305/connectors/sunspec/config.py
def connector_kwargs(self) -> dict[str, Any]:
    """Return the connector's keyword arguments, with the role it reads the device as."""
    return {**super().connector_kwargs(), "role": self.role}

PrintDemoDeviceConfig

Bases: _DeviceConfigBase

A device that logs what it would have done instead of doing it.

Needs no hardware, which makes it the connector to point at when trying the client against a utility server for the first time.

Source code in src/py20305/connectors/config.py
class PrintDemoDeviceConfig(_DeviceConfigBase):
    """A device that logs what it would have done instead of doing it.

    Needs no hardware, which makes it the connector to point at when trying
    the client against a utility server for the first time.
    """

    type: Literal["print_demo"] = "print_demo"

CustomDeviceConfig

Bases: _DeviceConfigBase

A connector supplied by import path.

The escape hatch for a device this package has no connector for: point class_path at your own :class:~py20305.connectors.base.BaseConnector subclass and it is constructed with init_kwargs.

Source code in src/py20305/connectors/config.py
class CustomDeviceConfig(_DeviceConfigBase):
    """A connector supplied by import path.

    The escape hatch for a device this package has no connector for: point
    ``class_path`` at your own
    :class:`~py20305.connectors.base.BaseConnector` subclass and it
    is constructed with ``init_kwargs``.
    """

    type: Literal["custom"] = "custom"
    class_path: str = Field(description="Full Python import path for connector class")
    init_kwargs: dict[str, Any] = Field(default_factory=dict)

py20305.connectors.sunspec.connector

The SunSpec Modbus connector, on the IEEE 2030.5 connector contract.

:class:SunSpecConnector drives a SunSpec device over Modbus TCP, Modbus RTU or Modbus TCP with TLS through the Modbus core, and converts what it reads and writes in :mod:py20305.connectors.sunspec._ieee2030_5. Nothing SunSpec leaves this package: monitoring is a list of readings, ratings and settings use the DERCapability and DERSettings element names, status uses the DERStatus types, and controls arrive as update_<element> calls.

A DER is read through models 701 to 705 (and 706, 712 and 713 where the device has them), and its state of charge through model 713, 802 or 124. A meter is read through models 201 to 204, 211 to 214 or 220; set its role to site_meter or der_meter, and power_sign when the meter's sign of real power is known.

Needs the sunspec extra (pip install py20305[sunspec]).

SunSpecConnector

Bases: BaseConnector

A SunSpec Modbus device, presented with the IEEE 2030.5 connector contract.

Takes the keyword arguments of :class:~py20305.connectors.sunspec.config.SunSpecDeviceConfig's connector_kwargs(). Construction connects to the device and scans its models; a device that refuses the scan raises :class:~py20305.connectors.errors.ConnectorConnectionError.

Elements the device has no write for keep the base class's no-op, so the dispatcher reports them as unsupported by design.

Source code in src/py20305/connectors/sunspec/connector.py
class SunSpecConnector(BaseConnector):
    """A SunSpec Modbus device, presented with the IEEE 2030.5 connector contract.

    Takes the keyword arguments of
    :class:`~py20305.connectors.sunspec.config.SunSpecDeviceConfig`'s
    ``connector_kwargs()``. Construction connects to the device and scans its
    models; a device that refuses the scan raises
    :class:`~py20305.connectors.errors.ConnectorConnectionError`.

    Elements the device has no write for keep the base class's no-op, so the
    dispatcher reports them as unsupported by design.
    """

    connector_name: str = "SunSpecConnector"
    #: It reaches the device over Modbus, so its exchanges say so.
    telemetry_protocol: str = "modbus"
    #: A Modbus unit names one device.
    devices_per_endpoint: str = "one"
    #: The registry passes the client's reading profile; see ``__init__``.
    takes_reading_profile: bool = True

    def __init__(
        self, *, reading_profile: ReadingProfile = ReadingProfile.DEFAULT, **kwargs: Any
    ) -> None:
        """Connect to the device and scan its models.

        ``reading_profile`` is the client's. Under
        ``SIGNED_LOAD_CONVENTION`` the real, reactive and apparent power
        totals and the state of energy carry the wiring's PhaseCode, as that
        profile registers them; under ``DEFAULT`` they are unphased.
        """
        from py20305.diagnostics import report

        self._core = SunSpecModbusConnector(report=report, **kwargs)
        self._controls = convert.Controls()
        self._lock: asyncio.Lock | None = None
        self._lock_loop: asyncio.AbstractEventLoop | None = None
        self.der_type = int(kwargs.get("der_type", 83))
        self._line_to_line_voltage = kwargs.get("role", "der") == "der"
        self._phased_totals = reading_profile is ReadingProfile.SIGNED_LOAD_CONVENTION
        #: The wiring (``ACType``) the device last stated.
        self._wiring: int | None = None

    @property
    def endpoint_id(self) -> str:
        """Return ``host:port`` for TCP or ``rtu:<line>`` for serial."""
        return self._core.endpoint_id

    async def fetch_monitoring(self) -> list[Reading]:
        values = await self._core.fetch_monitoring()
        stated = values.get("ACType")
        if isinstance(stated, int) and not isinstance(stated, bool):
            self._wiring = stated
        return convert.readings(
            values,
            line_to_line_voltage=self._line_to_line_voltage,
            phased_totals=self._phased_totals,
            wiring=self._wiring,
        )

    async def fetch_nameplate(self) -> dict[str, Any]:
        values = await self._core.fetch_nameplate()
        # The core read model 702 for the ratings, so the model holds them.
        models = self._core._target.models
        return convert.nameplate(values, models[702][0] if models.get(702) else None)

    async def fetch_configuration(self) -> dict[str, Any]:
        return convert.settings(await self._core.fetch_configuration())

    async def fetch_status(self) -> dict[str, Any]:
        status = convert.status(await self._core.fetch_status())
        # The state of charge comes from the last monitoring read, which reads
        # the storage models; IEEE 2030.5 PerCent is hundredths of a percent.
        soc = self._core.last_state_of_charge
        if soc is not None:
            percent, when = soc
            status["stateOfChargeStatus"] = {"dateTime": when, "value": round(percent * 100)}
        return status

    def supported_modes2(self) -> int | None:
        """Return the DERControlType2 bits this device can apply.

        The connector implements opModMaxLimWAbsorb for every device, but a
        device with no charge-rate limit applies nothing for it, so bit 7 is
        left out for that device. The other bits follow the controls the
        connector implements.
        """
        bits = implemented_modes2(self)
        if not self._core.charge_limit_supported():
            bits &= ~(1 << MODES2_BIT_OF_ELEMENT["opModMaxLimWAbsorb"])
        return bits

    def _controls_lock(self) -> asyncio.Lock:
        """Return the lock that serializes control writes, bound to the running loop."""
        loop = asyncio.get_running_loop()
        lock = getattr(self, "_lock", None)
        if lock is None or self._lock_loop is not loop:
            lock = asyncio.Lock()
            self._lock = lock
            self._lock_loop = loop
        return lock

    async def _apply(self, element: str, params: dict[str, Any]) -> ConnectorPayload:
        # One write at a time, from merging the element to the write's result:
        # a refused write puts the merged state back, and that must not undo
        # an element another call merged in the meantime.
        async with self._controls_lock():
            before = copy.deepcopy(self._controls)
            method, core_params = self._controls.translate(element, params)
            try:
                await getattr(self._core, method)(core_params)
            except BaseException:
                self._controls = before
                raise
        return None
endpoint_id property
endpoint_id: str

Return host:port for TCP or rtu:<line> for serial.

supported_modes2
supported_modes2() -> int | None

Return the DERControlType2 bits this device can apply.

The connector implements opModMaxLimWAbsorb for every device, but a device with no charge-rate limit applies nothing for it, so bit 7 is left out for that device. The other bits follow the controls the connector implements.

Source code in src/py20305/connectors/sunspec/connector.py
def supported_modes2(self) -> int | None:
    """Return the DERControlType2 bits this device can apply.

    The connector implements opModMaxLimWAbsorb for every device, but a
    device with no charge-rate limit applies nothing for it, so bit 7 is
    left out for that device. The other bits follow the controls the
    connector implements.
    """
    bits = implemented_modes2(self)
    if not self._core.charge_limit_supported():
        bits &= ~(1 << MODES2_BIT_OF_ELEMENT["opModMaxLimWAbsorb"])
    return bits

py20305.connectors.registry

Connector configuration registry with lazy instantiation.

Loads connector definitions from typed DeviceConfig objects and materializes them lazily on first access. Supports case-insensitive LFDI lookup.

ConnectorRegistryError

Bases: RuntimeError

Raised when a connector configuration cannot be materialized.

Source code in src/py20305/connectors/registry.py
class ConnectorRegistryError(RuntimeError):
    """Raised when a connector configuration cannot be materialized."""

LazyConnectorProxy

Defers connector construction until the first attribute access.

Source code in src/py20305/connectors/registry.py
class LazyConnectorProxy:
    """Defers connector construction until the first attribute access."""

    def __init__(self, name: str, factory: Callable[[], Any]) -> None:
        # Use object.__setattr__ to avoid triggering __getattr__
        object.__setattr__(self, "_name", name)
        object.__setattr__(self, "_factory", factory)
        object.__setattr__(self, "_instance", None)
        # Lazily-allocated asyncio.Lock that serialises ``aresolve`` calls
        # so two concurrent first-touch awaits don't both spawn the
        # factory (for a connector that connects and scans its device on
        # construction, that would mean two connections and two scans
        # against the same device). The lock binds to whichever loop first
        # awaited it; rebind if the running loop changes (crash-recovery
        # rebuild + session-scoped test fixtures).
        object.__setattr__(self, "_aresolve_lock", None)
        object.__setattr__(self, "_aresolve_lock_loop", None)
        # Cache for permanent construction failures (for example a device
        # that refuses the connector's scan). Without the cache, every
        # poll cycle re-runs the factory and re-scans the broken device
        # -- on a demo deployment that drove the diagnostics panel counts
        # up by ~6/min per misconfigured device. With the cache, the proxy
        # re-raises the same exception for ``_PERMANENT_FAILURE_TTL_SECONDS``
        # before letting another
        # construction attempt through, so a device that comes back
        # online (firmware reload, model registration) recovers without
        # a restart.
        object.__setattr__(self, "_permanent_failure", None)
        object.__setattr__(self, "_permanent_failure_at", None)

    def _check_cached_permanent_failure(self) -> None:
        """Re-raise the cached construction failure if it's still fresh.

        Called by both ``resolve`` and ``aresolve`` before running the
        factory. After the TTL expires the cache is cleared so the next
        call attempts construction again -- a device that operators
        repaired sees recovery within ``_PERMANENT_FAILURE_TTL_SECONDS``
        without a restart.
        """
        if self._permanent_failure is None or self._permanent_failure_at is None:
            return
        age = time.monotonic() - self._permanent_failure_at
        if age < _PERMANENT_FAILURE_TTL_SECONDS:
            raise self._permanent_failure
        # TTL expired -- clear and let the factory run again.
        logger.info(
            "LazyConnectorProxy %s: permanent-failure cache expired after %.0fs; "
            "retrying construction",
            self._name,
            age,
        )
        object.__setattr__(self, "_permanent_failure", None)
        object.__setattr__(self, "_permanent_failure_at", None)

    def _record_permanent_failure(self, exc: BaseException) -> None:
        """Cache a permanent construction failure for the TTL window."""
        object.__setattr__(self, "_permanent_failure", exc)
        object.__setattr__(self, "_permanent_failure_at", time.monotonic())

    def resolve(self) -> Any:
        """Return the underlying connector, creating it on demand.

        Synchronous: blocks the calling thread for the duration of the
        factory (which may connect to and scan the device, with retries).
        Use ``aresolve`` from the async hot paths so the event loop can keep
        handling other requests during construction.

        Permanent construction failures (factory raised
        ``ConnectorConnectionError(permanent=True)``) are cached for
        ``_PERMANENT_FAILURE_TTL_SECONDS`` and re-raised without
        re-running the factory.
        """
        if self._instance is not None:
            return self._instance
        self._check_cached_permanent_failure()
        try:
            instance = self._factory()
        except Exception as exc:
            if getattr(exc, "permanent", False):
                self._record_permanent_failure(exc)
            raise
        object.__setattr__(self, "_instance", instance)
        return instance

    def constructed(self) -> Any | None:
        """Return the connector if it has been constructed, else ``None``.

        Never constructs it, so a caller that must not wait on a device can ask.
        """
        return self._instance

    def _get_aresolve_lock(self) -> asyncio.Lock:
        """Return an ``asyncio.Lock`` bound to the running loop.

        Lazy-allocate on first call; rebind if the loop changes since
        the last allocation. ``asyncio.Lock`` instances bind to the
        loop that first awaited them and raise ``RuntimeError`` if
        reused on another loop -- which happens whenever the registry
        outlives its loop (crash-recovery rebuild; session-scoped
        fixtures in tests).
        """
        loop = asyncio.get_running_loop()
        if self._aresolve_lock is None or self._aresolve_lock_loop is not loop:
            object.__setattr__(self, "_aresolve_lock", asyncio.Lock())
            object.__setattr__(self, "_aresolve_lock_loop", loop)
        return self._aresolve_lock  # type: ignore[no-any-return]

    async def aresolve(self) -> Any:
        """Async resolver: runs ``resolve`` on a worker thread.

        First-touch construction of a real Modbus connector takes seconds
        (TCP handshake + scan + readiness retries). Calling it from an
        ``async def`` route on the client's event loop blocks every
        other coroutine for that whole window. This wrapper offloads the
        work via ``asyncio.to_thread`` so the loop stays responsive.

        Once constructed, returns the cached instance with no thread hop,
        so subsequent calls cost the same as ``resolve``.

        The lock-protected double-check around the to_thread guarantees
        the factory runs at most once per proxy even when N coroutines
        race for first-touch construction. Without it, the per-device
        4 cycle types (metering / capability / settings / status) firing
        close together at startup could each construct their own
        connector and open duplicate device connections -- the exact
        fan-out this wrapper exists to make safe. Note: ``asyncio.to_thread``
        itself uses the default ``ThreadPoolExecutor`` (size
        ``min(32, cpu_count + 4)``), so concurrent first-touch awaits
        across *different* proxies can still queue behind the pool;
        wall-clock for first dashboard load with N >> pool_size devices
        is bounded by ``ceil(N / pool_size) * scan_time``.
        """
        if self._instance is not None:
            return self._instance
        # Fast-path: a cached permanent failure within TTL re-raises
        # without taking the lock or hitting a worker thread, so the
        # 4 cycle types polling a known-broken device cost almost
        # nothing per cycle.
        self._check_cached_permanent_failure()
        async with self._get_aresolve_lock():
            # Double-check: another coroutine may have completed the
            # construction while we were waiting on the lock.
            if self._instance is not None:
                return self._instance
            self._check_cached_permanent_failure()
            return await asyncio.to_thread(self.resolve)

    def __getattr__(self, item: str) -> Any:
        return getattr(self.resolve(), item)

    def __repr__(self) -> str:
        state = "initialized" if self._instance is not None else "lazy"
        return f"<LazyConnectorProxy name={self._name!r} state={state}>"
resolve
resolve() -> Any

Return the underlying connector, creating it on demand.

Synchronous: blocks the calling thread for the duration of the factory (which may connect to and scan the device, with retries). Use aresolve from the async hot paths so the event loop can keep handling other requests during construction.

Permanent construction failures (factory raised ConnectorConnectionError(permanent=True)) are cached for _PERMANENT_FAILURE_TTL_SECONDS and re-raised without re-running the factory.

Source code in src/py20305/connectors/registry.py
def resolve(self) -> Any:
    """Return the underlying connector, creating it on demand.

    Synchronous: blocks the calling thread for the duration of the
    factory (which may connect to and scan the device, with retries).
    Use ``aresolve`` from the async hot paths so the event loop can keep
    handling other requests during construction.

    Permanent construction failures (factory raised
    ``ConnectorConnectionError(permanent=True)``) are cached for
    ``_PERMANENT_FAILURE_TTL_SECONDS`` and re-raised without
    re-running the factory.
    """
    if self._instance is not None:
        return self._instance
    self._check_cached_permanent_failure()
    try:
        instance = self._factory()
    except Exception as exc:
        if getattr(exc, "permanent", False):
            self._record_permanent_failure(exc)
        raise
    object.__setattr__(self, "_instance", instance)
    return instance
constructed
constructed() -> Any | None

Return the connector if it has been constructed, else None.

Never constructs it, so a caller that must not wait on a device can ask.

Source code in src/py20305/connectors/registry.py
def constructed(self) -> Any | None:
    """Return the connector if it has been constructed, else ``None``.

    Never constructs it, so a caller that must not wait on a device can ask.
    """
    return self._instance
aresolve async
aresolve() -> Any

Async resolver: runs resolve on a worker thread.

First-touch construction of a real Modbus connector takes seconds (TCP handshake + scan + readiness retries). Calling it from an async def route on the client's event loop blocks every other coroutine for that whole window. This wrapper offloads the work via asyncio.to_thread so the loop stays responsive.

Once constructed, returns the cached instance with no thread hop, so subsequent calls cost the same as resolve.

The lock-protected double-check around the to_thread guarantees the factory runs at most once per proxy even when N coroutines race for first-touch construction. Without it, the per-device 4 cycle types (metering / capability / settings / status) firing close together at startup could each construct their own connector and open duplicate device connections -- the exact fan-out this wrapper exists to make safe. Note: asyncio.to_thread itself uses the default ThreadPoolExecutor (size min(32, cpu_count + 4)), so concurrent first-touch awaits across different proxies can still queue behind the pool; wall-clock for first dashboard load with N >> pool_size devices is bounded by ceil(N / pool_size) * scan_time.

Source code in src/py20305/connectors/registry.py
async def aresolve(self) -> Any:
    """Async resolver: runs ``resolve`` on a worker thread.

    First-touch construction of a real Modbus connector takes seconds
    (TCP handshake + scan + readiness retries). Calling it from an
    ``async def`` route on the client's event loop blocks every
    other coroutine for that whole window. This wrapper offloads the
    work via ``asyncio.to_thread`` so the loop stays responsive.

    Once constructed, returns the cached instance with no thread hop,
    so subsequent calls cost the same as ``resolve``.

    The lock-protected double-check around the to_thread guarantees
    the factory runs at most once per proxy even when N coroutines
    race for first-touch construction. Without it, the per-device
    4 cycle types (metering / capability / settings / status) firing
    close together at startup could each construct their own
    connector and open duplicate device connections -- the exact
    fan-out this wrapper exists to make safe. Note: ``asyncio.to_thread``
    itself uses the default ``ThreadPoolExecutor`` (size
    ``min(32, cpu_count + 4)``), so concurrent first-touch awaits
    across *different* proxies can still queue behind the pool;
    wall-clock for first dashboard load with N >> pool_size devices
    is bounded by ``ceil(N / pool_size) * scan_time``.
    """
    if self._instance is not None:
        return self._instance
    # Fast-path: a cached permanent failure within TTL re-raises
    # without taking the lock or hitting a worker thread, so the
    # 4 cycle types polling a known-broken device cost almost
    # nothing per cycle.
    self._check_cached_permanent_failure()
    async with self._get_aresolve_lock():
        # Double-check: another coroutine may have completed the
        # construction while we were waiting on the lock.
        if self._instance is not None:
            return self._instance
        self._check_cached_permanent_failure()
        return await asyncio.to_thread(self.resolve)

ConnectorConfigRegistry

Resolves a device LFDI to its connector, constructing it on first use.

Holds typed device configurations and hands out a :class:LazyConnectorProxy per device. Nothing opens a socket or scans a device until something asks for that device's connector, so a configuration naming an offline device costs nothing until it is used.

LFDI lookup is case-insensitive: certificate tooling differs on hex case and a device should resolve either way.

An application with device types of its own supplies a factory_resolver rather than subclassing. That covers the cases class_path cannot: a connector that needs shared runtime state, one reached over a transport this package knows nothing about, or one whose configuration is a model defined downstream.

Source code in src/py20305/connectors/registry.py
class ConnectorConfigRegistry:
    """Resolves a device LFDI to its connector, constructing it on first use.

    Holds typed device configurations and hands out a
    :class:`LazyConnectorProxy` per device. Nothing opens a socket or scans a
    device until something asks for that device's connector, so a
    configuration naming an offline device costs nothing until it is used.

    LFDI lookup is case-insensitive: certificate tooling differs on hex case
    and a device should resolve either way.

    An application with device types of its own supplies a ``factory_resolver``
    rather than subclassing. That covers the cases ``class_path`` cannot: a
    connector that needs shared runtime state, one reached over a transport
    this package knows nothing about, or one whose configuration is a model
    defined downstream.
    """

    def __init__(
        self,
        devices: list[DeviceConfig],
        factory_resolver: Callable[[Any], Callable[[], Any] | None] | None = None,
        *,
        reading_profile: Any = None,
    ) -> None:
        """Build a registry from typed device configs.

        Args:
            devices: The configured devices. Each is resolved to a connector
                class through :data:`CONNECTOR_TYPE_MAP`, or through its own
                ``class_path`` for
                :class:`~py20305.connectors.config.CustomDeviceConfig`.
            factory_resolver: Consulted for every device before the built-in
                resolution runs. Return a zero-argument callable constructing
                the connector to claim the device, or ``None`` to let this
                package handle it. Called once per device at first resolution,
                not on every lookup, and the callable it returns is invoked
                lazily like any other -- so a resolver may close over
                expensive state without paying for it up front.
            reading_profile: The client's
                :class:`~py20305.telemetry.mup.ReadingProfile`, passed as
                ``reading_profile`` to a connector class that sets
                ``takes_reading_profile``, whose readings depend on it.
        """
        self._device_configs: dict[str, DeviceConfig] = {}
        self._device_proxies: dict[str, LazyConnectorProxy] = {}
        self._factory_resolver = factory_resolver
        self._reading_profile = reading_profile

        for device in devices:
            self._device_configs[device.lfdi] = device

    def get_connector(self, lfdi: str) -> LazyConnectorProxy | None:
        """Return a proxy for the device connector mapped to lfdi.

        LFDI comparison is case-insensitive, and the proxy is cached under the
        configured spelling so it is returned whichever spelling is asked for.
        Caching under the caller's spelling instead would mean a caller using
        a different case never hits the cache -- rebuilding the proxy and the
        connector on every lookup, which for a Modbus device is a fresh
        connection and scan each time, and which defeats the proxy's own
        failure cache and single-flight lock.
        """
        canonical = self._canonical_lfdi(lfdi)
        if canonical is None:
            return None

        cached = self._device_proxies.get(canonical)
        if cached is not None:
            return cached

        proxy = self._build_lazy_proxy(self._device_configs[canonical])
        self._device_proxies[canonical] = proxy
        return proxy

    def _canonical_lfdi(self, lfdi: str) -> str | None:
        """Return the configured spelling of ``lfdi``, or ``None`` if unknown."""
        if lfdi in self._device_configs:
            return lfdi
        wanted = lfdi.lower()
        for stored in self._device_configs:
            if stored.lower() == wanted:
                return stored
        return None

    def role_of(self, lfdi: str) -> str:
        """Return the configured role of ``lfdi``, or ``"der"`` for an unknown device.

        An unknown device keeps the behavior every device had before roles
        existed, so a caller asking about it is not told it is a meter.
        """
        canonical = self._canonical_lfdi(lfdi)
        if canonical is None:
            return "der"
        # getattr: a downstream configuration model may predate roles.
        return str(getattr(self._device_configs[canonical], "role", "der"))

    def iter_device_specs(self) -> list[DeviceConfig]:
        """Return all registered device configurations."""
        return list(self._device_configs.values())

    # ------------------------------------------------------------------
    # Internal
    # ------------------------------------------------------------------

    def _build_lazy_proxy(self, device: DeviceConfig) -> LazyConnectorProxy:
        # Three branches, in precedence order. A downstream ``factory_resolver``
        # gets first refusal, so an application can own device types this
        # package has never heard of. A ``custom`` device carries its own
        # ``class_path`` and ``init_kwargs``, the escape hatch for a connector
        # that needs no shared state. Everything else resolves through the map
        # and unpacks its model into kwargs, minus the fields every device
        # config shares.
        #
        # The proxy wraps all three identically, so a downstream connector gets
        # the same lazy construction, permanent-failure caching and
        # single-flight ``aresolve`` as a bundled one.
        from py20305.connectors.config import CustomDeviceConfig

        if self._factory_resolver is not None:
            resolved = self._factory_resolver(device)
            if resolved is not None:
                return LazyConnectorProxy(name=device.lfdi, factory=resolved)

        if isinstance(device, CustomDeviceConfig):
            class_path = device.class_path
            kwargs = device.init_kwargs
        else:
            try:
                class_path = CONNECTOR_TYPE_MAP[device.type]
            except KeyError as exc:
                known = ", ".join(sorted(CONNECTOR_TYPE_MAP))
                raise ConnectorRegistryError(
                    f"Unknown device type {device.type!r}. Known types: {known}. "
                    "For a connector this package does not ship, either configure "
                    "the device as type 'custom' with a class_path pointing at "
                    "your BaseConnector subclass, or pass a factory_resolver that "
                    "claims this type."
                ) from exc
            kwargs = device.connector_kwargs()

        reading_profile = self._reading_profile

        def factory() -> Any:
            cls = self._import_class(class_path)
            if reading_profile is not None and getattr(cls, "takes_reading_profile", False):
                return cls(**kwargs, reading_profile=reading_profile)
            return cls(**kwargs)

        return LazyConnectorProxy(name=device.lfdi, factory=factory)

    def _import_class(self, class_path: str) -> type:
        try:
            module_name, class_name = class_path.rsplit(".", 1)
        except ValueError as exc:
            raise ConnectorRegistryError(f"Invalid class path '{class_path}'.") from exc

        try:
            module = importlib.import_module(module_name)
            return getattr(module, class_name)  # type: ignore[no-any-return]
        except (ImportError, AttributeError) as exc:
            raise ConnectorRegistryError(
                f"Unable to import connector class '{class_path}'."
            ) from exc
get_connector
get_connector(lfdi: str) -> LazyConnectorProxy | None

Return a proxy for the device connector mapped to lfdi.

LFDI comparison is case-insensitive, and the proxy is cached under the configured spelling so it is returned whichever spelling is asked for. Caching under the caller's spelling instead would mean a caller using a different case never hits the cache -- rebuilding the proxy and the connector on every lookup, which for a Modbus device is a fresh connection and scan each time, and which defeats the proxy's own failure cache and single-flight lock.

Source code in src/py20305/connectors/registry.py
def get_connector(self, lfdi: str) -> LazyConnectorProxy | None:
    """Return a proxy for the device connector mapped to lfdi.

    LFDI comparison is case-insensitive, and the proxy is cached under the
    configured spelling so it is returned whichever spelling is asked for.
    Caching under the caller's spelling instead would mean a caller using
    a different case never hits the cache -- rebuilding the proxy and the
    connector on every lookup, which for a Modbus device is a fresh
    connection and scan each time, and which defeats the proxy's own
    failure cache and single-flight lock.
    """
    canonical = self._canonical_lfdi(lfdi)
    if canonical is None:
        return None

    cached = self._device_proxies.get(canonical)
    if cached is not None:
        return cached

    proxy = self._build_lazy_proxy(self._device_configs[canonical])
    self._device_proxies[canonical] = proxy
    return proxy
role_of
role_of(lfdi: str) -> str

Return the configured role of lfdi, or "der" for an unknown device.

An unknown device keeps the behavior every device had before roles existed, so a caller asking about it is not told it is a meter.

Source code in src/py20305/connectors/registry.py
def role_of(self, lfdi: str) -> str:
    """Return the configured role of ``lfdi``, or ``"der"`` for an unknown device.

    An unknown device keeps the behavior every device had before roles
    existed, so a caller asking about it is not told it is a meter.
    """
    canonical = self._canonical_lfdi(lfdi)
    if canonical is None:
        return "der"
    # getattr: a downstream configuration model may predate roles.
    return str(getattr(self._device_configs[canonical], "role", "der"))
iter_device_specs
iter_device_specs() -> list[DeviceConfig]

Return all registered device configurations.

Source code in src/py20305/connectors/registry.py
def iter_device_specs(self) -> list[DeviceConfig]:
    """Return all registered device configurations."""
    return list(self._device_configs.values())

py20305.connectors.dispatcher

ConnectorDispatcher: implements ControlDispatcher backed by connectors.

Bridges the event processing system to the connector system. Translates DERControl Pydantic models into connector method calls via the modes translation layer.

ConnectorDispatcher

Implements ControlDispatcher protocol using the connector system.

Resolves device_href to a connector via the registry and an LFDI resolver callback, then translates control models to connector calls.

Source code in src/py20305/connectors/dispatcher.py
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
class ConnectorDispatcher:
    """Implements ControlDispatcher protocol using the connector system.

    Resolves device_href to a connector via the registry and an LFDI
    resolver callback, then translates control models to connector calls.
    """

    def __init__(
        self,
        registry: ConnectorConfigRegistry,
        lfdi_resolver: Callable[[str], str | None],
        command_observer: CommandObserver | None = None,
        command_gate: CommandGate | None = None,
        telemetry: DeviceTelemetryEmitter | None = None,
        write_history: WriteHistory | None = None,
        command_intercept: CommandIntercept | None = None,
    ) -> None:
        """
        Args:
            registry: Connector registry.
            lfdi_resolver: device_href -> LFDI.
            command_observer: Where applied controls are reported. Injected
                rather than imported: the commanded plane is a host-application
                product concern and this module is client code, so the
                dependency has to point the other way. Omitted, controls apply
                exactly as before and nothing is recorded.
            telemetry: Reports each applied control to the monitoring system.
                Optional and disabled by default.
            write_history: Keeps each write, with the mRIDs that caused it, in
                the operations history. Optional; can also be attached later.
            command_intercept: Offered each permitted write that names a device
                by LFDI, before the connector. A write the intercept takes is
                not applied to the connector. Omitted, every write goes to the
                connector. See :class:`~py20305.commands.CommandIntercept`.
        """
        self._registry = registry
        self._lfdi_resolver = lfdi_resolver
        # `is None`, not `or`: an observer accumulates records, so a
        # collection-backed one is falsy while empty and `or` would silently
        # replace it with the no-op.
        self._gate = AllowAllCommands() if command_gate is None else command_gate
        self._commands = NullCommandObserver() if command_observer is None else command_observer
        self._telemetry = telemetry
        self._write_history = write_history
        self._intercept = command_intercept
        # Devices already reported as having no connector. A server can list a
        # device this process has no connector for, and every control aimed at
        # it reaches the lookup below, so without this the same warning is
        # logged once per control for as long as the device stays listed.
        self._missing_connector_reported: set[str] = set()
        self._checked_connector_classes: set[type] = set()
        #: (relay group, stream) -> the last queued schedule notification
        #: delivery. Each delivery waits for the one before it, so a connector
        #: receives a stream's notifications in the order they were relayed.
        self._relay_tails: dict[tuple[object, str], asyncio.Task[None]] = {}
        #: Relays of each stream that have not queued their deliveries yet, oldest
        #: first. A newer relay queues after each one that shares a relay group.
        self._relays_in_flight: dict[str, list[_PendingRelay]] = {}

    @property
    def telemetry(self) -> DeviceTelemetryEmitter | None:
        """The southbound telemetry emitter, if one was injected.

        The metering cycle reports through the same emitter as the control
        path, so both halves of a device's traffic land on one channel with
        one configuration behind them.
        """
        return self._telemetry

    def attach_write_history(self, history: WriteHistory | None) -> None:
        """Keep every write this dispatcher issues in ``history``, or stop with None."""
        self._write_history = history

    def _keep_write(
        self,
        label: str,
        control: str,
        params: dict[str, Any],
        *,
        outcome: str,
        at: float,
        lfdi: str | None,
        origin: str,
        applied_mrid: bytes | None,
        cause_mrid: bytes | None,
        error: str | None = None,
        error_type: str | None = None,
    ) -> None:
        """Store one write in the history, when one is attached. Never raises."""
        if self._write_history is None:
            return
        try:
            self._write_history.record(
                label,
                control,
                params,
                outcome=outcome,
                at=at,
                lfdi=lfdi,
                origin=origin,
                applied_mrid=applied_mrid,
                cause_mrid=cause_mrid,
                error=error,
                error_type=error_type,
            )
        except Exception:
            logger.debug("Write history failed for %s on %s", control, label, exc_info=True)

    @property
    def registry(self) -> ConnectorConfigRegistry:
        """The registry this dispatcher resolves through.

        Exposed so a caller wiring a second consumer -- the metering cycle,
        which reads the same devices this writes to -- resolves through the
        same registry. Constructing a second one would build a second
        connector per device and open duplicate connections to it.
        """
        return self._registry

    def takes_controls(self, lfdi: str | None) -> bool:
        """Return whether the device takes controls. A meter does not.

        Only a device configured with a meter role is refused. A device the
        registry does not know, a control with no LFDI, and a registry that
        keeps no roles all take controls, as every device did before roles
        existed.
        """
        return lfdi is None or self._role_of(lfdi) not in _METER_ROLES

    def _role_of(self, lfdi: str) -> object:
        # getattr: a registry supplied by an embedding application may keep no roles.
        role_of = getattr(self._registry, "role_of", None)
        return role_of(lfdi) if role_of is not None else "der"

    def _refuse_meter(self, lfdi: str | None) -> None:
        """Raise ``DeviceNotConfiguredError`` for a control addressed to a meter.

        A meter is configured to measure, not to be commanded, so the control
        is not applicable to it as configured: IEEE 2030.5-2023 Table 31 status
        252 (Not Applicable), the code ``DeviceNotConfiguredError`` reports. 251
        (Not Supported) would say the device lacks the function, which is a
        statement about its hardware rather than its configuration.
        """
        if not self.takes_controls(lfdi):
            raise DeviceNotConfiguredError(
                f"{lfdi} is configured as a {self._role_of(lfdi or '')}, which takes no controls"
            )

    def _skips_meter(self, lfdi: str | None, action: str) -> bool:
        """Return True, and log it, when a write that needs no response targets a meter."""
        if self.takes_controls(lfdi):
            return False
        logger.debug("Skipped %s for %s: a meter takes no controls", action, lfdi)
        return True

    async def _resolve_connector(self, device_href: str) -> BaseConnector | None:
        """Resolve a device_href to a connector instance.

        Async because first-touch construction of a real Modbus connector
        runs scan + readiness retries that block whichever thread does the
        work; offload to a worker via ``aresolve``.
        """
        from py20305.diagnostics import report

        lfdi = self._lfdi_resolver(device_href)
        if lfdi is None:
            report(
                "warnings",
                f"No LFDI found for device href {device_href}",
                source="dispatcher",
                dedup_key=f"unresolved_href:{device_href}",
                details={"device_href": device_href},
            )
            return None

        return await self._resolve_connector_by_lfdi(lfdi)

    async def supported_modes2(self, lfdi: str) -> int | None:
        """Return the DERControlType2 bits the device with ``lfdi`` can apply.

        None when the device has no connector, or its connector has not been
        constructed yet. Nothing is reported for a missing connector, since a
        response may be posted for a device the client does not drive.

        This runs on the response path, so it never constructs a connector:
        construction can connect to and scan the device with retries, and the
        acknowledgment and the activation timer wait on the response.
        """
        from py20305.connectors.modes import modes_supported2
        from py20305.connectors.registry import LazyConnectorProxy

        proxy = self._registry.get_connector(lfdi)
        if proxy is None:
            return None
        connector = proxy.constructed() if isinstance(proxy, LazyConnectorProxy) else None
        if connector is None:
            return None
        try:
            return modes_supported2(connector)
        except Exception:
            logger.debug("Could not read the supported modes for %s", lfdi[:8], exc_info=True)
            return None

    async def _resolve_connector_by_lfdi(self, lfdi: str) -> BaseConnector | None:
        """Resolve a device LFDI directly to a connector instance.

        Used by multi-device dispatch where the processor
        has already expanded a server-side EndDevice href into a list of
        local sub-device LFDIs and we skip the href→LFDI step.
        """
        from py20305.diagnostics import report, resolve

        dedup_key = f"no_connector:{lfdi}"
        proxy = self._registry.get_connector(lfdi)
        if proxy is not None:
            if lfdi in self._missing_connector_reported:
                # The device has a connector now: clear the standing warning,
                # and report again if it ever loses the connector.
                self._missing_connector_reported.discard(lfdi)
                resolve(dedup_key)
            connector: BaseConnector = await proxy.aresolve()
            self._warn_unused_update_methods(connector)
            return connector

        if lfdi in self._missing_connector_reported:
            logger.debug("No connector found for LFDI %s (already reported)", lfdi)
            return None
        self._missing_connector_reported.add(lfdi)
        report(
            "warnings",
            f"No connector found for LFDI {lfdi}; controls for this device are not applied",
            source="dispatcher",
            dedup_key=dedup_key,
            details={"lfdi": lfdi},
        )
        return None

    def _warn_unused_update_methods(self, connector: BaseConnector) -> None:
        """Warn once per connector class about ``update_*`` methods the client never calls."""
        connector_class = type(connector)
        if connector_class in self._checked_connector_classes:
            return
        self._checked_connector_classes.add(connector_class)
        unused = unused_update_methods(connector_class)
        if unused:
            logger.warning(
                "Connector %s defines %s, which the client no longer calls. Controls reach "
                "a connector through one update_<element> method per control element, "
                "for example update_op_mod_max_lim_w; until the connector defines those, "
                "the controls for the elements it does not define are not applied.",
                connector_class.__name__,
                ", ".join(unused),
            )

    async def apply_control(
        self,
        device_href: str,
        derc: Dercontrol1,
        curves: list[Dercurve1],
        *,
        origin: str = CommandOrigin.IEEE2030_5,
    ) -> None:
        """Apply a DERControl's settings to a device.

        Raises:
            CommandNotPermittedError: the gate refused at least one mode, so the
                device did not receive the control as sent. The event processor
                reports the device as rejected rather than started (IEEE
                2030.5-2023 Table 31). With a gate that answers the same for a
                device and origin throughout, as :class:`CommandGate` requires,
                no mode was written.
            DeviceNotConfiguredError: the device is configured as a meter.
            ModeNotSupportedError: the control translates to at least one mode
                and the connector implements none of them, so nothing was
                applied. A control that applies at least one mode is not
                refused for the modes the connector leaves out. The event
                processor reports the device as rejected with Table 31 status
                251 (252 for a 2018 server) rather than as started.
        """
        self._refuse_meter(self._lfdi_resolver(device_href))
        connector = await self._resolve_connector(device_href)
        await self._apply_control_to_connector(
            connector,
            derc,
            curves,
            lfdi=self._lfdi_resolver(device_href),
            device_href=device_href,
            origin=origin,
        )

    async def apply_control_by_lfdi(
        self,
        lfdi: str,
        derc: Dercontrol1,
        curves: list[Dercurve1],
        *,
        origin: str = CommandOrigin.IEEE2030_5,
    ) -> None:
        """Apply a DERControl directly to a device identified by LFDI.

        Raises:
            CommandNotPermittedError: as for :meth:`apply_control`.
            DeviceNotConfiguredError: the device is configured as a meter.
            ModeNotSupportedError: as for :meth:`apply_control`.
        """
        self._refuse_meter(lfdi)
        connector = await self._resolve_connector_by_lfdi(lfdi)
        await self._apply_control_to_connector(
            connector, derc, curves, lfdi=lfdi, device_href=None, origin=origin
        )

    async def _apply_control_to_connector(
        self,
        connector: BaseConnector | None,
        derc: Dercontrol1,
        curves: list[Dercurve1],
        *,
        lfdi: str | None,
        device_href: str | None,
        origin: str = CommandOrigin.IEEE2030_5,
    ) -> None:
        if connector is None:
            return

        label = lfdi or device_href or "<unknown>"
        # An event's own activation: what was written and what caused it are
        # the same event.
        derc_mrid = derc.m_rid.value
        translations = translate_controls(derc.dercontrol_base, curves)
        logger.debug(
            "Applying control to %s via %s (%d mode(s))",
            label,
            connector.connector_name,
            len(translations),
        )

        refused: list[str] = []
        unimplemented: list[str] = []
        declined: list[ModeNotSupportedError] = []
        for method_name, params in translations:
            method, reason = self.control_support(connector, method_name)
            if method is not None:
                logger.debug("  %s.%s(%s)", connector.connector_name, method_name, params)
                try:
                    applied = await self._apply_one(
                        method,
                        method_name,
                        params,
                        lfdi=lfdi,
                        origin=origin,
                        kind="control",
                        label=label,
                        applied_mrid=derc_mrid,
                        cause_mrid=derc_mrid,
                    )
                except ModeNotSupportedError as exc:
                    # The connector found at run time that the device cannot
                    # take this mode. Skip it like an unimplemented mode so the
                    # control's other modes are still applied.
                    unimplemented.append(method_name)
                    declined.append(exc)
                    continue
                if not applied:
                    refused.append(method_name.removeprefix("update_"))
            elif reason == BY_DESIGN:
                # This connector has no register for the mode and never claimed
                # one. Nothing an operator can do, so it does not belong in a
                # warnings surface -- and a control carrying it alongside modes
                # the connector does implement is normal traffic, not a fault.
                unimplemented.append(method_name)
                logger.debug(
                    "  %s does not implement %s; skipped",
                    connector.connector_name,
                    method_name,
                )
            else:
                unimplemented.append(method_name)
                self._report_unimplemented_mode(
                    connector, lfdi=lfdi, device_href=device_href, method_name=method_name
                )
        # Every mode is offered to the gate first, so each refused write is
        # recorded. The event processor then reports the device as rejected:
        # a status 2 (Active) would tell the server the device runs a control
        # that was never written (IEEE 2030.5-2023 Table 31).
        if refused:
            raise CommandNotPermittedError(
                f"{origin} may not command {label}: another interface holds the "
                f"command role, so {', '.join(refused)} was not applied"
            )
        self._require_an_implemented_mode(connector, label, translations, unimplemented, declined)

    async def _apply_one(
        self,
        method: Callable[[dict[str, Any]], Any],
        method_name: str,
        params: dict[str, Any],
        *,
        lfdi: str | None,
        origin: str,
        label: str,
        kind: str = "control",
        connector: BaseConnector | None = None,
        applied_mrid: bytes | None = None,
        cause_mrid: bytes | None = None,
    ) -> bool:
        """Apply one translated mode and report it to the command observer.

        ``kind`` names the apply path for the command intercept, as
        :class:`~py20305.commands.InterceptedWrite` lists them.

        Returns True when the control reached the connector or the command
        intercept took it, False when the gate refused it. The DERControl and
        named-control callers raise
        ``CommandNotPermittedError`` on a refusal; the default-control and clear
        callers report it and go on.

        Stamped before the call, like an acquisition: the write shadow compares
        this against when a readback *started*, so a command has to be marked at
        the moment it was issued rather than when it completed.

        A failure is recorded and re-raised. Swallowing it here would change the
        dispatcher's contract with the event processor, and a rejected command is
        exactly the thing an audit trail should retain.
        """
        # ``control`` drops the ``update_`` prefix so the recorded name matches
        # the management API's operation vocabulary -- one name per control,
        # whichever interface issued it.
        control = method_name.removeprefix("update_")

        # Authority is checked here because this is the one place every apply
        # path passes through -- a control, a default control, a clear and a
        # named operation. Checking at each caller instead would mean the DDERC
        # reapply and comms-loss routes each needing their own gate, which is
        # exactly how a write path ends up ungated.
        if lfdi:
            if not self._gate.may_command(lfdi, origin):
                self._report_not_commanding(lfdi, control, origin)
                self._keep_write(
                    label,
                    control,
                    params,
                    outcome="refused",
                    at=time.time(),
                    lfdi=lfdi,
                    origin=origin,
                    applied_mrid=applied_mrid,
                    cause_mrid=cause_mrid,
                    error=f"{origin} does not hold the command role for this device",
                    error_type="refused",
                )
                # Recorded as a write that did not happen, so the trail shows the
                # refusal beside the rejection the event processor reports.
                if self._telemetry is not None:
                    self._telemetry.record_write(
                        label,
                        control,
                        params,
                        connector=(
                            connector
                            if connector is not None
                            else getattr(method, "__self__", None)
                        ),
                        lfdi=lfdi,
                        error=f"{origin} does not hold the command role for this device",
                        error_type="refused",
                        origin=origin,
                        applied_mrid=applied_mrid,
                        cause_mrid=cause_mrid,
                    )
                return False
        else:
            # Deliberately ungated: authority is held per device, and there is no
            # device here to hold it over. Denying instead would drop writes for
            # an href that resolves to a connector but not to an LFDI -- a case
            # that predates the gate and is handled below -- so the choice is to
            # let it through and say so rather than to fail closed by accident.
            logger.debug("Ungated %s on %s: no LFDI to resolve authority for", control, label)
        if (
            lfdi
            and self._intercept is not None
            and await self._intercepted(
                self._intercept,
                lfdi,
                control,
                params,
                origin=origin,
                kind=kind,
                label=label,
                applied_mrid=applied_mrid,
                cause_mrid=cause_mrid,
            )
        ):
            return True
        issued_at = time.time()
        # A bound method carries its connector, so the device's address and
        # protocol are reachable without widening every call site. A caller
        # that wraps the method -- the native clear-control path passes a
        # lambda -- has no ``__self__`` to introspect, so it supplies the
        # connector explicitly and that takes precedence.
        if connector is None:
            connector = getattr(method, "__self__", None)
        try:
            await method(params)
        except Exception as exc:
            self._keep_write(
                label,
                control,
                params,
                outcome="failed",
                at=issued_at,
                lfdi=lfdi,
                origin=origin,
                applied_mrid=applied_mrid,
                cause_mrid=cause_mrid,
                error=str(exc),
                error_type=type(exc).__name__,
            )
            if lfdi:
                self._commands.record_command(
                    lfdi, control, params, origin=origin, at=issued_at, error=str(exc)
                )
            # A rejected command is reported too. The northbound side may still
            # believe it succeeded, and that divergence is the point.
            if self._telemetry is not None:
                self._telemetry.record_write(
                    label,
                    control,
                    params,
                    connector=connector,
                    lfdi=lfdi,
                    error=str(exc),
                    error_type=type(exc).__name__,
                    origin=origin,
                    applied_mrid=applied_mrid,
                    cause_mrid=cause_mrid,
                )
            raise
        self._keep_write(
            label,
            control,
            params,
            outcome="applied",
            at=issued_at,
            lfdi=lfdi,
            origin=origin,
            applied_mrid=applied_mrid,
            cause_mrid=cause_mrid,
        )
        if self._telemetry is not None:
            self._telemetry.record_write(
                label,
                control,
                params,
                connector=connector,
                lfdi=lfdi,
                origin=origin,
                applied_mrid=applied_mrid,
                cause_mrid=cause_mrid,
            )
        if lfdi:
            self._commands.record_command(lfdi, control, params, origin=origin, at=issued_at)
        else:
            # No LFDI means no key to file the record under. Rare (an href that
            # resolves to a connector but not to an LFDI) and worth seeing.
            logger.debug("Applied %s to %s with no LFDI; not recorded", control, label)
        return True

    # One keyword per field of the write.
    async def _intercepted(  # pylint: disable=too-many-arguments
        self,
        intercept: CommandIntercept,
        lfdi: str,
        control: str,
        params: dict[str, Any],
        *,
        origin: str,
        kind: str,
        label: str,
        applied_mrid: bytes | None,
        cause_mrid: bytes | None,
    ) -> bool:
        """Offer one permitted write to the command intercept. Return True if it took the write.

        A taken write is kept in the write history as ``intercepted``. The
        command observer and the telemetry emitter receive nothing, because no
        write reached the device. An exception is kept as a failed write and
        re-raised, as a connector failure is.
        """
        write = InterceptedWrite(
            lfdi=lfdi,
            control=control,
            params=copy.deepcopy(params),
            origin=origin,
            kind=kind,
            applied_mrid=applied_mrid,
            cause_mrid=cause_mrid,
        )
        at = time.time()
        try:
            taken = await intercept.intercept(write)
        except Exception as exc:
            self._keep_write(
                label,
                control,
                params,
                outcome="failed",
                at=at,
                lfdi=lfdi,
                origin=origin,
                applied_mrid=applied_mrid,
                cause_mrid=cause_mrid,
                error=str(exc),
                error_type=type(exc).__name__,
            )
            raise
        if not taken:
            return False
        logger.debug("Intercepted %s for %s (%s)", control, label, kind)
        self._keep_write(
            label,
            control,
            params,
            outcome="intercepted",
            at=at,
            lfdi=lfdi,
            origin=origin,
            applied_mrid=applied_mrid,
            cause_mrid=cause_mrid,
        )
        return True

    async def apply_operation(
        self,
        lfdi: str,
        control: str,
        params: dict[str, Any],
        *,
        origin: str,
    ) -> None:
        """Apply one named control to one device by LFDI, and record it.

        The write funnel for callers that already know which control they want,
        rather than a DERControl to be translated -- a Modbus master writing a
        register, for instance. Everything an event-driven write gets applies:
        the command is recorded with its origin, a failure is recorded as
        rejected and re-raised.

        Raises:
            ConnectorError: no connector is registered for ``lfdi``, or the
                connector does not implement this control.
            CommandNotPermittedError: a gate refused this origin authority over
                this device. Raised rather than reported because this caller
                named the control and has somewhere to put the answer -- a
                protocol server owes its own client the distinction between a
                write that failed and one that was not permitted.
            DeviceNotConfiguredError: the device is configured as a meter.
        """
        self._refuse_meter(lfdi)
        connector = await self._resolve_connector_by_lfdi(lfdi)
        if connector is None:
            raise ConnectorError(f"no connector for LFDI {lfdi}")
        method_name = f"update_{control}"
        method, _reason = self.control_support(connector, method_name)
        if method is None:
            raise ConnectorError(f"connector for {lfdi} does not implement {method_name}")
        applied = await self._apply_one(
            method, method_name, params, lfdi=lfdi, origin=origin, kind="operation", label=lfdi
        )
        if not applied:
            raise CommandNotPermittedError(
                f"{origin} may not command {lfdi}: another interface holds the "
                f"command role, so {control!r} was not applied"
            )

    async def apply_default_control(
        self,
        device_href: str,
        dderc: DefaultDercontrol,
        curves: list[Dercurve1],
        *,
        origin: str = CommandOrigin.DDERC_REAPPLY,
        cause_mrid: bytes | None = None,
    ) -> None:
        """Apply default DER control (DDERC fallback) to a device.

        ``cause_mrid`` names the event whose end brought the default back, for
        the audit trail. ``None`` when no single event caused it. A meter is
        skipped: a default control carries no response to refuse it with.
        """
        if self._skips_meter(self._lfdi_resolver(device_href), "default control"):
            return
        connector = await self._resolve_connector(device_href)
        await self._apply_default_control_to_connector(
            connector,
            dderc,
            curves,
            lfdi=self._lfdi_resolver(device_href),
            device_href=device_href,
            origin=origin,
            cause_mrid=cause_mrid,
        )

    async def apply_default_control_by_lfdi(
        self,
        lfdi: str,
        dderc: DefaultDercontrol,
        curves: list[Dercurve1],
        *,
        origin: str = CommandOrigin.DDERC_REAPPLY,
        cause_mrid: bytes | None = None,
    ) -> None:
        """Apply default DER control directly to a device identified by LFDI.

        A meter is skipped, as in :meth:`apply_default_control`.
        """
        if self._skips_meter(lfdi, "default control"):
            return
        connector = await self._resolve_connector_by_lfdi(lfdi)
        await self._apply_default_control_to_connector(
            connector,
            dderc,
            curves,
            lfdi=lfdi,
            device_href=None,
            origin=origin,
            cause_mrid=cause_mrid,
        )

    async def _apply_default_control_to_connector(
        self,
        connector: BaseConnector | None,
        dderc: DefaultDercontrol,
        curves: list[Dercurve1],
        *,
        lfdi: str | None,
        device_href: str | None,
        origin: str = CommandOrigin.DDERC_REAPPLY,
        cause_mrid: bytes | None = None,
    ) -> None:
        if connector is None:
            return

        label = lfdi or device_href or "<unknown>"
        dderc_mrid = dderc.m_rid.value
        translations = translate_default_controls(dderc, curves)
        logger.debug("Applying DDERC fallback to %s (%d mode(s))", label, len(translations))
        unimplemented: list[str] = []
        declined: list[ModeNotSupportedError] = []
        for method_name, params in translations:
            method, reason = self.control_support(connector, method_name)
            if method is not None:
                try:
                    await self._apply_one(
                        method,
                        method_name,
                        params,
                        lfdi=lfdi,
                        origin=origin,
                        kind="default_control",
                        label=label,
                        applied_mrid=dderc_mrid,
                        cause_mrid=cause_mrid,
                    )
                except ModeNotSupportedError as exc:
                    # Same as for a DERControl above.
                    unimplemented.append(method_name)
                    declined.append(exc)
            elif reason == BY_DESIGN:
                # Same reasoning as for a DERControl above.
                unimplemented.append(method_name)
                logger.debug(
                    "  %s does not implement %s; skipped",
                    connector.connector_name,
                    method_name,
                )
            else:
                unimplemented.append(method_name)
                self._report_unimplemented_mode(
                    connector, lfdi=lfdi, device_href=device_href, method_name=method_name
                )
        self._require_an_implemented_mode(connector, label, translations, unimplemented, declined)

    @staticmethod
    def _require_an_implemented_mode(
        connector: BaseConnector,
        label: str,
        translations: list[tuple[str, dict[str, Any]]],
        unimplemented: list[str],
        declined: list[ModeNotSupportedError] | None = None,
    ) -> None:
        """Raise when a control had modes to apply and the connector took none.

        ``unimplemented`` holds the modes the connector does not implement and
        the modes it declined while applying them (``declined`` holds those
        refusals). A declined mode does not stop the control's other modes.

        IEEE 2030.5-2023 §10.10.4.2.1 lets a client "reject or partially act
        upon" a control for its capabilities. Partial action is a control with
        at least one applied mode, and that stays a success. A control that
        applied nothing has not started, and completing normally would have the
        server told it is in force. ``ModeNotSupportedError`` maps to Table 31
        status 251, or 252 for a 2018 server.

        A control that translates to no mode at all is left alone: it names
        nothing the connector could have implemented.
        """
        if translations and len(unimplemented) == len(translations):
            names = ", ".join(name.removeprefix("update_") for name in unimplemented)
            reasons = "".join(f"; {exc}" for exc in declined or ())
            raise ModeNotSupportedError(
                f"{connector.connector_name} for {label} implements none of the modes in "
                f"this control, so nothing was applied: {names}{reasons}"
            )

    async def relay_schedule_notification(
        self,
        lfdis: list[str],
        notification: ScheduleNotification,
    ) -> None:
        """Relay a schedule notification to each connector owning an affected LFDI.

        Resolves each LFDI to its connector (the same ``registry.get_connector``
        path dispatch uses), de-duplicates so a connector that owns several affected
        LFDIs is notified once, and isolates per-connector errors -- a
        throwing/slow connector here must never affect event processing or the
        other connectors.

        De-dup is keyed by ``connector.relay_group`` when present. A connector
        fronting several devices over one connection sets it to that
        connection's name, so N per-LFDI instances collapse to a single
        notification -- which is correct, because the notification already
        carries every affected LFDI. Connectors that don't set it fall back to
        instance identity.

        The de-duped connectors are notified **concurrently** so one slow
        connector can't delay delivery to the others; each call is
        error-isolated. Each connector receives a stream's notifications one at
        a time, in the order they were relayed: a delivery starts only after
        the previous delivery of that stream to the same connector finished.
        Without this, an older notification still in delivery could finish
        after a newer one and leave the connector on stale schedule data.

        The order is taken when the relay starts, before its connectors are
        resolved. Before a relay queues its deliveries, it waits for every older
        relay of the stream to resolve its connectors, which is immediate once a
        connector is resolved, and then for each older relay that shares one of
        its relay groups to queue its own. A slow resolution of an older relay
        therefore cannot let a newer one reach a shared connector first, even
        for a different device. Delivery to other relay groups never waits.
        """
        loop = asyncio.get_running_loop()
        relay = _PendingRelay(resolved=loop.create_future(), queued=loop.create_future())
        in_flight = self._relays_in_flight.setdefault(notification.stream, [])
        earlier = list(in_flight)
        in_flight.append(relay)
        tasks: list[asyncio.Task[None]] = []
        try:
            targets: list[tuple[object, str, BaseConnector]] = []
            try:
                targets = await self._resolve_relay_targets(lfdis, notification)
            finally:
                relay.groups = {group for group, _, _ in targets}
                relay.resolved.set_result(None)
            for other in earlier:
                # asyncio.wait does not raise when the other relay failed.
                await asyncio.wait({other.resolved})
                if other.groups & relay.groups:
                    await asyncio.wait({other.queued})
            tasks = [
                self._queue_notification(group, lfdi, connector, notification)
                for group, lfdi, connector in targets
            ]
        finally:
            relay.queued.set_result(None)
            in_flight.remove(relay)
            if not in_flight:
                del self._relays_in_flight[notification.stream]
        if tasks:
            await asyncio.gather(*tasks)

    async def _resolve_relay_targets(
        self, lfdis: list[str], notification: ScheduleNotification
    ) -> list[tuple[object, str, BaseConnector]]:
        """Return the de-duplicated ``(group, lfdi, connector)`` targets of a relay."""
        from py20305.diagnostics import report

        seen: set[object] = set()
        targets: list[tuple[object, str, BaseConnector]] = []
        for lfdi in lfdis:
            try:
                connector = await self._resolve_connector_by_lfdi(lfdi)
            except asyncio.CancelledError:
                raise
            except Exception as exc:
                # Resolution (e.g. LazyConnectorProxy.aresolve permanent errors)
                # must not abort the whole relay -- isolate and keep going.
                report(
                    "warnings",
                    (
                        f"Resolving connector for {lfdi} failed during schedule relay "
                        f"({notification.stream}/{notification.transition}): {exc}"
                    ),
                    source="dispatcher",
                    dedup_key=f"schedule_notify_resolve:{lfdi}:{notification.stream}",
                    details={"lfdi": lfdi, "stream": notification.stream, "error": str(exc)},
                )
                continue
            if connector is None:
                continue
            group = getattr(connector, "relay_group", None) or id(connector)
            if group in seen:
                continue
            seen.add(group)
            targets.append((group, lfdi, connector))
        return targets

    def _queue_notification(
        self,
        group: object,
        lfdi: str,
        connector: BaseConnector,
        notification: ScheduleNotification,
    ) -> asyncio.Task[None]:
        """Start a delivery that runs after the previous one of its stream to *group*."""
        key = (group, notification.stream)
        previous = self._relay_tails.get(key)
        task = asyncio.create_task(self._notify_after(previous, lfdi, connector, notification))
        self._relay_tails[key] = task

        def _forget(finished: asyncio.Task[None]) -> None:
            if self._relay_tails.get(key) is finished:
                del self._relay_tails[key]

        task.add_done_callback(_forget)
        return task

    async def _notify_after(
        self,
        previous: asyncio.Task[None] | None,
        lfdi: str,
        connector: BaseConnector,
        notification: ScheduleNotification,
    ) -> None:
        """Wait for *previous* to finish, however it ends, then deliver *notification*."""
        if previous is not None:
            # asyncio.wait does not raise when previous failed or was cancelled.
            await asyncio.wait({previous})
        await self._notify_one(lfdi, connector, notification)

    async def _notify_one(
        self,
        lfdi: str,
        connector: BaseConnector,
        notification: ScheduleNotification,
    ) -> None:
        """Relay to a single connector, isolating any error.

        An informational relay must never propagate into event processing or
        affect the other connectors (gather sees no exception).
        """
        from py20305.diagnostics import report

        logger.debug(
            "relay %s/%s mrid=%s -> %s (lfdi=%s, affects=%d)",
            notification.stream,
            notification.transition,
            notification.mrid,
            connector.connector_name,
            lfdi,
            len(notification.affected_lfdis),
        )
        try:
            await connector.on_schedule_notification(notification)
        except asyncio.CancelledError:
            # Shutdown cancels in-flight relay tasks -- a cancellation is not a
            # connector failure; stay quiet and propagate.
            raise
        except Exception as exc:
            report(
                "warnings",
                (
                    f"Connector {connector.connector_name} raised in "
                    f"on_schedule_notification ({notification.stream}/"
                    f"{notification.transition}): {exc}"
                ),
                source="dispatcher",
                dedup_key=f"schedule_notify:{lfdi}:{notification.stream}:{notification.mrid}",
                details={
                    "lfdi": lfdi,
                    "stream": notification.stream,
                    "mrid": notification.mrid,
                    "transition": notification.transition,
                    "error": str(exc),
                },
            )

    @staticmethod
    def _report_not_commanding(lfdi: str, control: str, origin: str) -> None:
        """Surface a write refused because its origin does not command the device.

        Reported rather than raised: a 2030.5 server posting events to a device
        another interface commands is a configuration statement being honored, not a
        fault, and raising would turn every such event into an error the event
        engine has to interpret. Silence is the wrong answer too -- an operator
        seeing a posted control never arrive needs this row to know why.
        """
        from py20305.diagnostics import report

        report(
            "warnings",
            f"{origin} may not command {lfdi[:8]}: another interface holds "
            f"the command role. '{control}' was not applied.",
            source="dispatcher",
            dedup_key=f"not-commanding-{origin}-{lfdi}",
            details={"device": lfdi, "origin": str(origin), "control": control},
        )

    @staticmethod
    def control_support(
        connector: object, method_name: str
    ) -> tuple[Callable[[dict[str, Any]], Any] | None, str | None]:
        """Return ``(bound method, reason)``. ``reason`` is None when implemented.

        ``BaseConnector`` declares every ``update_*`` method as a concrete method that
        return ``None``, so ``getattr`` finds one whether or not the connector
        implements it. Reading that as support makes a connector look like it
        accepted a command it never carried out: the dispatch succeeds, the
        commanded plane records it, and a Modbus master is acknowledged for a
        write that reached no device.

        The two ways a mode can be unsupported need telling apart, because only
        one of them is anybody's mistake:

        ``BY_DESIGN``
            The connector inherits the base no-op, as a connector does for every
            mode its device has no way to carry out -- the base defaults exist
            for exactly that. Expected, and not something an operator can act on.

        ``OFFER_MISSING``
            No implementation resolves at all. For a plugin-backed connector,
            whose modes arrive through ``__getattr__`` from a live offer, that
            means the offer lacks a mode it should carry -- typically a plugin
            built against an older SDK. Actionable, and what the unimplemented
            diagnostic was written for.
        """
        own = getattr(type(connector), method_name, None)
        if own is not None and own is getattr(BaseConnector, method_name, None):
            return None, BY_DESIGN
        bound: Callable[[dict[str, Any]], Any] | None = getattr(connector, method_name, None)
        if bound is None:
            return None, OFFER_MISSING
        return bound, None

    @staticmethod
    def _report_unimplemented_mode(
        connector: BaseConnector,
        *,
        lfdi: str | None,
        device_href: str | None,
        method_name: str,
    ) -> None:
        """Surface a translated mode the connector can't accept.

        When a server-issued DERControl translates to ``method_name`` but the
        resolved connector doesn't expose that method, the control has nowhere
        to go. Dropping it silently is the wrong answer: the operator sees the
        post land at the client and never reach the device, with nothing
        saying why. The usual cause is a connector built against an older
        revision of this package that predates the mode.

        Routed through ``diagnostics.report`` so it surfaces alongside
        ``no_connector`` and ``unresolved_href``. The dedup key is scoped per
        (LFDI-or-href, method), so a device polled repeatedly collapses to one
        entry with ``count`` ticking up rather than flooding the log.
        """
        from py20305.diagnostics import report

        identifier = lfdi or device_href or "<unknown>"
        report(
            "warnings",
            (
                f"Connector {connector.connector_name} for {identifier} "
                f"does not implement {method_name}; control dropped. "
                "A connector supplied outside this package may predate "
                "this mode -- rebuild it against the current version."
            ),
            source="dispatcher",
            dedup_key=f"unimplemented_mode:{identifier}:{method_name}",
            details={
                "lfdi": lfdi,
                "device_href": device_href,
                "method": method_name,
                "connector": connector.connector_name,
            },
        )

    async def clear_control(
        self,
        device_href: str,
        *,
        cause_mrid: bytes | None = None,
    ) -> None:
        """Clear active control from a device by sending disable params.

        Prefers the connector's own ``clear_control`` when it has one. A
        connector talking to a remote device should implement it as a single
        round-trip rather than paying for the per-mode fan-out below; the
        bundled connectors talk to the device directly, so they don't
        override it and take the fan-out.
        """
        logger.debug("Clearing all controls on %s", device_href)
        if self._skips_meter(self._lfdi_resolver(device_href), "clear"):
            return
        connector = await self._resolve_connector(device_href)
        await self._clear_control_on_connector(
            connector,
            lfdi=self._lfdi_resolver(device_href),
            label=device_href,
            cause_mrid=cause_mrid,
        )

    async def clear_control_by_lfdi(
        self,
        lfdi: str,
        *,
        cause_mrid: bytes | None = None,
    ) -> None:
        """Clear active control from a device identified by LFDI.

        The by-LFDI counterpart of ``clear_control`` (the comms-loss
        safe-default when dispatching by LFDI). Skips the href->LFDI
        resolution step.
        """
        logger.debug("Clearing all controls on LFDI %s", lfdi)
        if self._skips_meter(lfdi, "clear"):
            return
        connector = await self._resolve_connector_by_lfdi(lfdi)
        await self._clear_control_on_connector(
            connector, lfdi=lfdi, label=lfdi, cause_mrid=cause_mrid
        )

    async def disable_modes(
        self,
        device_href: str,
        modes: frozenset[str],
        *,
        cause_mrid: bytes | None = None,
    ) -> None:
        """Disable the named control modes on a device.

        ``modes`` are DERControlBase field names (``op_mod_fixed_w``) or the
        CSIP-AUS limit element names (``opModExpLimW``), as the event processor
        tracks them. Called at event end for the modes the ended event set and
        the DefaultDERControl does not carry. A meter is skipped.
        """
        if self._skips_meter(self._lfdi_resolver(device_href), "mode disable"):
            return
        connector = await self._resolve_connector(device_href)
        await self._disable_modes_on_connector(
            connector,
            modes,
            lfdi=self._lfdi_resolver(device_href),
            label=device_href,
            cause_mrid=cause_mrid,
        )

    async def disable_modes_by_lfdi(
        self,
        lfdi: str,
        modes: frozenset[str],
        *,
        cause_mrid: bytes | None = None,
    ) -> None:
        """The by-LFDI counterpart of ``disable_modes``."""
        if self._skips_meter(lfdi, "mode disable"):
            return
        connector = await self._resolve_connector_by_lfdi(lfdi)
        await self._disable_modes_on_connector(
            connector, modes, lfdi=lfdi, label=lfdi, cause_mrid=cause_mrid
        )

    async def _disable_modes_on_connector(
        self,
        connector: BaseConnector | None,
        modes: frozenset[str],
        *,
        lfdi: str | None,
        label: str,
        cause_mrid: bytes | None,
    ) -> None:
        if connector is None:
            return
        calls: dict[str, dict[str, Any]] = {}
        for mode in sorted(modes):
            entry = FIELD_DISABLE_CALLS.get(mode)
            if entry is not None:
                calls.setdefault(entry[0], entry[1])
        for method_name, params in calls.items():
            method, _reason = self.control_support(connector, method_name)
            if method is None:
                continue
            logger.debug("  %s: %s disabled at event end", label, method_name)
            await self._apply_one(
                method,
                method_name,
                params,
                lfdi=lfdi,
                origin=CommandOrigin.EVENT_END,
                # Withdrawing a mode is a clear, whatever caused it.
                kind="clear",
                label=label,
                cause_mrid=cause_mrid,
            )

    async def _clear_control_on_connector(
        self,
        connector: BaseConnector | None,
        *,
        lfdi: str | None = None,
        label: str = "",
        cause_mrid: bytes | None = None,
    ) -> None:
        """Disable every active control on a device.

        Both branches route through ``_apply_one`` so a clear is recorded like
        any other write. It reaches the device the same way, and it is the
        comms-loss safe default -- the one control action most worth being able
        to account for after the fact -- so leaving it out of the audit trail
        and the monitoring stream would be the wrong asymmetry.
        """
        if connector is None:
            return

        native_clear = getattr(connector, "clear_control", None)
        if callable(native_clear):
            # One round-trip that clears everything, so it is one record
            # rather than the fan-out's per-mode ones.
            await self._apply_one(
                lambda _params: native_clear(),
                "clear_control",
                {},
                lfdi=lfdi,
                origin=CommandOrigin.COMMS_LOSS,
                kind="clear",
                label=label,
                # The lambda has no ``__self__``; without this the clear would
                # report as generic with no destination -- losing exactly the
                # attribution this path most needs.
                connector=connector,
                cause_mrid=cause_mrid,
            )
            return

        for method_name, params in DISABLE_CALLS:
            # Same distinction the translation loops draw, and it matters more
            # here: this fan-out touches every mode, and a clear is recorded like
            # any other write. Taking an inherited no-op for an implementation
            # would file twenty commands that reached no register, for a device
            # that implements a handful of modes.
            method, _reason = self.control_support(connector, method_name)
            if method is not None:
                await self._apply_one(
                    method,
                    method_name,
                    params,
                    lfdi=lfdi,
                    origin=CommandOrigin.COMMS_LOSS,
                    kind="clear",
                    label=label,
                    cause_mrid=cause_mrid,
                )
telemetry property
telemetry: DeviceTelemetryEmitter | None

The southbound telemetry emitter, if one was injected.

The metering cycle reports through the same emitter as the control path, so both halves of a device's traffic land on one channel with one configuration behind them.

registry property
registry: ConnectorConfigRegistry

The registry this dispatcher resolves through.

Exposed so a caller wiring a second consumer -- the metering cycle, which reads the same devices this writes to -- resolves through the same registry. Constructing a second one would build a second connector per device and open duplicate connections to it.

attach_write_history
attach_write_history(history: WriteHistory | None) -> None

Keep every write this dispatcher issues in history, or stop with None.

Source code in src/py20305/connectors/dispatcher.py
def attach_write_history(self, history: WriteHistory | None) -> None:
    """Keep every write this dispatcher issues in ``history``, or stop with None."""
    self._write_history = history
takes_controls
takes_controls(lfdi: str | None) -> bool

Return whether the device takes controls. A meter does not.

Only a device configured with a meter role is refused. A device the registry does not know, a control with no LFDI, and a registry that keeps no roles all take controls, as every device did before roles existed.

Source code in src/py20305/connectors/dispatcher.py
def takes_controls(self, lfdi: str | None) -> bool:
    """Return whether the device takes controls. A meter does not.

    Only a device configured with a meter role is refused. A device the
    registry does not know, a control with no LFDI, and a registry that
    keeps no roles all take controls, as every device did before roles
    existed.
    """
    return lfdi is None or self._role_of(lfdi) not in _METER_ROLES
supported_modes2 async
supported_modes2(lfdi: str) -> int | None

Return the DERControlType2 bits the device with lfdi can apply.

None when the device has no connector, or its connector has not been constructed yet. Nothing is reported for a missing connector, since a response may be posted for a device the client does not drive.

This runs on the response path, so it never constructs a connector: construction can connect to and scan the device with retries, and the acknowledgment and the activation timer wait on the response.

Source code in src/py20305/connectors/dispatcher.py
async def supported_modes2(self, lfdi: str) -> int | None:
    """Return the DERControlType2 bits the device with ``lfdi`` can apply.

    None when the device has no connector, or its connector has not been
    constructed yet. Nothing is reported for a missing connector, since a
    response may be posted for a device the client does not drive.

    This runs on the response path, so it never constructs a connector:
    construction can connect to and scan the device with retries, and the
    acknowledgment and the activation timer wait on the response.
    """
    from py20305.connectors.modes import modes_supported2
    from py20305.connectors.registry import LazyConnectorProxy

    proxy = self._registry.get_connector(lfdi)
    if proxy is None:
        return None
    connector = proxy.constructed() if isinstance(proxy, LazyConnectorProxy) else None
    if connector is None:
        return None
    try:
        return modes_supported2(connector)
    except Exception:
        logger.debug("Could not read the supported modes for %s", lfdi[:8], exc_info=True)
        return None
apply_control async
apply_control(device_href: str, derc: Dercontrol1, curves: list[Dercurve1], *, origin: str = CommandOrigin.IEEE2030_5) -> None

Apply a DERControl's settings to a device.

Raises:

Type Description
CommandNotPermittedError

the gate refused at least one mode, so the device did not receive the control as sent. The event processor reports the device as rejected rather than started (IEEE 2030.5-2023 Table 31). With a gate that answers the same for a device and origin throughout, as :class:CommandGate requires, no mode was written.

DeviceNotConfiguredError

the device is configured as a meter.

ModeNotSupportedError

the control translates to at least one mode and the connector implements none of them, so nothing was applied. A control that applies at least one mode is not refused for the modes the connector leaves out. The event processor reports the device as rejected with Table 31 status 251 (252 for a 2018 server) rather than as started.

Source code in src/py20305/connectors/dispatcher.py
async def apply_control(
    self,
    device_href: str,
    derc: Dercontrol1,
    curves: list[Dercurve1],
    *,
    origin: str = CommandOrigin.IEEE2030_5,
) -> None:
    """Apply a DERControl's settings to a device.

    Raises:
        CommandNotPermittedError: the gate refused at least one mode, so the
            device did not receive the control as sent. The event processor
            reports the device as rejected rather than started (IEEE
            2030.5-2023 Table 31). With a gate that answers the same for a
            device and origin throughout, as :class:`CommandGate` requires,
            no mode was written.
        DeviceNotConfiguredError: the device is configured as a meter.
        ModeNotSupportedError: the control translates to at least one mode
            and the connector implements none of them, so nothing was
            applied. A control that applies at least one mode is not
            refused for the modes the connector leaves out. The event
            processor reports the device as rejected with Table 31 status
            251 (252 for a 2018 server) rather than as started.
    """
    self._refuse_meter(self._lfdi_resolver(device_href))
    connector = await self._resolve_connector(device_href)
    await self._apply_control_to_connector(
        connector,
        derc,
        curves,
        lfdi=self._lfdi_resolver(device_href),
        device_href=device_href,
        origin=origin,
    )
apply_control_by_lfdi async
apply_control_by_lfdi(lfdi: str, derc: Dercontrol1, curves: list[Dercurve1], *, origin: str = CommandOrigin.IEEE2030_5) -> None

Apply a DERControl directly to a device identified by LFDI.

Raises:

Type Description
CommandNotPermittedError

as for :meth:apply_control.

DeviceNotConfiguredError

the device is configured as a meter.

ModeNotSupportedError

as for :meth:apply_control.

Source code in src/py20305/connectors/dispatcher.py
async def apply_control_by_lfdi(
    self,
    lfdi: str,
    derc: Dercontrol1,
    curves: list[Dercurve1],
    *,
    origin: str = CommandOrigin.IEEE2030_5,
) -> None:
    """Apply a DERControl directly to a device identified by LFDI.

    Raises:
        CommandNotPermittedError: as for :meth:`apply_control`.
        DeviceNotConfiguredError: the device is configured as a meter.
        ModeNotSupportedError: as for :meth:`apply_control`.
    """
    self._refuse_meter(lfdi)
    connector = await self._resolve_connector_by_lfdi(lfdi)
    await self._apply_control_to_connector(
        connector, derc, curves, lfdi=lfdi, device_href=None, origin=origin
    )
apply_operation async
apply_operation(lfdi: str, control: str, params: dict[str, Any], *, origin: str) -> None

Apply one named control to one device by LFDI, and record it.

The write funnel for callers that already know which control they want, rather than a DERControl to be translated -- a Modbus master writing a register, for instance. Everything an event-driven write gets applies: the command is recorded with its origin, a failure is recorded as rejected and re-raised.

Raises:

Type Description
ConnectorError

no connector is registered for lfdi, or the connector does not implement this control.

CommandNotPermittedError

a gate refused this origin authority over this device. Raised rather than reported because this caller named the control and has somewhere to put the answer -- a protocol server owes its own client the distinction between a write that failed and one that was not permitted.

DeviceNotConfiguredError

the device is configured as a meter.

Source code in src/py20305/connectors/dispatcher.py
async def apply_operation(
    self,
    lfdi: str,
    control: str,
    params: dict[str, Any],
    *,
    origin: str,
) -> None:
    """Apply one named control to one device by LFDI, and record it.

    The write funnel for callers that already know which control they want,
    rather than a DERControl to be translated -- a Modbus master writing a
    register, for instance. Everything an event-driven write gets applies:
    the command is recorded with its origin, a failure is recorded as
    rejected and re-raised.

    Raises:
        ConnectorError: no connector is registered for ``lfdi``, or the
            connector does not implement this control.
        CommandNotPermittedError: a gate refused this origin authority over
            this device. Raised rather than reported because this caller
            named the control and has somewhere to put the answer -- a
            protocol server owes its own client the distinction between a
            write that failed and one that was not permitted.
        DeviceNotConfiguredError: the device is configured as a meter.
    """
    self._refuse_meter(lfdi)
    connector = await self._resolve_connector_by_lfdi(lfdi)
    if connector is None:
        raise ConnectorError(f"no connector for LFDI {lfdi}")
    method_name = f"update_{control}"
    method, _reason = self.control_support(connector, method_name)
    if method is None:
        raise ConnectorError(f"connector for {lfdi} does not implement {method_name}")
    applied = await self._apply_one(
        method, method_name, params, lfdi=lfdi, origin=origin, kind="operation", label=lfdi
    )
    if not applied:
        raise CommandNotPermittedError(
            f"{origin} may not command {lfdi}: another interface holds the "
            f"command role, so {control!r} was not applied"
        )
apply_default_control async
apply_default_control(device_href: str, dderc: DefaultDercontrol, curves: list[Dercurve1], *, origin: str = CommandOrigin.DDERC_REAPPLY, cause_mrid: bytes | None = None) -> None

Apply default DER control (DDERC fallback) to a device.

cause_mrid names the event whose end brought the default back, for the audit trail. None when no single event caused it. A meter is skipped: a default control carries no response to refuse it with.

Source code in src/py20305/connectors/dispatcher.py
async def apply_default_control(
    self,
    device_href: str,
    dderc: DefaultDercontrol,
    curves: list[Dercurve1],
    *,
    origin: str = CommandOrigin.DDERC_REAPPLY,
    cause_mrid: bytes | None = None,
) -> None:
    """Apply default DER control (DDERC fallback) to a device.

    ``cause_mrid`` names the event whose end brought the default back, for
    the audit trail. ``None`` when no single event caused it. A meter is
    skipped: a default control carries no response to refuse it with.
    """
    if self._skips_meter(self._lfdi_resolver(device_href), "default control"):
        return
    connector = await self._resolve_connector(device_href)
    await self._apply_default_control_to_connector(
        connector,
        dderc,
        curves,
        lfdi=self._lfdi_resolver(device_href),
        device_href=device_href,
        origin=origin,
        cause_mrid=cause_mrid,
    )
apply_default_control_by_lfdi async
apply_default_control_by_lfdi(lfdi: str, dderc: DefaultDercontrol, curves: list[Dercurve1], *, origin: str = CommandOrigin.DDERC_REAPPLY, cause_mrid: bytes | None = None) -> None

Apply default DER control directly to a device identified by LFDI.

A meter is skipped, as in :meth:apply_default_control.

Source code in src/py20305/connectors/dispatcher.py
async def apply_default_control_by_lfdi(
    self,
    lfdi: str,
    dderc: DefaultDercontrol,
    curves: list[Dercurve1],
    *,
    origin: str = CommandOrigin.DDERC_REAPPLY,
    cause_mrid: bytes | None = None,
) -> None:
    """Apply default DER control directly to a device identified by LFDI.

    A meter is skipped, as in :meth:`apply_default_control`.
    """
    if self._skips_meter(lfdi, "default control"):
        return
    connector = await self._resolve_connector_by_lfdi(lfdi)
    await self._apply_default_control_to_connector(
        connector,
        dderc,
        curves,
        lfdi=lfdi,
        device_href=None,
        origin=origin,
        cause_mrid=cause_mrid,
    )
relay_schedule_notification async
relay_schedule_notification(lfdis: list[str], notification: ScheduleNotification) -> None

Relay a schedule notification to each connector owning an affected LFDI.

Resolves each LFDI to its connector (the same registry.get_connector path dispatch uses), de-duplicates so a connector that owns several affected LFDIs is notified once, and isolates per-connector errors -- a throwing/slow connector here must never affect event processing or the other connectors.

De-dup is keyed by connector.relay_group when present. A connector fronting several devices over one connection sets it to that connection's name, so N per-LFDI instances collapse to a single notification -- which is correct, because the notification already carries every affected LFDI. Connectors that don't set it fall back to instance identity.

The de-duped connectors are notified concurrently so one slow connector can't delay delivery to the others; each call is error-isolated. Each connector receives a stream's notifications one at a time, in the order they were relayed: a delivery starts only after the previous delivery of that stream to the same connector finished. Without this, an older notification still in delivery could finish after a newer one and leave the connector on stale schedule data.

The order is taken when the relay starts, before its connectors are resolved. Before a relay queues its deliveries, it waits for every older relay of the stream to resolve its connectors, which is immediate once a connector is resolved, and then for each older relay that shares one of its relay groups to queue its own. A slow resolution of an older relay therefore cannot let a newer one reach a shared connector first, even for a different device. Delivery to other relay groups never waits.

Source code in src/py20305/connectors/dispatcher.py
async def relay_schedule_notification(
    self,
    lfdis: list[str],
    notification: ScheduleNotification,
) -> None:
    """Relay a schedule notification to each connector owning an affected LFDI.

    Resolves each LFDI to its connector (the same ``registry.get_connector``
    path dispatch uses), de-duplicates so a connector that owns several affected
    LFDIs is notified once, and isolates per-connector errors -- a
    throwing/slow connector here must never affect event processing or the
    other connectors.

    De-dup is keyed by ``connector.relay_group`` when present. A connector
    fronting several devices over one connection sets it to that
    connection's name, so N per-LFDI instances collapse to a single
    notification -- which is correct, because the notification already
    carries every affected LFDI. Connectors that don't set it fall back to
    instance identity.

    The de-duped connectors are notified **concurrently** so one slow
    connector can't delay delivery to the others; each call is
    error-isolated. Each connector receives a stream's notifications one at
    a time, in the order they were relayed: a delivery starts only after
    the previous delivery of that stream to the same connector finished.
    Without this, an older notification still in delivery could finish
    after a newer one and leave the connector on stale schedule data.

    The order is taken when the relay starts, before its connectors are
    resolved. Before a relay queues its deliveries, it waits for every older
    relay of the stream to resolve its connectors, which is immediate once a
    connector is resolved, and then for each older relay that shares one of
    its relay groups to queue its own. A slow resolution of an older relay
    therefore cannot let a newer one reach a shared connector first, even
    for a different device. Delivery to other relay groups never waits.
    """
    loop = asyncio.get_running_loop()
    relay = _PendingRelay(resolved=loop.create_future(), queued=loop.create_future())
    in_flight = self._relays_in_flight.setdefault(notification.stream, [])
    earlier = list(in_flight)
    in_flight.append(relay)
    tasks: list[asyncio.Task[None]] = []
    try:
        targets: list[tuple[object, str, BaseConnector]] = []
        try:
            targets = await self._resolve_relay_targets(lfdis, notification)
        finally:
            relay.groups = {group for group, _, _ in targets}
            relay.resolved.set_result(None)
        for other in earlier:
            # asyncio.wait does not raise when the other relay failed.
            await asyncio.wait({other.resolved})
            if other.groups & relay.groups:
                await asyncio.wait({other.queued})
        tasks = [
            self._queue_notification(group, lfdi, connector, notification)
            for group, lfdi, connector in targets
        ]
    finally:
        relay.queued.set_result(None)
        in_flight.remove(relay)
        if not in_flight:
            del self._relays_in_flight[notification.stream]
    if tasks:
        await asyncio.gather(*tasks)
control_support staticmethod
control_support(connector: object, method_name: str) -> tuple[Callable[[dict[str, Any]], Any] | None, str | None]

Return (bound method, reason). reason is None when implemented.

BaseConnector declares every update_* method as a concrete method that return None, so getattr finds one whether or not the connector implements it. Reading that as support makes a connector look like it accepted a command it never carried out: the dispatch succeeds, the commanded plane records it, and a Modbus master is acknowledged for a write that reached no device.

The two ways a mode can be unsupported need telling apart, because only one of them is anybody's mistake:

BY_DESIGN The connector inherits the base no-op, as a connector does for every mode its device has no way to carry out -- the base defaults exist for exactly that. Expected, and not something an operator can act on.

OFFER_MISSING No implementation resolves at all. For a plugin-backed connector, whose modes arrive through __getattr__ from a live offer, that means the offer lacks a mode it should carry -- typically a plugin built against an older SDK. Actionable, and what the unimplemented diagnostic was written for.

Source code in src/py20305/connectors/dispatcher.py
@staticmethod
def control_support(
    connector: object, method_name: str
) -> tuple[Callable[[dict[str, Any]], Any] | None, str | None]:
    """Return ``(bound method, reason)``. ``reason`` is None when implemented.

    ``BaseConnector`` declares every ``update_*`` method as a concrete method that
    return ``None``, so ``getattr`` finds one whether or not the connector
    implements it. Reading that as support makes a connector look like it
    accepted a command it never carried out: the dispatch succeeds, the
    commanded plane records it, and a Modbus master is acknowledged for a
    write that reached no device.

    The two ways a mode can be unsupported need telling apart, because only
    one of them is anybody's mistake:

    ``BY_DESIGN``
        The connector inherits the base no-op, as a connector does for every
        mode its device has no way to carry out -- the base defaults exist
        for exactly that. Expected, and not something an operator can act on.

    ``OFFER_MISSING``
        No implementation resolves at all. For a plugin-backed connector,
        whose modes arrive through ``__getattr__`` from a live offer, that
        means the offer lacks a mode it should carry -- typically a plugin
        built against an older SDK. Actionable, and what the unimplemented
        diagnostic was written for.
    """
    own = getattr(type(connector), method_name, None)
    if own is not None and own is getattr(BaseConnector, method_name, None):
        return None, BY_DESIGN
    bound: Callable[[dict[str, Any]], Any] | None = getattr(connector, method_name, None)
    if bound is None:
        return None, OFFER_MISSING
    return bound, None
clear_control async
clear_control(device_href: str, *, cause_mrid: bytes | None = None) -> None

Clear active control from a device by sending disable params.

Prefers the connector's own clear_control when it has one. A connector talking to a remote device should implement it as a single round-trip rather than paying for the per-mode fan-out below; the bundled connectors talk to the device directly, so they don't override it and take the fan-out.

Source code in src/py20305/connectors/dispatcher.py
async def clear_control(
    self,
    device_href: str,
    *,
    cause_mrid: bytes | None = None,
) -> None:
    """Clear active control from a device by sending disable params.

    Prefers the connector's own ``clear_control`` when it has one. A
    connector talking to a remote device should implement it as a single
    round-trip rather than paying for the per-mode fan-out below; the
    bundled connectors talk to the device directly, so they don't
    override it and take the fan-out.
    """
    logger.debug("Clearing all controls on %s", device_href)
    if self._skips_meter(self._lfdi_resolver(device_href), "clear"):
        return
    connector = await self._resolve_connector(device_href)
    await self._clear_control_on_connector(
        connector,
        lfdi=self._lfdi_resolver(device_href),
        label=device_href,
        cause_mrid=cause_mrid,
    )
clear_control_by_lfdi async
clear_control_by_lfdi(lfdi: str, *, cause_mrid: bytes | None = None) -> None

Clear active control from a device identified by LFDI.

The by-LFDI counterpart of clear_control (the comms-loss safe-default when dispatching by LFDI). Skips the href->LFDI resolution step.

Source code in src/py20305/connectors/dispatcher.py
async def clear_control_by_lfdi(
    self,
    lfdi: str,
    *,
    cause_mrid: bytes | None = None,
) -> None:
    """Clear active control from a device identified by LFDI.

    The by-LFDI counterpart of ``clear_control`` (the comms-loss
    safe-default when dispatching by LFDI). Skips the href->LFDI
    resolution step.
    """
    logger.debug("Clearing all controls on LFDI %s", lfdi)
    if self._skips_meter(lfdi, "clear"):
        return
    connector = await self._resolve_connector_by_lfdi(lfdi)
    await self._clear_control_on_connector(
        connector, lfdi=lfdi, label=lfdi, cause_mrid=cause_mrid
    )
disable_modes async
disable_modes(device_href: str, modes: frozenset[str], *, cause_mrid: bytes | None = None) -> None

Disable the named control modes on a device.

modes are DERControlBase field names (op_mod_fixed_w) or the CSIP-AUS limit element names (opModExpLimW), as the event processor tracks them. Called at event end for the modes the ended event set and the DefaultDERControl does not carry. A meter is skipped.

Source code in src/py20305/connectors/dispatcher.py
async def disable_modes(
    self,
    device_href: str,
    modes: frozenset[str],
    *,
    cause_mrid: bytes | None = None,
) -> None:
    """Disable the named control modes on a device.

    ``modes`` are DERControlBase field names (``op_mod_fixed_w``) or the
    CSIP-AUS limit element names (``opModExpLimW``), as the event processor
    tracks them. Called at event end for the modes the ended event set and
    the DefaultDERControl does not carry. A meter is skipped.
    """
    if self._skips_meter(self._lfdi_resolver(device_href), "mode disable"):
        return
    connector = await self._resolve_connector(device_href)
    await self._disable_modes_on_connector(
        connector,
        modes,
        lfdi=self._lfdi_resolver(device_href),
        label=device_href,
        cause_mrid=cause_mrid,
    )
disable_modes_by_lfdi async
disable_modes_by_lfdi(lfdi: str, modes: frozenset[str], *, cause_mrid: bytes | None = None) -> None

The by-LFDI counterpart of disable_modes.

Source code in src/py20305/connectors/dispatcher.py
async def disable_modes_by_lfdi(
    self,
    lfdi: str,
    modes: frozenset[str],
    *,
    cause_mrid: bytes | None = None,
) -> None:
    """The by-LFDI counterpart of ``disable_modes``."""
    if self._skips_meter(lfdi, "mode disable"):
        return
    connector = await self._resolve_connector_by_lfdi(lfdi)
    await self._disable_modes_on_connector(
        connector, modes, lfdi=lfdi, label=lfdi, cause_mrid=cause_mrid
    )

unused_update_methods

unused_update_methods(connector_class: type) -> list[str]

Return the update_* methods a connector class defines that the client never calls.

The client calls one update_<element> method per control element (METHOD_BY_ELEMENT). A class written for an earlier contract may still define methods named for its own control vocabulary; they are never called.

Source code in src/py20305/connectors/dispatcher.py
def unused_update_methods(connector_class: type) -> list[str]:
    """Return the ``update_*`` methods a connector class defines that the client never calls.

    The client calls one ``update_<element>`` method per control element
    (``METHOD_BY_ELEMENT``). A class written for an earlier contract may still
    define methods named for its own control vocabulary; they are never called.
    """
    called = set(METHOD_BY_ELEMENT.values())
    known = called | {name for name in dir(BaseConnector) if name.startswith("update_")}
    return sorted(
        name
        for name in dir(connector_class)
        if name.startswith("update_")
        and name not in known
        and callable(getattr(connector_class, name, None))
    )

py20305.connectors.errors

Errors a connector raises when talking to a device.

Transport-neutral: a connector speaking Modbus, MQTT, SQL or anything else raises these same types, so the code above it -- the dispatcher, the event engine, the API -- reasons about failure without knowing the protocol underneath. :mod:py20305.connectors.control_errors covers the other half: a control the device declined rather than a transport that broke.

ConnectorError

Bases: Exception

Base exception for connector operations.

Source code in src/py20305/connectors/errors.py
class ConnectorError(Exception):
    """Base exception for connector operations."""

ConnectorConnectionError

Bases: ConnectorError

Raised when the connector cannot reach the target device.

The optional permanent flag signals that the failure won't change on retry without operator intervention -- e.g. Modbus protocol exception codes 1-4 (illegal function/address/value, server failure), which typically mean the configured device is missing models the connector was told to scan for.

Source code in src/py20305/connectors/errors.py
class ConnectorConnectionError(ConnectorError):
    """Raised when the connector cannot reach the target device.

    The optional ``permanent`` flag signals that the failure won't change
    on retry without operator intervention -- e.g. Modbus protocol
    exception codes 1-4 (illegal function/address/value, server failure),
    which typically mean the configured device is missing models the
    connector was told to scan for.
    """

    def __init__(self, *args: object, permanent: bool = False) -> None:
        super().__init__(*args)
        self.permanent = permanent

ConnectorTimeoutError

Bases: ConnectorError

Raised when a connector operation exceeds its deadline.

Source code in src/py20305/connectors/errors.py
class ConnectorTimeoutError(ConnectorError):
    """Raised when a connector operation exceeds its deadline."""

ConnectorWriteError

Bases: ConnectorError

Raised when a control write fails or is rejected by the device.

Source code in src/py20305/connectors/errors.py
class ConnectorWriteError(ConnectorError):
    """Raised when a control write fails or is rejected by the device."""

ConnectorValueError

Bases: ConnectorError

Raised when a control parameter is outside the range the profile allows.

Distinct from :class:ConnectorWriteError: nothing was attempted. The parameter itself is invalid, so no device could have accepted it and a retry with the same value cannot succeed. The register is left untouched, including any mode-enable point -- a lever must not be raised for a write that will not happen.

Reported to the head-end as IEEE 2030.5 Table 31 status 253 (Invalid), because the fault is in the event's data rather than in what the device can do. Adapters translate accordingly at their own boundary.

Source code in src/py20305/connectors/errors.py
class ConnectorValueError(ConnectorError):
    """Raised when a control parameter is outside the range the profile allows.

    Distinct from :class:`ConnectorWriteError`: nothing was attempted. The
    parameter itself is invalid, so no device could have accepted it and a retry
    with the same value cannot succeed. The register is left untouched, including
    any mode-enable point -- a lever must not be raised for a write that will not
    happen.

    Reported to the head-end as IEEE 2030.5 Table 31 status 253 (Invalid),
    because the fault is in the event's data rather than in what the device can
    do. Adapters translate accordingly at their own boundary.
    """

py20305.connectors.control_errors

Errors a connector raises when it will not perform a control.

Distinct from :mod:py20305.connectors.errors, which covers a transport that broke. These say the transport was fine and the control still did not happen -- the device is offline, the mode is unsupported, the value is out of range, or the site declined on the customer's behalf.

The distinction is load-bearing because IEEE 2030.5 makes the head-end care about it. Each type below carries the retry behavior the caller should apply and the Table 31 response status the head-end should see; see :func:py20305.events.response.response_code_for_dispatch_error for the mapping.

ControlError

Bases: Exception

Base for a control a connector declined to perform.

Source code in src/py20305/connectors/control_errors.py
class ControlError(Exception):
    """Base for a control a connector declined to perform."""

DeviceOfflineTransientError

Bases: ControlError

The device is unreachable, but may return on its own.

Caller logs and retries on the next polling cycle.

Source code in src/py20305/connectors/control_errors.py
class DeviceOfflineTransientError(ControlError):
    """The device is unreachable, but may return on its own.

    Caller logs and retries on the next polling cycle.
    """

DeviceOfflinePermanentError

Bases: ControlError

The device is unreachable and will stay that way without intervention.

Caller suppresses further attempts for this device rather than retrying every cycle.

Source code in src/py20305/connectors/control_errors.py
class DeviceOfflinePermanentError(ControlError):
    """The device is unreachable and will stay that way without intervention.

    Caller suppresses further attempts for this device rather than retrying
    every cycle.
    """

DeviceNotConfiguredError

Bases: ControlError

The connector has no configuration for the addressed device.

Caller re-sends its device configuration once and retries.

Source code in src/py20305/connectors/control_errors.py
class DeviceNotConfiguredError(ControlError):
    """The connector has no configuration for the addressed device.

    Caller re-sends its device configuration once and retries.
    """

ModeNotSupportedError

Bases: ControlError

The device cannot perform the requested control mode.

Permanent for this device and mode. Callers that pre-filter by a device's advertised modes should never see this; if one does, the advertised set and the device disagree.

Source code in src/py20305/connectors/control_errors.py
class ModeNotSupportedError(ControlError):
    """The device cannot perform the requested control mode.

    Permanent for this device and mode. Callers that pre-filter by a device's
    advertised modes should never see this; if one does, the advertised set and
    the device disagree.
    """

OptOutError

Bases: ControlError

The control was declined on the customer's behalf.

Reports a decision, not a failure, and is surfaced to the head-end as IEEE 2030.5 Table 31 status 4 rather than a capability-limit code.

Source code in src/py20305/connectors/control_errors.py
class OptOutError(ControlError):
    """The control was declined on the customer's behalf.

    Reports a decision, not a failure, and is surfaced to the head-end as
    IEEE 2030.5 Table 31 status 4 rather than a capability-limit code.
    """

InvalidControlValueError

Bases: ControlError

A control parameter is outside the range the IEEE 2030.5 profile allows.

Like :class:OptOutError this is not a device fault, but unlike it the event is not performed: surfaced to the head-end as Table 31 status 253 (Invalid) rather than a capability-limit code.

Callers must not latch this against the device and mode. A corrected value arriving on the next event has to be allowed through -- the value is at fault, not the pairing of device and mode.

Source code in src/py20305/connectors/control_errors.py
class InvalidControlValueError(ControlError):
    """A control parameter is outside the range the IEEE 2030.5 profile allows.

    Like :class:`OptOutError` this is not a device fault, but unlike it the
    event is not performed: surfaced to the head-end as Table 31 status 253
    (Invalid) rather than a capability-limit code.

    Callers must not latch this against the device and mode. A corrected value
    arriving on the next event has to be allowed through -- the value is at
    fault, not the pairing of device and mode.
    """

py20305.commands

Command vocabulary, the observer interface that records it, and the write-path seams.

A control reaching a device is one :class:CommandRecord: what was commanded, by which interface, when, and whether the device has confirmed it. Monitoring adapters read that state so a master can see what the command interface is doing without being able to interfere, and an operator can tell why a setpoint moved.

:class:CommandObserver exists so the write path can say "this was commanded" without naming who keeps the record. The write funnels are published client code and the plane that stores the records is not, so the dependency has to point down: the funnels depend on this Protocol, and the host application injects the implementation. :class:NullCommandObserver is the default, which is what lets an embedded consumer run the same write path with no plane at all.

Reflection is deliberately not modeled here as a value the device reports. A device may clamp a setpoint, ramp toward it, or reject it, so commanded and achieved routinely differ; the record says what was asked for and how far the confirmation has got, and never pretends the two are the same.

CommandOrigin

Bases: StrEnum

The origins this package produces itself.

An origin says where a command entered the system, and it is a label: any string. Everything that takes one -- the dispatcher, :class:CommandGate, :class:CommandObserver, :class:CommandRecord -- carries it through without interpreting it. So an application that puts another interface in front of the same devices names that interface's origin itself, and passes the string. Nothing here has to learn the name first, and which interfaces an application has is not something this package should have to list.

These three are the exception, because the writes are made here: an IEEE 2030.5 control, and the two cases where the client reasserts state it already owns. Those two are not external commands at all, but they change the device just as visibly, and leaving them unrecorded is what makes a setpoint appear to move on its own. The members are strings, so a gate or an observer compares and stores them like any other origin.

Source code in src/py20305/commands.py
class CommandOrigin(StrEnum):
    """The origins this package produces itself.

    An origin says where a command entered the system, and it is a label: any
    string. Everything that takes one -- the dispatcher, :class:`CommandGate`,
    :class:`CommandObserver`, :class:`CommandRecord` -- carries it through
    without interpreting it. So an application that puts another interface in
    front of the same devices names that interface's origin itself, and passes
    the string. Nothing here has to learn the name first, and which interfaces
    an application has is not something this package should have to list.

    These three are the exception, because the writes are made here: an IEEE
    2030.5 control, and the two cases where the client reasserts state it
    already owns. Those two are not external commands at all, but they change
    the device just as visibly, and leaving them unrecorded is what makes a
    setpoint appear to move on its own. The members are strings, so a gate or
    an observer compares and stores them like any other origin.
    """

    IEEE2030_5 = "ieee2030_5"
    #: DdercTracker reapplying DefaultDERControl on the fallback path after an
    #: event completes. The classic "my setpoint reverted and nothing says why".
    DDERC_REAPPLY = "dderc_reapply"
    #: Loss-of-communications handling reasserting the planning limit.
    COMMS_LOSS = "comms_loss"
    #: An event ending: the modes it set that the DefaultDERControl does not
    #: carry are disabled, so a device does not keep a setpoint whose event
    #: is over.
    EVENT_END = "event_end"

CommandStatus

Bases: StrEnum

How far a command has got.

UNCONFIRMED is the honest default and often the terminal state: the connector contract exposes no general setpoint readback, so most controls have nothing to confirm against. It means "we asked and the write returned without error", not "the device is doing it".

Source code in src/py20305/commands.py
class CommandStatus(StrEnum):
    """How far a command has got.

    ``UNCONFIRMED`` is the honest default and often the terminal state: the
    connector contract exposes no general setpoint readback, so most controls
    have nothing to confirm against. It means "we asked and the write returned
    without error", not "the device is doing it".
    """

    UNCONFIRMED = "unconfirmed"
    CONFIRMED = "confirmed"
    REJECTED = "rejected"

CommandRecord dataclass

One control applied to one device.

Source code in src/py20305/commands.py
@dataclass(frozen=True, slots=True)
class CommandRecord:
    """One control applied to one device."""

    #: The connector operation, e.g. ``p_lim`` or ``es_permit_service``. Keyed on
    #: the operation rather than a measured quantity: a limit and the power that
    #: results from it are different things (see the module docstring).
    control: str
    #: What was sent, verbatim. Curve modes carry point lists here; nothing in
    #: this layer interprets the shape.
    params: Mapping[str, Any]
    #: Where the command entered: one of :class:`CommandOrigin`, or whatever
    #: the application calls the interface that issued it.
    origin: str
    #: Wall-clock epoch seconds at which the write was issued. Compared against
    #: an observation's read-start time to decide whether that observation could
    #: possibly reflect this command.
    commanded_at: float
    status: CommandStatus
    confirmed_at: float | None = None
    #: What the connector raised, when status is REJECTED.
    error: str | None = None

CommandObserver

Bases: Protocol

Where the write path reports what it did.

Two operations, because confirmation arrives separately from the command and usually from a different code path: the write funnel knows what was asked for, and whoever polls the device later knows what it says about itself.

Source code in src/py20305/commands.py
@runtime_checkable
class CommandObserver(Protocol):
    """Where the write path reports what it did.

    Two operations, because confirmation arrives separately from the command and
    usually from a different code path: the write funnel knows what was asked
    for, and whoever polls the device later knows what it says about itself.
    """

    def record_command(
        self,
        device: str,
        control: str,
        params: Mapping[str, Any],
        *,
        origin: str,
        at: float,
        error: str | None = None,
    ) -> None:
        """Record that ``control`` was applied to ``device``, or failed to be."""
        ...

    def record_readback(
        self, device: str, observed: Mapping[str, Any], *, read_started_at: float
    ) -> None:
        """Offer a device's self-reported state as confirmation evidence.

        ``read_started_at`` is when the read that produced ``observed`` *began*,
        not when it completed. An observation that started before a command was
        issued cannot reflect it, however recent its arrival, and is what the
        implementation uses to keep an in-flight poll from clearing a command it
        never saw.
        """
        ...
record_command
record_command(device: str, control: str, params: Mapping[str, Any], *, origin: str, at: float, error: str | None = None) -> None

Record that control was applied to device, or failed to be.

Source code in src/py20305/commands.py
def record_command(
    self,
    device: str,
    control: str,
    params: Mapping[str, Any],
    *,
    origin: str,
    at: float,
    error: str | None = None,
) -> None:
    """Record that ``control`` was applied to ``device``, or failed to be."""
    ...
record_readback
record_readback(device: str, observed: Mapping[str, Any], *, read_started_at: float) -> None

Offer a device's self-reported state as confirmation evidence.

read_started_at is when the read that produced observed began, not when it completed. An observation that started before a command was issued cannot reflect it, however recent its arrival, and is what the implementation uses to keep an in-flight poll from clearing a command it never saw.

Source code in src/py20305/commands.py
def record_readback(
    self, device: str, observed: Mapping[str, Any], *, read_started_at: float
) -> None:
    """Offer a device's self-reported state as confirmation evidence.

    ``read_started_at`` is when the read that produced ``observed`` *began*,
    not when it completed. An observation that started before a command was
    issued cannot reflect it, however recent its arrival, and is what the
    implementation uses to keep an in-flight poll from clearing a command it
    never saw.
    """
    ...

NullCommandObserver

Discards everything. The default where no plane is wired.

Published write paths run unchanged in a deployment that keeps no commanded state -- an embedded single-upstream consumer, or any test that cares about the write rather than the record.

Source code in src/py20305/commands.py
class NullCommandObserver:
    """Discards everything. The default where no plane is wired.

    Published write paths run unchanged in a deployment that keeps no commanded
    state -- an embedded single-upstream consumer, or any test that cares about
    the write rather than the record.
    """

    def record_command(
        self,
        device: str,
        control: str,
        params: Mapping[str, Any],
        *,
        origin: str,
        at: float,
        error: str | None = None,
    ) -> None:
        """No-op."""

    def record_readback(
        self, device: str, observed: Mapping[str, Any], *, read_started_at: float
    ) -> None:
        """No-op."""
record_command
record_command(device: str, control: str, params: Mapping[str, Any], *, origin: str, at: float, error: str | None = None) -> None

No-op.

Source code in src/py20305/commands.py
def record_command(
    self,
    device: str,
    control: str,
    params: Mapping[str, Any],
    *,
    origin: str,
    at: float,
    error: str | None = None,
) -> None:
    """No-op."""
record_readback
record_readback(device: str, observed: Mapping[str, Any], *, read_started_at: float) -> None

No-op.

Source code in src/py20305/commands.py
def record_readback(
    self, device: str, observed: Mapping[str, Any], *, read_started_at: float
) -> None:
    """No-op."""

CommandGate

Bases: Protocol

Whether an origin may command a device.

A deployment may serve several command interfaces while intending only one of them to command any given device. Deciding that in configuration alone leaves it unenforced at the write: every interface still reaches the dispatcher, so one interface's events and another's setpoints overwrite each other while the configuration reads as though a single one were in charge.

Injected rather than imported, for the same reason :class:CommandObserver is. Which interface holds authority over a device is the consuming application's concern, and the dispatcher is client code, so the dependency points that way.

Source code in src/py20305/commands.py
@runtime_checkable
class CommandGate(Protocol):
    """Whether an origin may command a device.

    A deployment may serve several command interfaces while intending only one of
    them to command any given device. Deciding that in configuration alone leaves
    it unenforced at the write: every interface still reaches the dispatcher, so
    one interface's events and another's setpoints overwrite each other while the
    configuration reads as though a single one were in charge.

    Injected rather than imported, for the same reason :class:`CommandObserver`
    is. Which interface holds authority over a device is the consuming
    application's concern, and the dispatcher is client code, so the dependency
    points that way.
    """

    def may_command(self, device: str, origin: str) -> bool:
        """Whether ``origin`` holds the command role for ``device``.

        Deny an origin you do not recognize. An origin is a string the caller
        names, so nothing upstream of this method rejects one that no interface
        owns: a mistyped name, or a write path added without one, arrives here
        looking like any other. An implementation that answers only for the
        origins it knows, and refuses the rest, is what makes that a refused
        write. One that permits by default makes it a command.

        Answer the same for the same device and origin while one control is
        being applied. The dispatcher asks once per mode, so a gate whose
        answer changes partway through can let some modes reach the device
        while the server is told the control was rejected.
        """
        ...
may_command
may_command(device: str, origin: str) -> bool

Whether origin holds the command role for device.

Deny an origin you do not recognize. An origin is a string the caller names, so nothing upstream of this method rejects one that no interface owns: a mistyped name, or a write path added without one, arrives here looking like any other. An implementation that answers only for the origins it knows, and refuses the rest, is what makes that a refused write. One that permits by default makes it a command.

Answer the same for the same device and origin while one control is being applied. The dispatcher asks once per mode, so a gate whose answer changes partway through can let some modes reach the device while the server is told the control was rejected.

Source code in src/py20305/commands.py
def may_command(self, device: str, origin: str) -> bool:
    """Whether ``origin`` holds the command role for ``device``.

    Deny an origin you do not recognize. An origin is a string the caller
    names, so nothing upstream of this method rejects one that no interface
    owns: a mistyped name, or a write path added without one, arrives here
    looking like any other. An implementation that answers only for the
    origins it knows, and refuses the rest, is what makes that a refused
    write. One that permits by default makes it a command.

    Answer the same for the same device and origin while one control is
    being applied. The dispatcher asks once per mode, so a gate whose
    answer changes partway through can let some modes reach the device
    while the server is told the control was rejected.
    """
    ...

AllowAllCommands

Permits everything. The default where no authority is wired.

A consumer with a single command interface, or a test concerned with the write rather than with who was allowed to make it, behaves exactly as it did before the gate existed.

Everything includes an origin nothing claims. With this gate a mistyped origin commands like a correct one, and the only trace is the name in the audit record. That is the right trade for one interface, where there is no second commander for a wrong name to be mistaken for. An application with more than one should wire a gate of its own, and leaving this one in place is then a decision to check nothing.

Source code in src/py20305/commands.py
class AllowAllCommands:
    """Permits everything. The default where no authority is wired.

    A consumer with a single command interface, or a test concerned with the
    write rather than with who was allowed to make it, behaves exactly as it did
    before the gate existed.

    Everything includes an origin nothing claims. With this gate a mistyped
    origin commands like a correct one, and the only trace is the name in the
    audit record. That is the right trade for one interface, where there is no
    second commander for a wrong name to be mistaken for. An application with
    more than one should wire a gate of its own, and leaving this one in place
    is then a decision to check nothing.
    """

    def may_command(self, device: str, origin: str) -> bool:
        """Always True."""
        return True
may_command
may_command(device: str, origin: str) -> bool

Always True.

Source code in src/py20305/commands.py
def may_command(self, device: str, origin: str) -> bool:
    """Always True."""
    return True

InterceptedWrite dataclass

One translated write, offered to a :class:CommandIntercept before the connector.

The fields are the values the dispatcher would otherwise pass to the connector and keep in the write history.

Source code in src/py20305/commands.py
@dataclass(frozen=True)
class InterceptedWrite:
    """One translated write, offered to a :class:`CommandIntercept` before the connector.

    The fields are the values the dispatcher would otherwise pass to the
    connector and keep in the write history.
    """

    #: The device the write is for.
    lfdi: str
    #: The connector operation without the ``update_`` prefix, e.g.
    #: ``op_mod_max_lim_w``, or ``clear_control`` for a connector's own clear.
    control: str
    #: What the connector would receive. A deep copy, so changing it, or any value
    #: nested in it, changes nothing the dispatcher applies or records.
    params: dict[str, Any]
    #: Where the command entered: one of :class:`CommandOrigin`, or the
    #: application's own origin.
    origin: str
    #: Which apply path produced the write:
    #:
    #: - ``"control"``: a DERControl applied when its event starts.
    #: - ``"default_control"``: a DefaultDERControl applied.
    #: - ``"clear"``: a write that withdraws a mode. This is the clear made on a
    #:   loss of communications, one write per mode or the connector's own
    #:   ``clear_control``, and the disabling of the modes an ended event set.
    #:   ``origin`` tells the two apart (``comms_loss`` or ``event_end``).
    #: - ``"operation"``: a named control passed to
    #:   :meth:`~py20305.connectors.dispatcher.ConnectorDispatcher.apply_operation`.
    kind: str
    #: The mRID of the DERControl or DefaultDERControl written, when there is one.
    applied_mrid: bytes | None
    #: The mRID of the event whose start or end caused the write, when known.
    cause_mrid: bytes | None

CommandIntercept

Bases: Protocol

Takes a translated write before it reaches the connector.

A host application can route some writes somewhere other than the device's connector, for example to logic that decides the final setpoint itself. The dispatcher offers each write to the intercept after the :class:CommandGate has permitted it, and only when the write names a device by LFDI. Only modes the connector implements are offered, so the intercept sees the same writes the connector would.

Injected rather than imported, for the same reason :class:CommandGate is. Omitted, every write goes to the connector.

Source code in src/py20305/commands.py
@runtime_checkable
class CommandIntercept(Protocol):
    """Takes a translated write before it reaches the connector.

    A host application can route some writes somewhere other than the device's
    connector, for example to logic that decides the final setpoint itself. The
    dispatcher offers each write to the intercept after the :class:`CommandGate`
    has permitted it, and only when the write names a device by LFDI. Only modes
    the connector implements are offered, so the intercept sees the same writes
    the connector would.

    Injected rather than imported, for the same reason :class:`CommandGate` is.
    Omitted, every write goes to the connector.
    """

    async def intercept(self, write: InterceptedWrite) -> bool:
        """Return True to take ``write``, or False to let the connector apply it.

        A taken write is not applied to the connector. The dispatcher keeps it
        in the write history with outcome ``intercepted``, records no command
        with the :class:`CommandObserver`, reports no device write to the
        telemetry emitter, and returns success to its caller. Taking a write
        makes the intercept responsible for it.

        An exception is kept in the write history as a failed write and raised
        to the dispatcher's caller, as a connector failure is.
        """
        ...
intercept async
intercept(write: InterceptedWrite) -> bool

Return True to take write, or False to let the connector apply it.

A taken write is not applied to the connector. The dispatcher keeps it in the write history with outcome intercepted, records no command with the :class:CommandObserver, reports no device write to the telemetry emitter, and returns success to its caller. Taking a write makes the intercept responsible for it.

An exception is kept in the write history as a failed write and raised to the dispatcher's caller, as a connector failure is.

Source code in src/py20305/commands.py
async def intercept(self, write: InterceptedWrite) -> bool:
    """Return True to take ``write``, or False to let the connector apply it.

    A taken write is not applied to the connector. The dispatcher keeps it
    in the write history with outcome ``intercepted``, records no command
    with the :class:`CommandObserver`, reports no device write to the
    telemetry emitter, and returns success to its caller. Taking a write
    makes the intercept responsible for it.

    An exception is kept in the write history as a failed write and raised
    to the dispatcher's caller, as a connector failure is.
    """
    ...

CommandNotPermittedError

Bases: Exception

A gate refused this origin authority over this device.

Distinct from a connector error because the cause and the remedy are different: nothing is wrong with the device or the transport, and the caller cannot retry its way out of it. A caller serving a protocol client needs the distinction to answer that client honestly -- refused is not the same answer as failed.

Raised by the entry points whose caller has somewhere to put it: a named control, and a DERControl applied for an event, which the event processor reports to the server as a rejection (IEEE 2030.5-2023 Table 31, status 252). A default control and a clear are reported and dropped instead, since they send no response.

Source code in src/py20305/commands.py
class CommandNotPermittedError(Exception):
    """A gate refused this origin authority over this device.

    Distinct from a connector error because the cause and the remedy are
    different: nothing is wrong with the device or the transport, and the caller
    cannot retry its way out of it. A caller serving a protocol client needs the
    distinction to answer that client honestly -- refused is not the same answer
    as failed.

    Raised by the entry points whose caller has somewhere to put it: a named
    control, and a DERControl applied for an event, which the event processor
    reports to the server as a rejection (IEEE 2030.5-2023 Table 31, status 252).
    A default control and a clear are reported and dropped instead, since they
    send no response.
    """