diff --git a/README.md b/README.md index fa4f46b..6913946 100644 --- a/README.md +++ b/README.md @@ -26,3 +26,9 @@ source mqttmock/bin/activate pip install -r requirements.txt ``` + +``` +apt install mosquitto-clients + +mosquitto_pub -h localhost -p 1883 -t "device" -m '{"msg": "test""}' +``` diff --git a/client/mqtt_client.py b/client/mqtt_client.py index 2fd94b8..1f1626e 100644 --- a/client/mqtt_client.py +++ b/client/mqtt_client.py @@ -9,11 +9,11 @@ load_dotenv(dotenv_path=".env.test") MQTT_HOST = os.getenv("MQTT_HOST") MQTT_PORT = int(os.getenv("MQTT_PORT")) -MQTT_DEVICE_CODE = int(os.getenv("MQTT_DEVICE_CODE")) +MQTT_DEVICE_CODE = os.getenv("MQTT_DEVICE_CODE") -def on_connect_mock(client, userdata, flags, rc, properties): - print(f"Connected with result code {rc}") +def on_connect_mock(client, userdata, flags, rc): + print(f"Connected with result code rc={rc}") def test_mqtt_mock(): @@ -22,7 +22,26 @@ def test_mqtt_mock(): client = mqtt.Client() client.on_connect = on_connect_mock client.connect(MQTT_HOST, MQTT_PORT, 60) - time.sleep(5) + topic = f"device/{MQTT_DEVICE_CODE}/command" + client.subscribe(topic, qos=1) + client.loop_start() + while True: + try: + print("publish start.") + topic = f"device/{MQTT_DEVICE_CODE}/send" + data = {"message": "test"} + message = json.dumps(data).encode('utf-8') + client.publish(topic, message, qos=1) + time.sleep(30) + except KeyboardInterrupt as e: + time.sleep(30) + break + except Exception as e: + print(f"error:{e}") + time.sleep(30) + + print(f"end") + client.loop_stop() def main():