SmartThings-Local
smartthings-local is a Python library for local, cloud-free control of Samsung connected appliances over authenticated CoAP-DTLS. It gives you the DTLS-CoAP transport, a tiered polling + OBSERVE state layer, and identity-cert tooling for AC14K_M-compatible firmware. Newer OCF-PKI appliances require a different authentication profile; see the laundry compatibility findings. Supported profiles can read state and write commands on the LAN with no SmartThings cloud round-trip.
The repo also ships a self-contained reference bridge demo (mqtt_demo/) that turns the library into auto-discovered Home Assistant entities over MQTT. One process supervises multiple appliances, each on its own DTLS session. Configuration, deployment and per-appliance coverage are in docs/bridge-demo.md.
Just want to control your Samsung appliance from Home Assistant?
Use localthings, a Home
Assistant custom component built on the smartthings-local package.
This repo is the protocol research project, the library itself, and a
self-contained MQTT bridge demo; new appliance support (capability
mappings, HA entities) should go to localthings, not here.
Documentation
docs/api.md — the supported API: every name downstream code may import, with its signature. Generated from the code, so it cannot drift.
docs/bridge-demo.md — the MQTT bridge demo: what it exposes, how to configure and deploy it, per-appliance coverage, config keys and topics.
docs/appliance-compatibility.md — which appliances answer a local session, how to check, and the firmware-family caveat.
docs/firmware-families.md — identifying which OCF stack and directory dialect an appliance runs, and what each stack binds.
docs/certificates.md — obtaining the client certificate compatible firmware accepts.
docs/appliance-resources.md — every OCF resource two appliances expose, what each one carries, and the probe or test that established it.
docs/ocf-pki-laundry.md — the newer OCF-PKI appliance generation, and why an AC14K_M certificate is refused there.
docs/oven-cook-start.md — starting an oven cycle from a local session: the single collection write that carries the cook parameters and the run command.
docs/ocf-vd-devices.md — server-authenticated findings from Samsung VD hardware.
docs/use-of-ai.md — how an AI assistant is used here, and the review the output goes through.
Quick start (library)
smartthings-local is on PyPI:
pip install smartthings-local
For compatible firmware, mint a client cert once (see
Getting a certificate), then drive a
session directly:
import cbor2
from smartthings_local.protocol.auth import CertificateAuth
from smartthings_local.protocol.dtls_session import DtlsCoapSession
auth = CertificateAuth.from_files(
"certs/client_fullchain.pem",
"certs/client.key",
)
sess = DtlsCoapSession(
"192.0.2.100", 49154,
auth=auth,
on_notification=lambda href, payload: ...,
)
sess.connect()
sess.start_reader()
code, body = sess.get(["device", "0"]) # Block2-aware read
code, _ = sess.post(["mode", "vs", "0"], cbor2.dumps({})) # write
sess.subscribe(["operational", "state", "vs", "0"]) # OBSERVE
sess.close()
get() and post() accept repeated URI-query strings. They also accept
ordered (number, bytes) options for reviewed OCF extensions while retaining
ownership of path, query, content-format, Accept, Observe, and blockwise
options:
code, body = sess.get(
["oic", "res"],
query=("rt=oic.r.doxm",),
extra_options=((2049, b"\x08\x00"),),
)
Path and query text is UTF-8 encoded, and every value is size bounded before
anything is sent. Additional options remain arbitrary bytes, must already be
ordered by option number, and may repeat a number when the option is
repeatable.
delete() uses the same path, query, extension-option, timeout, and response
contract without sending a request payload.
Observe relations may also include repeated URI-query strings. The same query
is retained for a blockwise notification refetch and for best-effort
deregistration:
sess.subscribe(["mode", "vs", "0"], query=("if=oic.if.b",))
An RFC 7641 relation is confirmed only by a valid Observe response option;
duplicate and stale 24-bit sequence values are not delivered. Some older
Samsung firmware omits that option. For those devices, a plain initial 2.05
is probationary until a later packet arrives on the same token with a different
Message ID. Its complete representation is still delivered through
on_notification; a blockwise representation is re-read before delivery.
Optional on_observe_pending, on_legacy_notification, and on_observe_error
constructor callbacks let consumers keep that compatibility path distinct from
confirmed RFC notifications and ordinary polling.
on_observe_delivery replaces on_notification for consumers that need the
whole relation context rather than (href, payload). It receives one
ObserveDelivery, whose registration field separates the server's answer to
the register CON from a change the server chose to send, and whose query
completes the relation identity when one href carries several query-qualified
relations. sequence is the Observe option value, or None on the optionless
responses some firmware sends. Setting it suppresses on_notification and
on_legacy_notification, so representations are delivered once:
def on_delivery(delivery):
if delivery.registration:
seed(delivery.href, delivery.payload) # answered because we asked
else:
record_push(delivery.href, delivery.payload)
sess = DtlsCoapSession(..., on_observe_delivery=on_delivery)
Periodic renewal can target only the relations that need it; unrelated
observations remain active. Existing query variants are preserved unless the
caller supplies an explicit replacement:
successful, failures = sess.refresh_observes(
(("mode", "vs", "0"),),
queries_by_href={"/mode/vs/0": ("if=oic.if.b",)},
)
removed = sess.unsubscribe(("mode", "vs", "0"))
successful reports hrefs whose replacement registration datagram was sent;
confirmation still comes from the Observe callbacks. unsubscribe() retires
every query-qualified relation for that exact path without disturbing sibling
paths. Refresh, unsubscribe, and orderly close pace every deregistration just
as subscribe() paces each registration, avoiding request bursts during
relation maintenance.
POST bodies through 1024 bytes retain the single-request behavior. Larger
bodies use token-stable Block1 requests under one monotonic timeout, include
Size1 on the first request, honor a server-requested smaller block size, and
return only the final response. Upload bodies are limited to 512 KiB and 1024
block requests; incomplete or contradictory success acknowledgements fail as
BlockwiseError.
connect() uses a 12-second monotonic DTLS handshake deadline by default. A
caller that needs a shorter bounded attempt can pass a positive finite value
without changing later reader timeouts. OpenSSL's DTLS timer schedules flight
retransmissions within that same deadline:
sess.connect(timeout=4.0)
The deadline stops further setup, retries, and network waits. If OpenSSL
reports that the handshake completed at the deadline boundary, the completed
session is retained rather than torn down as a timeout.
Connection attempts can also use a one-way cancellation signal. The signal is
backed by a socketpair, so setting it wakes the network wait immediately while
OpenSSL retains control of DTLS retransmission timing:
from smartthings_local.protocol.dtls_session import ConnectCancellation
cancel_connect = ConnectCancellation()
# Another thread may call cancel_connect.set().
sess.connect(timeout=8.0, cancel=cancel_connect)
Setting the signal stops subscribed connection attempts and closes their
temporary UDP sockets. It does not alter an already established session.
Interrupted attempts raise SessionClosedError.
Some Samsung OCF-PKI firmware can retain a half-open DTLS peer when a
handshake stops immediately after the cookie exchange. A caller using a
SamsungServerProfile and a fixed non-zero local UDP port can opt in to the
narrow cleanup path:
from smartthings_local.errors import HandshakePeerCleanupError
try:
sess.connect(timeout=8.0, cleanup_hvr_peer=True)
except HandshakePeerCleanupError:
# Apply the device-specific settle delay, then retry under caller policy.
schedule_connection_retry()
Cleanup is sent only after the bounded transcript contains at least two
complete epoch-zero ClientHello messages and every received record is a
complete epoch-zero HelloVerifyRequest. A malformed, fragmented, mixed, or
oversized transcript remains an ordinary SessionTimeoutError. On the exact
HVR-only shape, the session sends one epoch-zero fatal handshake_failure
alert, closes the temporary socket, and raises HandshakePeerCleanupError.
The package never sleeps or retries automatically, so the caller retains the
overall recovery budget and can use the settle interval validated for its
device. Cancellation and backend failures never trigger the alert.
Hosts that stop network work before their blocking executor drains can use the
session's two-phase shutdown. quiesce_for_close() is terminal: it interrupts
an in-progress handshake, wakes pending requests and notification refetches,
and rejects new work while retaining an established DTLS socket and active
Observe relation metadata. A subsequent close() paces explicit Observe
deregistrations, flushes the authenticated close-notify record, and then closes
that socket:
sess.quiesce_for_close() # safe from the host's early shutdown phase
# Later, after session workers have joined:
sess.close()
Use abort() when orderly shutdown is impossible. It performs the same
terminal wakeup but closes the established socket immediately, without waiting
for close-notify. All three methods are idempotent; a quiesced or aborted
session cannot be connected again.
Writes and retransmission
Reads retransmit each Block2 request; writes send once. Where a lost write is
the proven cause, and not a device refusing load, write_max_attempts lets
post() retransmit inside the caller's timeout, backing off per RFC 7252 §4.2
and pacing each retransmit:
sess = DtlsCoapSession("192.0.2.100", 49154, auth=auth, write_max_attempts=3)
Each attempt resends the byte-identical datagram, so a §4.5 server answers the
duplicate from its dedupe cache. Retrying from the caller cannot do that — a second
post() mints a fresh Message ID, which is a new request. It defaults to 1
(send once) because retransmitting into an appliance that is already dropping
under load turns one lost write into several, and §4.5 dedupe is unverified on
these appliances.
Note that post()'s timeout bounds the whole call, rate-limit pacing
included, rather than only the wait that follows the send. Every attempt has to
share one budget, and a caller that asked for 8 seconds should not wait 8
seconds plus however long the limiter withheld the request. At the default 5
req/s that costs at most 200 ms of it; at rate_limit_rps=1.0 it costs a full
second, so pair a low rate limit with a longer timeout.
Authentication
Every session needs a credential. A certificate provider covers the
AC14K_M-compatible firmware families; the newer OCF-PKI generation needs a
pinned server profile or a PSK, and
docs/ocf-pki-laundry.md
covers which is which.
Getting a certificate
A compatible appliance accepts a client certificate whose Subject DN carries a UUID those appliances' on-device ACLs grant access to. On the appliances tested the signer is not checked, so setup_cert.py self-signs by default, using the UUID it carries as a constant. Pass --fallback to sign with AC14K_M instead, for a device that validates the chain:
python setup_cert.py
That writes certs/client_fullchain.pem and certs/client.key. Minting touches no appliance: the UUID is a constant and the key and leaf are made locally. To see what a device makes of the result, probe it:
python -m smartthings_local.protocol.dtls_probe <ip> <port> --diagnostic \
--cert certs/client_fullchain.pem --key certs/client.key