app.py
Go to the documentation of this file.
1 import inject
2 import paho.mqtt.client as mqtt
3 import rospy
4 
5 from .bridge import create_bridge
6 from .mqtt_client import create_private_path_extractor
7 from .util import lookup_object
8 
9 
10 def create_config(mqtt_client, serializer, deserializer, mqtt_private_path):
11  if isinstance(serializer, str):
12  serializer = lookup_object(serializer)
13  if isinstance(deserializer, str):
14  deserializer = lookup_object(deserializer)
15  private_path_extractor = create_private_path_extractor(mqtt_private_path)
16  def config(binder):
17  binder.bind('serializer', serializer)
18  binder.bind('deserializer', deserializer)
19  binder.bind(mqtt.Client, mqtt_client)
20  binder.bind('mqtt_private_path_extractor', private_path_extractor)
21  return config
22 
23 
25  # init node
26  rospy.init_node('mqtt_bridge_node')
27 
28  # load parameters
29  params = rospy.get_param("~", {})
30  mqtt_params = params.pop("mqtt", {})
31  conn_params = mqtt_params.pop("connection")
32  mqtt_private_path = mqtt_params.pop("private_path", "")
33  bridge_params = params.get("bridge", [])
34 
35  # create mqtt client
36  mqtt_client_factory_name = rospy.get_param(
37  "~mqtt_client_factory", ".mqtt_client:default_mqtt_client_factory")
38  mqtt_client_factory = lookup_object(mqtt_client_factory_name)
39  mqtt_client = mqtt_client_factory(mqtt_params)
40 
41  # load serializer and deserializer
42  serializer = params.get('serializer', 'msgpack:dumps')
43  deserializer = params.get('deserializer', 'msgpack:loads')
44 
45  # dependency injection
46  config = create_config(
47  mqtt_client, serializer, deserializer, mqtt_private_path)
48  inject.configure(config)
49 
50  # configure and connect to MQTT broker
51  mqtt_client.on_connect = _on_connect
52  mqtt_client.on_disconnect = _on_disconnect
53  mqtt_client.connect(**conn_params)
54 
55  # configure bridges
56  bridges = []
57  for bridge_args in bridge_params:
58  bridges.append(create_bridge(**bridge_args))
59 
60  # start MQTT loop
61  mqtt_client.loop_start()
62 
63  # register shutdown callback and spin
64  rospy.on_shutdown(mqtt_client.disconnect)
65  rospy.on_shutdown(mqtt_client.loop_stop)
66  rospy.spin()
67 
68 
69 def _on_connect(client, userdata, flags, response_code):
70  rospy.loginfo('MQTT connected')
71 
72 
73 def _on_disconnect(client, userdata, response_code):
74  rospy.loginfo('MQTT disconnected')
75 
76 
77 __all__ = ['mqtt_bridge_node']
def mqtt_bridge_node()
Definition: app.py:24
def create_config(mqtt_client, serializer, deserializer, mqtt_private_path)
Definition: app.py:10
def _on_disconnect(client, userdata, response_code)
Definition: app.py:73
def _on_connect(client, userdata, flags, response_code)
Definition: app.py:69
def lookup_object
Definition: util.py:7


mqtt_bridge
Author(s): Junya Hayashi
autogenerated on Mon Feb 15 2021 03:57:51