DPSN MQTT client for managing topic subscriptions and publications
Project description
dpsn-client (Python)
Overview
dpsn-client is a Python SDK for interacting with the DPSN infrastructure. It allows you to connect to a DPSN broker using your Ethereum wallet for authentication, publish messages to topics, and subscribe to topics to receive messages.
For more information, visit:
Installation
pip install dpsn-client
Note: If installing from source or locally, navigate to the root directory and run
pip install -e .
Usage
Prerequisites
- DPSN URL: The hostname of the DPSN MQTT broker (e.g.,
betanet.dpsn.org). - Wallet Private Key: Your Ethereum private key (starting with
0x). This wallet will be used for authentication. Ensure it's kept secure. - Chain Options: Specify the network (
mainnetortestnet) and chain type (ethereum).
(Blockchain interaction features like purchasing topics, fetching owned topics, and getting topic prices are planned for future versions and require additional configuration not yet implemented in this Python client.)
Import the Library
from dpsn_client import DpsnClient, DPSNError
Create Client Instance
Initialize the client with your DPSN broker URL, private key, and chain options.
dpsn_url = "your-dpsn-broker.com" # e.g., betanet.dpsn.org
private_key = "0xYOUR_PRIVATE_KEY" # Replace with your actual private key
client = DpsnClient(
dpsn_url=dpsn_url,
private_key=private_key,
chain_options={
"network": "testnet", # or "mainnet"
"wallet_chain_type": "ethereum"
},
# Optional: connection_options={'ssl': True} # Default is True
)
Understanding DPSN Topics
Topics in DPSN are data distribution channels designed for secure, permissioned data streams associated with blockchain wallets.
-
Ownership-based channels: While topic purchase happens on the blockchain (feature planned), the MQTT authentication relies on the owner's wallet.
-
Data streams: Authenticated publishers push data to topics, and subscribers receive data.
-
Authenticated channels: The client uses signatures derived from the owner's private key to authenticate actions like connecting and publishing.
-
When publishing data, the publishing client uses the same private key that purchased the topic to authenticate the request, ensuring only authorized wallets can publish to their owned topics.
(Full topic lifecycle management via smart contracts, including purchasing and ownership verification).
Setup Event Handlers
Use decorators to define handlers for asynchronous events like receiving messages or errors. Set these up before calling init().
@client.on_msg
def handle_message(message_data):
"""Handles incoming messages."""
topic = message_data.get('topic')
payload = message_data.get('payload')
logger.info(f"Received message on topic '{topic}': {payload}")
@client.on_error
def handle_error(error: DPSNError):
"""Handles errors reported by the client."""
logger.error(f"DPSN Client Error: {error}")
# You can also add handlers later if needed:
# client.on_msg += another_message_handler
# client.on_error += another_error_handler
Initialize DPSN Client
Connect to the DPSN MQTT broker. This authenticates using a signature generated from your private key.
### Publish Data
Publish a JSON-serializable message to a specific topic string. The topic must start with your wallet address (`0x...`).
> **Caution:** You must initialize the client with the private key corresponding to the wallet address used in the topic prefix.
```python
# Example topic
publish_topic = "0xe14768a6d8798e4390ec4cb8a4c991202c2115a5cd7a6c0a7ababcaf93b4d2d4/BTCUSDT/ticker"
data_to_publish = {"ticker": "BTC/USDT", "price":83387.13000000, "timestamp": time.time()}
try:
#Publishing to topic
client.publish(publish_topic, data_to_publish, options={'qos': 1})
#Message published successfully
except DPSNError as e:
logger.error(f"Failed to publish: {e}")
except ValueError as e:
logger.error(f"Publish error (invalid topic format?): {e}")
Subscribing to Topics
Subscribe to a topic pattern to receive messages.
subscribe_topic = "0xe14768a6d8798e4390ec4cb8a4c991202c2115a5cd7a6c0a7ababcaf93b4d2d4/BTCUSDT/ticker" # Subscribe to topic
try:
#Subscribing to topic
client.subscribe(subscribe_topic, options={'qos': 1})
#Successfully subscribed to the topic
# Keep the script running to receive messages
logger.info("Waiting for messages... Press Ctrl+C to exit.")
while True:
time.sleep(1)
except DPSNError as e:
logger.error(f"Failed to subscribe: {e}")
except KeyboardInterrupt:
logger.info("Interrupted by user.")
Unsubscribing from Topics
Stop receiving messages from a specific topic.
# Unsubscribe ongoing topic subscription
try:
client.unsubscribe(subscribe_topic)
except DPSNError as e:
print(f"Failed to unsubscribe: {e}")
Disconnect
Disconnect cleanly from the MQTT broker.
# Disconnect client connection
try:
client.disconnect()
except DPSNError as e:
print(f"Error during disconnect: {e}")
API Reference
Class DpsnClient
Manages the connection, authentication, and messaging with the DPSN client. Inherits from events.Events.
Constructor
DpsnClient(
dpsn_url: str,
private_key: str,
chain_options: Dict[str, Any],
connection_options: Dict[str, Any] = None
)
dpsn_url: Hostname of the DPSN broker.private_key: Ethereum wallet private key (0x...).chain_options: Dictionary, requires{"network": "mainnet"|"testnet", "wallet_chain_type": "ethereum"}.connection_options: Optional dictionary, e.g.,{"ssl": True}(default).
Methods
init(options: Dict[str, Any] = None) -> mqtt.Client: Connects and authenticates to the broker.optionscan includeretry_options. RaisesDPSNErroron failure.publish(topic: str, message: Any, options: Dict[str, Any] = None) -> None: Publishes a JSON-serializablemessagetotopic.topicmust start withself.wallet_address.optionscan includeqos(default 1) andretain(default False). RaisesDPSNErrororValueError.subscribe(topic: str, options: Dict[str, Any] = None) -> None: Subscribes totopic.optionscan includeqos(default 1). RaisesDPSNError.unsubscribe(topic: str) -> None: Unsubscribes fromtopic. RaisesDPSNError.disconnect() -> None: Disconnects from the broker. RaisesDPSNError.generate_topic_hash(topic_name: str) -> str: Generates a unique hash for a giventopic_nameusing a nonce and keccak256. (Note: This is currently a utility function and not directly used for publish/subscribe which rely on the wallet address prefix).
Events
Register handlers using decorators (@client.event_name) or addition (client.event_name += handler_func).
on_msg(message_data: Dict): Triggered when a message is received on a subscribed topic.message_datais{'topic': str, 'payload': Any}(payload is decoded JSON if possible, else string).on_error(error: DPSNError): Triggered when an operational error occurs within the client (e.g., message handling failure, connection issue post-init).
Properties
wallet_address: The Ethereum address derived from the provided private key.connected: Boolean indicating the current connection state.
Class DPSNError
Custom exception class for client-specific errors.
code: ADPSN_ERROR_CODESenum member.message: Descriptive error message string.status: Optional connection status hint ('connected' or 'disconnected').
Enum DPSN_ERROR_CODES
Defines specific error types:
CONNECTION_ERROR(400)UNAUTHORIZED(401)PUBLISH_ERROR(402)INITIALIZATION_FAILED(403)CLIENT_NOT_INITIALIZED(404)CLIENT_NOT_CONNECTED(405)SUBSCRIBE_ERROR(406)SUBSCRIBE_NO_GRANT(407) - Currently unusedSUBSCRIBE_SETUP_ERROR(408) - Currently unusedDISCONNECT_ERROR(409)BLOCKCHAIN_CONFIG_ERROR(410) - Currently unusedINVALID_PRIVATE_KEY(411)ETHERS_ERROR(412) - Currently unusedMESSAGE_HANDLING_ERROR(414)
License
MIT License
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file dpsn_client-1.0.0.tar.gz.
File metadata
- Download URL: dpsn_client-1.0.0.tar.gz
- Upload date:
- Size: 10.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d19e4041f476cdeb7d5c1ee4ba880f75d88bd219be4398fcc9b426869c19d598
|
|
| MD5 |
a739c12f3b529c8726e4411ab12f741e
|
|
| BLAKE2b-256 |
9c4096015dbb323edffc0a87ee9d2f90558269c8a4344c3f5ed29c0a32931be0
|
File details
Details for the file dpsn_client-1.0.0-py3-none-any.whl.
File metadata
- Download URL: dpsn_client-1.0.0-py3-none-any.whl
- Upload date:
- Size: 7.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.6
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e75a5a3aba39196fefe6f536b18b0f8a2ed461276c79ff63828b3e1c9c0b57fd
|
|
| MD5 |
814af10b17914f6da87935823b8d76ef
|
|
| BLAKE2b-256 |
734b806d14d1042eb5450d2562ecd7aee141952d539911bd8ef1c9210d4ab610
|