Skip to content

Running a client

Two ways to use this package. Embedding it in your own application is covered in the quickstart; this page covers running it as a service.

pip install "py20305[cli,sunspec]"
py20305 --config client.yaml

The configuration file

One document describes the running client. A copy of the common options, commented, is at examples/client.example.yaml; the minimum is:

server:
  url: https://server.example.com:8443

tls:
  client_cert: certs/client.pem
  client_key: certs/client.key
  ca_cert: certs/ca.pem

devices:
  - type: sunspec
    lfdi: "0000000000000000000000000000000000000000"
    host: 192.168.1.50
    port: 502

Paths are relative to the configuration file, not the working directory — systemd will not start the process where you wrote it.

YAML and JSON are both accepted. YAML needs the cli extra; JSON works with no extra dependency.

Check before you run

py20305 --config client.yaml --check

Validates the file, resolves the certificate, and prints the LFDI the utility has to register, and the telemetry state file when one is set. Connects to nothing. A mistake is reported with the field that caused it:

error: invalid configuration in client.yaml:
  devices.0.sunspec.lfdi: Value error, lfdi must be 40 hex characters (length is 8, must be 40)

The server's schema

IEEE 2030.5-2018 and 2030.5-2023 share one namespace, so a message cannot be sorted into an edition by namespace. The server.schema block tells the client what the server speaks:

server:
  schema:
    base: auto            # auto, 2018 or 2023
    features: []          # functions borrowed from the other edition
    extensions: auto      # auto, or a list: csip-aus-1.2, csip-aus-1.3
  • base is the edition the server implements. auto reads the DeviceCapability: a schemaVer of 2.2 or higher means 2023, and anything else, including no schemaVer, means 2018. The 2023 schema makes the attribute optional, so a missing one is weak evidence; the client logs the decision and its evidence at INFO, and base overrides it. A discovered server's advertised level (DNS-SD -S1, -S2) sets auto first.
  • features are functions a server adopts from another edition, for example a 2018 server that takes the 2023 import and export limits. They are never detected: list them or they are off. import_export_limits is opModMaxLimWAbsorb and opModMaxLimWInject with DERControlType2 bits 7 and 8 in DERCapability modesSupported2, DERSettings modesEnabled2 and DERControlResponse modesResponded2. A feature permits those bits; the connector decides which it sets. A connector advertises an additional mode only when it implements the matching update_<element> method (for example update_op_mod_max_lim_w_inject), or states its own bitmap in supported_modes2() when it implements a method it cannot honor on the device.
  • extensions are schemas in other namespaces. auto detects CSIP-AUS from the namespaces the server declares, on every discovery. A list replaces detection: [] sends no CSIP-AUS elements to a server that declares them.

Inbound, the client accepts any element either edition defines and logs, at INFO, each element the server sends that its base does not define and which feature covers it. Outbound, it sends a 2023 element to a 2018 server only when an enabled feature covers it: DERStatus carries genConnectStatus and storConnectStatus and not connectStatus, no payload carries schemaVer, DERControlResponse carries no modesResponded, and a rejection goes out as status 252 where 2023 uses 251 (Table 27 against Table 31).

server.missing_location_fallback: true accepts a subscription the server created without a Location header, under a synthetic URI. Both editions require the header on a created resource, so this is a workaround for a non-conforming server, off by default.

server.server_2018_compat is deprecated. true means schema.base: 2018 plus missing_location_fallback: true; false means schema.base: 2023. It logs a warning that names the replacement.

What it does on start

  1. Loads and validates the configuration, then configures logging.
  2. Connects, retrying with backoff while the server is unreachable — a client on a gateway usually starts before the server is up, and exiting would just move the problem to whatever restarts it.
  3. Registers an EndDevice for its own certificate identity, but only if the server does not already have one. Registering unconditionally would create a duplicate on every restart and the utility would see one device as several. A server that refuses in-band registration is not fatal; many provision out of band.
  4. Starts reporting each configured device, unless telemetry.enabled is false.
  5. Polls once, then runs the schedule until stopped.

What it reports

With telemetry.enabled — on by default — each configured device is read on a schedule and reported to the server:

Resource How often
Meter readings, as MirrorUsagePoints post_rate_seconds
DERStatus post_rate_seconds
DERAvailability post_rate_seconds
DERSettings, when it has changed der_settings_poll_rate_seconds
DERCapability, when it has changed der_capability_poll_rate_seconds
LogEvents, when a device raises an alarm On the reading cycle

A device configured as a meter reports its readings only; see Meters.

If the server answers a readings POST with 400 or 404, it no longer knows the device's MirrorUsagePoint, for example after it restarted with a new resource tree. The client then POSTs the MirrorUsagePoint again in the same cycle and posts that cycle's readings to the new one, so nothing is lost beyond the refused POST. It makes one re-POST per cycle: if the re-POST fails or the readings are refused again, the next cycle tries again. A 403 is not retried; it means another client owns the MirrorUsagePoint, and the device stays blocked until it is restarted.

der_resource_put_policy: on_change replaces the two DER resource rates. It PUTs DERCapability and DERSettings once each, at startup, and then only when the content changes. A changed DERCapability also resends DERSettings. A rediscovery does not resend unchanged content, but a reconnect after a sustained loss of contact resends both, since the server may have lost them (CSIP G29). The default, periodic, keeps the rates in the table.

With subscription.enabled, subscription.renewal_method: put renews each subscription with a PUT to its own href (IEEE 2030.5 Annex A.2.7.2), and posts a new one to the list when the server answers 404 or 405; the default, post, re-POSTs it to the list. subscription.backstop_poll_seconds (default 900) sets how often a subscribed resource is still polled, in case notifications stop; it is never faster than the resource's pollRate.

On shutdown the client DELETEs its subscriptions, all at once, and waits at most 2 s for the answers (CsipClient.shutdown(subscription_cancel_timeout=...)); a subscription the server has not confirmed by then stays on the server. The notification listener then stops, waiting at most 2 s for a notification still being received (NotificationServer(shutdown_timeout=...)). An unreachable or unresponsive server therefore no longer holds a stop for the HTTP timeouts.

subscription.adopt_existing: true is for a client that takes over from another instance of itself, such as a standby that replaces a failed primary with the same certificate and the same notification_external_host and port. Both instances are then the same EndDevice to the server, and without adoption the new one POSTs a further subscription for every resource; a server that does not treat that POST as a renewal (IEEE 2030.5-2023 §8.9.3.4) keeps both, and each notification arrives once per set. With adoption, the client reads every page of its EndDevice's SubscriptionList when it connects, takes over each subscription whose notificationURI is its own and whose resource it would subscribe to, and POSTs only for the resources left. An adopted subscription's last renewal time is unknown: with renewal_method: put it is renewed at once; with post it is renewed on the renewal task's first pass, because a re-POST to a server that does not treat it as a renewal would create another copy. subscription.remove_duplicates: true also DELETEs the further subscriptions of its own it finds for a resource it adopted. A subscription with any other notificationURI is never adopted or removed. The comparison ignores differences a server may introduce when it echoes the URI: the case of the scheme and host, an explicit default port, percent-encoding case, and a trailing slash. If the server does not return its SubscriptionList, the client logs a warning and subscribes as it would without adoption. Embedding code can call CsipClient.adopt_subscriptions() itself.

subscription.unsubscribe_on_close: false is the other half of a handover: the instance that stops leaves its subscriptions on the server for the instance that adopts them, instead of DELETEing them at shutdown. The default, true, DELETEs them as described above. If an instance that hands over does DELETE them, the adopting instance's SubscriptionList check creates them again at the list's pollRate, and notifications sent in between are lost. Embedding code can decide per stop with CsipClient.shutdown(unsubscribe=False).

The server has the final say on the posting rate: an EndDevice.postRate above zero replaces post_rate_seconds for that device, which is what IEEE 2030.5 specifies. A server exposing no MirrorUsagePointList stops the readings only — the DER resources are a separate conversation and are still PUT — and the client says so once rather than failing a cycle forever.

reading_profile sets how the readings are encoded. default is the historical encoding. signed_load_convention carries the sign on every value (flowDirection 0), with active power negative on export and reactive power negative on injection, leaves commodity, dataQualifier and kind Not Applicable, and adds line-to-line voltage and State of Energy readings when the device supplies them. It is read at startup: a change alters the units and sign of readings already on the server, so it takes a restart. For a DER and a DER meter, export is the DER's output, so generation posts negative W. For a site meter, export is power from the premises to the grid: import posts positive W and var, and export negative (see Meters).

signed_as_reported posts W, var and power factor with the sign the connector reports, for every role: for a DER, positive while it delivers power and negative while it absorbs it, so a charging battery posts negative W. It omits flowDirection from every ReadingType that does not state one, keeps the default values of every other field, and gives no energy total a slot, since WhFwd and WhRev differ only by flowDirection; a connector that states a flowDirection for one still has it registered. A cycle with no reading to post, such as a charger with no vehicle plugged in, sends no readings POST at all; the MirrorUsagePoint stays. A connector that declares its readings (see Connectors) gets a MirrorUsagePoint of exactly those, posted once.

power_direction sets how real and reactive power carry their direction under the default profile. IEEE 2030.5 does not let a MeterReading's ReadingType change once it is created, so the choice matters for a device whose power changes direction, such as a battery:

Value What is posted
default flowDirection 1 (Forward) or 19 (Reverse), set once from the sign when the MirrorUsagePoint is created, with the magnitude. A battery that registered while discharging and later charges is still posted as Forward.
net flowDirection 4 (Net, forward minus reverse) with the sign on the value: positive while the device delivers power, negative while it absorbs it.
split Two readings per quantity, flowDirection 1 (Forward) and 19 (Reverse), each a magnitude; the direction not in use posts 0.

net and split post their readings under new mRIDs, so switching between modes never posts a value under a ReadingType registered for another mode. They apply to total and per-line W and var. power_direction is refused with signed_load_convention and signed_as_reported, which already sign every value. Like the profile, it is read at startup.

Keeping registrations across restarts

IEEE 2030.5 does not let the server's ReadingType for a reading change once it is created (2030.5-2023 10.10.3 rule n). Under the default profile and power_direction: default, a reading's flowDirection comes from the sign of its value when it is first registered. A client that restarts while a battery charges would register the same reading as Reverse instead of Forward.

telemetry.state_file names a file that keeps what was registered. The client loads it at start and repeats each registration exactly, writes it again after every change to the registered readings (through a temporary file and a rename), and writes it at shutdown. --telemetry-state-file sets the same path from the command line, and --check shows it. Unset, nothing is kept.

telemetry:
  state_file: telemetry-state.json

A file written under another reading_profile or power_direction, of another version, or damaged is ignored with a warning, and so is any entry in it that does not parse. Without a saved registration for a device, which includes the first start after upgrading from 0.16, the readings register from the current sign and the client logs one warning per device saying that they may differ from an earlier registration. An embedding application stores the same data with TelemetryCoordinator.to_checkpoint() and restore_from_checkpoint().

Rediscovery re-reads every path. A server that moves its resources, or that brings the MirrorUsagePoint function set online only after the client connected, is picked up without a restart.

Meters

A configured device is a DER unless its role says otherwise. A meter is configured like any other device, with a role:

devices:
  - type: sunspec
    lfdi: "0000000000000000000000000000000000000000"
    host: 192.168.1.50
  - type: sunspec
    lfdi: "2222222222222222222222222222222222222222"
    host: 192.168.1.60
    role: site_meter
role The device MirrorUsagePoint roleFlags Positive real power
der (default) A DER 0x49: isMirror, isDER, isSubmeter Output
site_meter The meter at the premises point of delivery 0x03: isMirror, isPremisesAggregationPoint Import, from the grid to the premises
der_meter A meter on one DER's circuit 0x49, as for the DER The DER's output

revenue_quality: true adds isRevenueQuality (0x10) to the roleFlags.

The two values follow the RoleFlagsType definitions in IEEE 2030.5-2023: isSubmeter "SHALL be set if the usage point is not a premises aggregation point", so the site value leaves it clear. CSIP-AUS v1.1a (January 2023), Annex A, lists the same values, 0x03 for the site's real and reactive power and 0x49 for the DER's. The CSIP-AUS v1.2 explainer (May 2025) keeps one MirrorUsagePoint for site measurements and one for device measurements and refers their definition to the utility handbook, so check the values against the edition the utility tests to.

A meter takes no controls and has no DER resources. The client PUTs no DERCapability, DERSettings, DERStatus or DERAvailability for it and posts no LogEvents. A control addressed to a meter is answered with status 252 (Not Applicable), and a control fanned out across several local devices skips the meters rather than reporting them.

mirror_under sets the LFDI a site meter's MirrorUsagePoint carries in its deviceLFDI element. IEEE 2030.5 defines that element as "the LFDI of the device being mirrored", so own, which puts the meter's lfdi there, is the literal reading. site, the default, puts the client's own EndDevice LFDI there instead, the one its certificate identifies, which stands for the site: a meter has no EndDevice of its own on the server, and a server that accepts mirrors only for registered EndDevices refuses a MirrorUsagePoint naming an LFDI it does not know. If a server rejects a site meter's MirrorUsagePoint, or expects the meter's own LFDI there, set mirror_under: own. The setting is refused on any other role; a der_meter always carries its own lfdi. A meter's lfdi names it and seeds the mRIDs of its readings, so it must differ from every other device's, but the meter needs no certificate. A site meter under the site's EndDevice therefore shares that EndDevice's LFDI with the site's DER without sharing an mRID with it.

A meter's readings are real power, reactive power, frequency, current, average voltage, the power factor's magnitude, apparent power, the per-phase values its model has, and two energy totals in Wh, each a Summation (accumulationBehaviour 9): energy in the forward direction (flowDirection 1) and in the reverse direction (19). For a site meter forward is energy imported. For a DER meter it is the DER's output, which such a meter counts as exported. The energy totals are posted under the default reading profile only; signed_load_convention does not define them.

The SunSpec meter models do not say which sign of real power is import, and meters differ. power_sign sets it for a SunSpec meter:

power_sign What the client does
auto (default) Learns the sign from which energy total, imported or exported, rises while real power is not zero. Real and reactive power are not posted until two readings agree; the client logs once at INFO when it has learned the sign.
import_positive Positive W from the meter is import.
export_positive Positive W from the meter is export.

The client keeps comparing the totals with the sign in use, and logs a WARNING once if they contradict it on three readings in a row. Reactive power is oriented like real power. power_sign is refused on a DER.

A site meter's power changes direction during the day, so power_direction: net or split keeps that direction on the server, where default fixes it when the MirrorUsagePoint is created. For a site meter, net posts import positive and export negative, and split posts import as Forward (1) and export as Reverse (19), the same directions as its energy totals.

Under reading_profile: signed_load_convention, real and reactive power carry the load convention's sign: negative on export. A site meter's import positive values already follow it, so they are posted as the meter reports them: import positive, export negative. A DER meter's values, like a DER's, are positive for the DER's output, which is export, so they are negated. The power factor takes the sign of the reactive power posted with it. A real or reactive power reading the connector marks Net (flowDirection 4) is signed the same way, in the same frame, and keeps its flowDirection.

The operations history keeps a site meter's readings in a series of their own, beside the devices'.

How an event ends

An event runs to the end of its interval unless the server ends it sooner. Two signals do that, and the client honors both:

  • EventStatus.currentStatus set to 2 on an event still in the list.
  • The event removed from the DERControlList before its Effective Scheduled Period is over. IEEE 2030.5-2023 §10.2.2.3 rule p) makes removal a cancellation, and notes that this differs from earlier revisions: a server built against IEEE 2030.5-2018 signals cancellation only by setting the status.

Either signal reverts the device to the DefaultDERControl and POSTs "The event has been cancelled" when the event's responseRequired asks for it. Cancelling an event that is already running applies the wind-down randomization §10.2.3.3 requires, so the revert can land later than the cancellation that caused it.

An event with randomizeStart or randomizeDuration is randomized per device, as IEEE 2030.5-2023 §10.2.3.2.2 and §10.2.3.2.3 require: each EndDevice the client acts for draws its own offsets, so the devices of one event start and end at different moments rather than as one block, and each device's ACTIVE and COMPLETED Responses are posted at its own start and end. An event received after its start begins on each device at the current time plus that device's start offset (§10.2.2.3 rule k), and a successive event starts on each device where the earlier one ended on it (rule m). A device whose own randomized window has already ended when the event arrives is not dispatched and is answered EXPIRED (rule j).

Removal is acted on only when the list was fetched completely. A DERControl fetch that fails or does not parse leaves the client holding no list rather than an empty one. The distinction matters: an empty list is a server that removed every event, and treating a failed fetch as one would revert every device on a single transient error.

Which devices a program controls

A DERProgram controls the EndDevices whose function set assignments list it, and a device can reach one program through more than one assignment. Each poll of the program lists reads those assignments again. A device whose assignments no longer name a program stops receiving that program's controls while the other devices keep them, so withdrawing one device from a program does not wait for a full rediscovery.

A device with no assignments is mapped from the DeviceCapability program list when the server has one, as at discovery. A device keeps its programs on a poll where one of its program lists could not be read, or the server did not serve it (404 or 204). The list that failed may be the one that names them, so the client does not treat the failure as a withdrawal; a list the server serves and that names nothing is a withdrawal.

A withdrawal also ends the control a running event holds on the device, as soon as the poll finds it. IEEE 2030.5-2023 §8.8.3 has a client act on the events of the function set assignments it is in, so a device no longer assigned to a program is no longer governed by that program's events. The client releases the event's modes on that device as it would at the event's end: a mode the device's other programs' defaults do not carry is switched off, and the default that now governs the device is applied. The event keeps running on its other devices. The standard defines no response status for a withdrawal, so the client posts none for that device, and the event's later "completed" or "cancelled" response goes only to the devices still running it. Where a group lookup stands in for the program's devices, the whole group is the program's reach, so nothing is released until the event ends. A device the client finds withdrawn only after the event has ended, or by a full rediscovery, is released when the event ends.

The same release happens for every device an event held when its whole program is removed.

Superseded events and the modes they give up

When a higher-priority event takes over some of an event's modes on a device, the event that took them owns them from then on, and its own end is what releases them. The superseded event keeps only the modes that were not taken. So when the superseding event ends first, the client releases those modes on the device at that moment, by applying the default's value or switching the mode off when no default names it. It does so whether or not the superseded event is still running, and whether or not another event is running on the device.

The CSIP-AUS limits (opModExpLimW, opModImpLimW, opModGenLimW and opModLoadLimW) are modes like any other. CSIP-AUS v1.1a §5.2.4.1 puts DERControls under the IEEE 2030.5 event rules, and IEEE 2030.5-2023 §10.2.2.3 rule q) supersedes overlapping events mode by mode. A higher-priority event with opModExpLimW therefore supersedes a lower-priority event with opModExpLimW on the same device and leaves that event's other limits and modes running. Two events that carry different limits do not supersede each other. Events with no CSIP-AUS elements are compared as before.

Default controls while an event runs

IEEE 2030.5-2023 §10.10.4.2.1 manages a DER by the DefaultDERControl for each control mode that has no active DERControl. The client applies it that way. A device with an active event still receives the default's modes that no active event controls on that device, and does not receive the modes an event controls. A default that names only modes an active event controls writes nothing. When the event ends, the whole default is applied, as before.

A mode goes to the default of the program with the lowest primacy that names it, so a default does not write a mode that the default of a higher-priority program also names, and a program's default still writes the modes no higher-priority default names. The client works this out from the programs as they stand, and writes a mode that has since been freed even when the same default was written before without it. The choice is the same when a device first receives its defaults and when an event ends: a device in two programs receives each mode from the lowest-primacy default that names it, whichever program that is. Programs of equal primacy are ranked in the order the device was assigned to them, so a mode both name has one source. The default of the lowest-primacy program also carries the settings that are not modes, such as setGradW; the other defaults supply only modes.

A default that names no control mode is not applied to a device while an event is active on it.

A control the device cannot apply

A DERControl may name modes the device's connector does not implement. The client applies the modes it can and skips the rest, including a mode the connector declines when it tries to apply it. When the connector implements or accepts none of the modes a control names, nothing is applied, so the client does not report the event as started. It answers with status 251 (Not Supported), or 252 for a server on the 2018 edition, where 251 is reserved. For a group of devices under one EndDevice, the answer is a rejection only when every device in the group rejects the control.

Simulating a loss of communications

comms_loss_seconds puts the client into loss-of-communications mode after that long without reaching the server: it opts out of the rest of any active event, manages the DER at the planning limit, and keeps opting out until contact returns. Verifying that behavior normally means taking the server away, which is not something you can do to a production head-end.

CsipClient.simulate_comm_loss(duration_seconds) produces the silence instead. Outbound requests fail as though the network were gone, and notifications are accepted but not acted on, so the ordinary detector sees exactly what a real outage looks like and reacts the same way. Nothing is faked downstream of that: the detector, the diagnostics, the retry ladder and the recovery path all run for real.

status = await client.simulate_comm_loss(1200)   # 20 minutes
...
status = await client.clear_comm_loss_simulation()

A few things worth knowing before you point this at a live site:

  • The window always closes. It expires on its own, and a restart clears it. There is no way to leave a site isolated by forgetting about it.
  • Activation waits for work already in progress. A request already talking to the server, or a notification handler already running, is allowed to finish first — otherwise one of them completes just after you were told the link was down, and refreshes the contact clock or applies a setpoint. The returned status reports whether both drains finished; if one did not, the isolation was not clean and the window is still open.
  • Clearing drives recovery immediately. Left to the schedule, the client would not leave comms-loss mode until the connectivity heartbeat and then a probe tick had both come round, which on default settings is over two minutes of looking like nothing happened.
  • phase tells you how recovery went. Clearing the gate and leaving comms-loss mode are different events, and recovery re-polls schedules against the real server, so it can fail. Watch for recovered rather than assuming it.
  • The device does not rejoin the event it was opted out of. That is the ordinary comms-loss rule, not an artifact of the simulation: the resume-after boundary holds the DER at the planning limit until an event starting after it arrives.
  • The loss-of-communications record is marked. When the injected failure is what produced the silence, that diagnostic carries a simulated flag, so it cannot be mistaken for a genuine outage. Attribution follows the failures themselves, not merely whether a window was open: a link already down when you arm a simulation still reports a genuine outage. The flag is on that entry specifically — other diagnostics raised while a window is open are not marked, deliberately, so that a real fault occurring during a test stays legible as one.
  • The redirect probe is not gated. run_redirect_probe opens its own connection for its first leg, so that step still reaches the network during a window and will appear to succeed while the second leg fails. It does not feed connectivity health, so the detector is unaffected — but the mixed result is confusing if you run the probe mid-simulation.

The client applies no policy of its own here: it will isolate itself whenever asked, for as long as asked. Deciding whether simulation should be available at all, and bounding how long a window may run, belongs to whatever is driving it.

Stopping

SIGINT or SIGTERM asks it to stop; it finishes what it is doing and closes its session in order. Ctrl-C works on every platform.

Exit codes

Code Meaning
0 Stopped on request
2 The configuration is wrong — retrying will not help
3 The server could not be reached, or the run loop failed

Distinguished so a supervisor can restart on 3 and not restart-loop on 2.

Under systemd

A complete unit is at examples/systemd/py20305.service, with the install steps -- service account, virtualenv, certificate permissions -- in the README beside it. The essentials:

[Service]
Type=simple
ExecStart=/opt/py20305/venv/bin/py20305 --config /etc/py20305/client.yaml
Restart=on-failure
RestartPreventExitStatus=2
User=py20305
Group=py20305

RestartPreventExitStatus=2 is the point of the distinct exit codes: a broken configuration stops rather than restarting forever.

The shipped unit adds the sandboxing a client needs none of the privileges around -- read-only filesystem, no devices, no new privileges. Those assume a device reached over Modbus TCP; one on a serial port needs its tty granted back, and the unit says how.

This package deliberately does not supervise itself. Retrying the connection is its job; restarting a crashed process is systemd's, and doing it here would hide failures from the thing meant to observe them.

The management API

Off by default. When enabled it binds to loopback, because it is unauthenticated — exposing it on a routable address makes the client's controls available to that network.

api:
  enabled: true
  host: 127.0.0.1
  port: 8080

Needs the api extra. See Management API.

The operations history

On by default. The client keeps every event's lifecycle and responses, every device write, and each device's readings in 15-minute intervals, with a site meter's readings in a series of their own, in py20305-history.sqlite3 in the working directory. Each part can be switched off, or all of it:

history:
  enabled: false

See Operations history.

Logging

Always to stderr, which is what journald and docker logs collect. Add a file if you also want one:

logging:
  level: INFO
  file: /var/log/py20305/client.log

--log-level DEBUG overrides the configured level for one run. It does not change where the logs go.

Only the runner configures logging. The library itself just calls getLogger, so embedding it never takes handler policy away from your application.