-
Notifications
You must be signed in to change notification settings - Fork 1
/
mqtt_cli.py
53 lines (43 loc) · 1.91 KB
/
mqtt_cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import click
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
@click.command()
@click.option('--host', default='hackgt.danrowe.com',
help='The mqtt broker to connect to.')
@click.option('--port', default=1883,
help='The mqtt broker port to connect to.')
@click.option('--topic', default='cmnd/hackgt/chat',
help='The mqtt topic to send/receive on.')
@click.option('--username', default='hackgt',
help='The mqtt username.')
@click.option('--password', default='letmein',
help='The mqtt password.')
@click.option('--message',
help='If message is passed, sends message instead of listening')
def mqtt_cli(host, port, topic, message, username, password):
"""Simple MQTT CLI tool for sending and receiving MQTT Messages."""
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(username, password=password)
client.connect(host, port, 60)
print('Connecting to %s:%s' % (host, port))
if message:
click.echo('Sending to Topic: %s' % topic)
click.echo('Message Sent: %s' % message)
client.publish(topic, message) # publish
else:
click.echo('Listening on Topic: %s' % topic)
# Subscribing outside of on_connect() means that if we lose the
# connection and reconnect then subscriptions won't be renewed.
client.subscribe(topic)
# Blocking call that processes network traffic, dispatches
# callbacks and handles reconnecting.
client.loop_forever()
if __name__ == '__main__':
mqtt_cli()