This document targets maintainers and contributors of device-sdk-python. It records
architecture constraints, coding conventions, the testing strategy, and the release process.
-
100% alignment with device-sdk-go v4
- Directory structure, module names, function signatures, constant names, error codes, and MessageBus topic formats must match the Go reference implementation exactly.
- Only minimal adaptations for Python language features (type annotations, dataclasses, async/await, exceptions instead of multiple return values) are allowed.
-
Zero-dependency core
internal/clients/{logger,secret,metrics}.pyuse only the standard library.- Optional heavy dependencies (e.g.
cryptographyfor TLS) must be lazily imported so the SDK starts without them installed.
-
Copyright headers
# Copyright (C) 2026 YIQISOFT # SPDX-License-Identifier: Apache-2.0
-
Configuration-driven, zero hardcoding
- Ports, hosts, topic prefixes, QoS, KeepAlive, etc. are read from
configuration.yaml/ environment variables. 59990appears only as the fallback default in the_DEFAULT_HTTP_PORTconstant.
- Ports, hosts, topic prefixes, QoS, KeepAlive, etc. are read from
-
Unit tests first, network isolation
- Unit tests must not depend on external MQTT/Metadata/Redis services.
_start_device_validation_handler,_start_command_subscription, etc. silently degrade to a log message when the client is unavailable.
| Path | Responsibility | Go equivalent |
|---|---|---|
interfaces/ |
ProtocolDriver, DeviceServiceSDK, AutoEventManager ABCs | pkg/interfaces/ |
models/ |
CommandValue, CommandRequest, AsyncValues, DiscoveredDevice | pkg/models/ |
internal/cache/ |
Devices/Profiles/ProvisionWatchers singleton caches | internal/cache/ |
internal/transformer/ |
Mask/Shift/Base/Scale/Offset, assertion, mapping, CBOR | internal/transformer/ |
internal/autoevent/ |
Scheduled acquisition executor + manager | internal/autoevent/ |
internal/application/ |
command_read/write, callbacks, device return, profile scan | internal/application/ |
internal/autodiscovery/ |
Discovery scheduler + locker | internal/autoevent/ (discovery) |
internal/clients/ |
Logger, secret store, metrics, Core Data/Command clients, TLS manager | pkg/clients/, internal/ |
internal/controller/http/ |
REST routes: command, discovery, common endpoints | internal/controller/http/ |
internal/controller/messaging/ |
MQTT client, event publish, command sub, system events callback | internal/controller/messaging/ |
internal/common/ |
Constants, error codes, utils, configuration | internal/common/ |
internal/metadata/ |
Core Metadata client | internal/metadata/ |
internal/provision/ |
YAML resource loader (devices, profiles, watchers) | internal/provision/ |
service/ |
DeviceService assembly, bootstrap entry | pkg/service/, service/ |
examples/simple/ |
Minimal runnable example | example/driver/simpledriver.go |
# stdlib
import logging
import threading
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
# third party
import paho.mqtt.client as mqtt
import cbor2
# local: use absolute imports (package name device_sdk_py)
from device_sdk_py.models import CommandValue
from device_sdk_py.internal.common.consts import API_VERSION
from device_sdk_py.internal.common.utils import EdgexError- Relative imports must not cross more than 2 levels (e.g.
from ...models); use absolute imports instead. - For circular dependencies, import inside a
TYPE_CHECKINGblock.
| Go | Python |
|---|---|
CamelCase functions/methods |
snake_case |
PascalCase types/constants |
PascalCase (kept for export compatibility) |
UPPER_SNAKE_CASE constants |
UPPER_SNAKE_CASE |
errors.EdgeX |
EdgexError (exception) |
Multiple return values (T, error) |
return T, raise EdgexError on failure |
context.Context |
implicit (correlation_id passed through) |
sync.Mutex |
threading.Lock / threading.Semaphore |
chan T |
queue.Queue[T] |
Go errors.Kind |
Python EdgexErrorKind |
HTTP Status |
|---|---|---|
KindContractInvalid |
KIND_CONTRACT_INVALID |
400 |
KindEntityDoesNotExist |
KIND_ENTITY_DOES_NOT_EXIST |
404 |
KindNotAllowed |
KIND_NOT_ALLOWED |
405 |
KindStatusConflict |
KIND_STATUS_CONFLICT |
409 |
KindServiceLocked |
KIND_SERVICE_LOCKED |
423 |
KindServerError |
KIND_SERVER_ERROR |
500 |
KindNotImplemented |
KIND_NOT_IMPLEMENTED |
501 |
- HTTP routes, headers, query parameters, device states, permission strings →
internal/common/consts.py(merges Goconsts.go+go-mod-core-contracts/common). - SDK-reserved prefixes such as
ds-,urlRawQuery,CorrelationHeaderlikewise.
Every public function/class must include:
def foo(bar: str) -> int:
"""Short description.
Mirrors `GoFunctionName` in go-file.go: notes the corresponding Go source location.
Args:
bar: Parameter description.
Returns:
Return value description.
Raises:
EdgexError: When it is raised.
"""Events: edgex/events/device/<svc>/<profile>/<device>/<source>
Commands: edgex/device/command/request/<svc>/<device>/<command>/<get|set>
Responses: edgex/response/<svc>/<requestId>
SysEvents: edgex/system-events/<svc>/<type>/<action>/<svc> (publish)
edgex/system-events/core-metadata/+/+/<svc>/# (subscribe)
edgex/system-events/core-metadata/deviceprofile/delete/#
edgex/system-events/core-metadata/provisionwatcher/+/<baseSvc>/#
Validation: edgex/<svc>/validate/device
- The base prefix defaults to
edgexand is configurable viaMessageBus.BaseTopicPrefix. - Name field escaping: device/profile/command names must conform to RFC3986 (Go uses
PathBuilder.EnableNameFieldEscape).
{
"apiVersion": "v3",
"correlationId": "uuid",
"requestId": "uuid",
"contentType": "application/json",
"payload": { ... },
"receivedTopic": "edgex/...",
"queryParams": { "ds-pushevent": "true" }
}- The
Checksumfield was removed (v3+). - When
contentTypeisapplication/cbor, the payload is base64-encoded CBOR bytes.
command_read/write→transformer.command_values_to_event→Eventpublish_event()→encode_event_request()(binary reading → CBOR, otherwise JSON)- Wrap in
MessageEnvelope→ checkMaxEventSize→client.publish(envelope, topic)
GET /api/v3/device/name/{name}/{command}
→ command.ReadController.get_command()
→ filter_query_params(ds-pushevent/ds-returnevent/ds-regexcommand)
→ application.command_read()
→ _validate_service_and_device_state() // 423 check
→ Profiles().device_command/resource lookup
→ driver.handle_read_commands()
→ transformer.command_values_to_event()
→ transform_read_result (Mask→Shift→Base→Scale→Offset)
→ check_assertion (failure → OperatingState=DISABLED)
→ map_command_value (ResourceOperation mappings)
→ Event
→ ds-pushevent → _send_event_handler() → MessageBus
→ ds-returnevent → EventResponse (JSON/CBOR)
ProtocolDriver → sdk.async_values_channel().put(AsyncValues)
→ DeviceService._pump_async_values() (background thread)
→ command_values_to_event()
→ _send_event_handler() → MessageBus
POST /api/v3/discovery
→ DiscoveryController.discovery()
→ driver.discover() (background thread)
→ sdk.discovered_device_channel().put([DiscoveredDevice])
→ DeviceService._pump_discovered_devices()
→ match ProvisionWatchers (allow/block lists)
→ MetadataClient.add_device(bypass_validation=True)
→ local cache Devices().add()
→ publish discovery progress system event
| Layer | File(s) | Coverage focus |
|---|---|---|
| Models | tests/test_models.py |
CommandValue typed getters/setters, binary/array/object encoding |
| Cache | tests/test_bootstrap.py |
Devices/Profiles/Watchers CRUD, admin/operating state, lastConnected |
| Transformer | tests/test_transformer.py |
Mask/Shift/Base/Scale/Offset, overflow→"overflow", assertion, mapping |
| AutoEvent | tests/test_autoevent.py |
Scheduling, concurrency, stop/restart |
| HTTP | tests/test_simple_example.py |
ping/version/device GET/PUT, ds-* query params, discovery/profile scan |
| Messaging | tests/test_system_events.py etc. |
client connect/pub/sub, command subscription, system events callback |
| Security | tests/test_secure_mode.py, tests/test_application_aligned.py |
Secret store, JWT, TLS manager, application layer |
# all tests
python -m pytest tests/ -q
# single file
python -m pytest tests/test_bootstrap.py -v
# coverage
python -m pytest tests/ --cov=device_sdk_py --cov-report=html- External dependencies: MQTT client, Metadata client, Secret provider → patch with
MagicMockin tests. - Time:
time.time_ns()→ patch to a fixed value. - Random IDs:
uuid.uuid4()→ patch to a predictable sequence.
- Add
transform_xxx()intransformresult.py. - Insert it into the
transform_read_result()chain (order: Mask→Shift→Base→Scale→Offset). - Call it in reverse on the write path via
_transform_write_parameter(). - Cover forward/inverse/overflow in unit tests.
- Add a
NatsMessageClientimplementing theMessageClientABC inclient.py. - Dispatch on
config.typeinnew_message_client(). - Map NATS-specific parameters in the
Optionalconfig section.
- Add
XXX_SYSTEM_EVENT_TYPE,SYSTEM_EVENT_ACTION_XXXinconsts.py. - Add a
_handle_xxx_system_event()dispatcher incallback.py. - Add the new topic to
subscribe_system_events(). - Implement the
DeviceService._on_xxx_*()callbacks.
| Step | Command |
|---|---|
| Bump version | src/device_sdk_py/__init__.py + pyproject.toml |
| All tests green | python -m pytest tests/ -q |
| Example runs | cd examples/simple && python -m device_service (background) + curl /api/v3/ping |
| Docs in sync | README.md, DEVELOPMENT.md, CHANGELOG.md |
| Build distribution | pip wheel . -w dist/ |
| Tag | git tag v4.x.x && git push --tags |
- EdgeX Foundry documentation (latest)
- ADR 0011 - Device Service REST API
- ADR 013 - Device Services Send Events via Message Bus
- device-sdk-go v4 source
- go-mod-core-contracts v4
- app-functions-sdk-python
| Date | Version | Notes |
|---|---|---|
| 2026-08-06 | 4.0.0 | Initial port: REST, MessageBus, command sub, system events, async/discovery pumps, CBOR, assertion, full configuration |
| 2026-08-21 | 4.0.1 | Core Keeper registry support, TLS/mTLS manager, OpenBao secret store, JWT auto-refresh, Core Data/Command clients, default port 59990 |