|
1 | 1 | import logging
|
| 2 | +from socket import gethostname |
2 | 3 |
|
3 | 4 | import paho.mqtt.client as mqtt
|
| 5 | +import paho.mqtt.subscribe as subscribe |
4 | 6 |
|
5 | 7 | from cpopservice import config
|
6 | 8 | from cpopservice.core.models import Serializable
|
@@ -32,9 +34,24 @@ def name():
|
32 | 34 | return 'mqtt'
|
33 | 35 |
|
34 | 36 | def __init__(self):
|
35 |
| - self.client = mqtt.Client() |
36 |
| - self.client.connect(config.BROKER_HOST, config.BROKER_PORT) |
| 37 | + self.client_id = 'cpop-service-%s' % gethostname() |
| 38 | + self.client = mqtt.Client(client_id=self.client_id) |
| 39 | + self.client.connect(config.BROKER_HOST, config.BROKER_PORT, keepalive=30) |
37 | 40 |
|
38 | 41 | def publish_event(self, event: Serializable):
|
39 | 42 | LOG.debug('publishing message to topic %s: %s', config.MQTT_TOPIC_NAME, event)
|
40 | 43 | self.client.publish(config.MQTT_TOPIC_NAME, event.to_bson())
|
| 44 | + |
| 45 | + |
| 46 | +class CPOPSubscriberMQTT: |
| 47 | + |
| 48 | + def __init__(self, callback=None): |
| 49 | + self.callback = callback |
| 50 | + pass |
| 51 | + |
| 52 | + def listen(self): |
| 53 | + subscribe.callback(self.on_message, config.MQTT_TOPIC_NAME, hostname=config.BROKER_HOST, |
| 54 | + port=config.BROKER_PORT) |
| 55 | + |
| 56 | + def on_message(self, client, userdata, message): |
| 57 | + print(message) |
0 commit comments