Metadata-Version: 2.5
Name: connectmq
Version: 1.0.0
Summary: Publish and subscribe on the free public MQTT broker broker.connectmq.com in one line. Preconfigured paho-mqtt client and CLI for TCP, TLS, WebSocket and secure WebSocket.
Project-URL: Homepage, https://connectmq.com
Project-URL: Documentation, https://connectmq.com/blog/free-public-mqtt-broker
Author: ConnectMQ Team
License-Expression: MIT
License-File: LICENSE
Keywords: connectmq,free-mqtt-broker,iot,mqtt,mqtt-broker,mqtt-client,paho-mqtt,public-mqtt-broker,pubsub
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Communications
Classifier: Topic :: Internet
Classifier: Topic :: System :: Networking
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: paho-mqtt<3,>=2.0
Description-Content-Type: text/markdown

# connectmq

Publish and subscribe on the free public MQTT broker **broker.connectmq.com** in one line, with no account needed.
The package is a preconfigured [paho-mqtt](https://pypi.org/project/paho-mqtt/) client and CLI for TCP, TLS, WebSocket and secure WebSocket.
It also works with private brokers created on [connectmq.com](https://connectmq.com).

```bash
pip install connectmq
connectmq test
# OK  mqtts://broker.connectmq.com:8883  connect 220 ms, round-trip 46 ms
```

Requires Python 3.9 or later.

## Quick start

```python
import connectmq

prefix = connectmq.topic_prefix()  # e.g. "connectmq/demo/7f3a91"

# Publish (dicts and lists are sent as JSON)
connectmq.publish(f"{prefix}/temperature", {"value": 21.5}, retain=True)

# Subscribe: iterate over incoming messages
for msg in connectmq.subscribe(f"{prefix}/#", count=1, timeout=10):
    print(msg.topic, msg.json())
```

The public area is shared, so use a random prefix to keep your topics apart from other testers.

## Reuse one connection

```python
import connectmq

with connectmq.Client(transport="tls") as client:
    # Callback style: returns a function that unsubscribes
    stop = client.subscribe("connectmq/demo/7f3a91/#", lambda m: print(m.topic, m.payload))

    for i in range(10):
        client.publish("connectmq/demo/7f3a91/counter", i, qos=1)

    reply = client.once("connectmq/demo/7f3a91/reply", timeout=5)  # raises TimeoutError
    stop()
```

## API

| Function | Description |
|---|---|
| `publish(topic, payload, qos=0, retain=False, **options)` | Publish one message with a short-lived connection |
| `subscribe(topics, qos=0, count=0, timeout=None, **options)` | Iterator over messages; stops after `count` messages or `timeout` seconds of silence |
| `once(topic, timeout=30, **options)` | Next message on a topic filter; raises `TimeoutError` |
| `connect(**options)` / `Client(**options)` | Connected client; use as a context manager |
| `test(transport="tls", **options)` | Connects, publishes, receives; returns `TestResult(ok, url, connect_ms, round_trip_ms, error)` |
| `broker_info()` | Endpoints and limits of the public broker |
| `topic_prefix(root="connectmq/demo")` | Random topic prefix |
| `broker_url(transport, host, port)` | URL for `tcp`, `tls`, `ws` or `wss` |
| `topic_matches(filter, topic)` | Wildcard matching for `+`, `#` and `$share/...` |

`Client` methods: `publish()`, `subscribe(topics, callback, qos)`, `messages(topics, qos, count, timeout)`, `once()` and `close()`.
The underlying paho client is available as `client.mqtt`.

Callbacks are registered before the broker acknowledges a subscription, so retained messages are never missed.

`Message` has `topic`, `payload` (UTF-8 string), `raw` (bytes), `qos`, `retain`, `received` (datetime) and `json()`.

### Options

| Option | Default | Notes |
|---|---|---|
| `transport` | `"tls"` | `tcp` 1883, `tls` 8883, `ws` 8083, `wss` 8084 (`/mqtt`) |
| `host` | `"broker.connectmq.com"` | Any MQTT broker |
| `port` | Standard port | |
| `client_id` | `py-` plus a random suffix | Must be unique and non-empty |
| `username`, `password` | `None` | Not needed on the public broker |
| `protocol` | `5` | `5` for MQTT 5.0, `4` for MQTT 3.1.1 |
| `keepalive`, `timeout` | `60`, `10.0` | Seconds |

## Examples

**Send sensor readings**

```python
import random, time, connectmq

with connectmq.Client() as client:
    while True:
        client.publish("connectmq/demo/7f3a91/sensor", {"temperature": round(random.uniform(20, 25), 1)})
        time.sleep(5)
```

**Log messages to CSV**

```python
import csv, connectmq

with open("mqtt-log.csv", "a", newline="") as f:
    writer = csv.writer(f)
    for msg in connectmq.subscribe("connectmq/demo/7f3a91/#"):
        writer.writerow([msg.received.isoformat(), msg.topic, msg.payload])
```

**Private ConnectMQ broker**

```python
import os, connectmq

client = connectmq.connect(
    host="YOUR_BROKER_HOST",
    transport="tls",
    username=os.environ["MQTT_USERNAME"],
    password=os.environ["MQTT_PASSWORD"],
)
```

## CLI

```bash
connectmq test                                  # connectivity and round-trip
connectmq info                                  # endpoints and limits
connectmq prefix                                # random topic prefix
connectmq sub "connectmq/demo/7f3a91/#"
connectmq pub connectmq/demo/7f3a91/temp '{"value":21.5}' -q 1 -r
echo hello | connectmq pub connectmq/demo/7f3a91/msg
python -m connectmq test                        # if the script folder is not on PATH
```

| Option | Description |
|---|---|
| `-t, --transport` | `tcp`, `tls` (default), `ws`, `wss` |
| `-H, --host`, `-P, --port` | Broker host and port |
| `-q, --qos` | 0, 1 or 2 |
| `-r, --retain` | Retained message (`pub`) |
| `-n, --count` | Exit after n messages (`sub`) |
| `-j, --json` | JSON line output (`sub`) |
| `-u, --username`, `-p, --password` | Credentials for private brokers |

## Public broker

| Protocol | URL |
|---|---|
| MQTT (TCP) | `mqtt://broker.connectmq.com:1883` |
| MQTT over TLS | `mqtts://broker.connectmq.com:8883` |
| WebSocket | `ws://broker.connectmq.com:8083/mqtt` |
| Secure WebSocket | `wss://broker.connectmq.com:8084/mqtt` |

Access is anonymous, but the client ID must not be empty. Limits: 64 KB per message, 10 messages per second and 10 subscriptions per client, topics up to 8 levels deep, and sessions expire after at most 30 minutes.

> **Everything on the public broker is public.** Any client can subscribe to `#`.
> Use the broker only for testing, and always under a random topic prefix.
> For production, create a private broker with its own credentials at [connectmq.com](https://connectmq.com).

More: [Free Public MQTT Broker for Testing](https://connectmq.com/blog/free-public-mqtt-broker).
Also available for Node.js (`@connectmq/mqtt`), .NET (`ConnectMQ.Mqtt`), Node-RED (`node-red-contrib-connectmq`) and PowerShell (`MQTTBroker`).

## License

MIT
