getSignal.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 
3 # Import the ping list
4 from pingList import IP2PING
5 
6 # Import mesages
7 from ros_monitoring.msg import SignalInformation, Info_ping
8 
9 # Other imports
10 from tcppinglib import async_tcpping, models
11 import rospy, asyncio
12 
13 # Get signal class
14 class getSignal:
15  def __init__(self) -> None:
16  # Start the node
17  rospy.init_node('getConnectionStatus', anonymous=False)
18  rospy.loginfo("Get signal topic started")
19  # Creates the publisher of the messages
20  try:
21  self.message_pub = rospy.Publisher("connectionStatus", SignalInformation, queue_size=10)
22  except Exception as e:
23  rospy.logerr("Failure to create publisher")
24  rospy.logerr("An exception occurred:", type(e).__name__,e.args)
25 
26  # Set the asynchronous loop
27  try:
28  self.loop = asyncio.get_event_loop()
29  except:
30  rospy.logerr("Failure to asynchronous loop")
31  rospy.logerr("An exception occurred:", type(e).__name__,e.args)
32 
33  # Create the global lists
34  try:
35  # Copy the list of ips and settings defined in the pingList file
36  self.ip_list = IP2PING.copy()
37  # Creates an empty list to store the messages
38  self.msg_list = []
39  # Create an empty list for asynchronous tasks
40  self.ping_tasks = {}
41  # Add verification keys to the lists of ips and messages
42  for i in range(0,len(self.ip_list)):
43  # Add an ID key in the list of ips and configurations
44  self.ip_list[i].update({'_id': i})
45  # Links the same key to the list of messages
46  self.msg_list.append({'_id': i})
47  rospy.loginfo("Ping to: " + self.ip_list[i]['ip'] + ':' + str(self.ip_list[i]['port']))
48  except:
49  rospy.logerr("Failure to create the global lists")
50  rospy.logerr("An exception occurred:", type(e).__name__,e.args)
51 
52  # Launches the ping_ips task asynchronously
53  try:
54  asyncio.run(self.main())
55  except:
56  rospy.logerr("Error on launch task asynchronously")
57  rospy.logerr("An exception occurred:", type(e).__name__,e.args)
58 
59  # Keeps the node alive
60  rospy.spin()
61 
62 # Function to ping against defined ips
63  async def ping(self, ip_dict: dict):
64  try:
65  # Ping against ip_dict settings asynchronously
66  aping = await async_tcpping(
67  address=ip_dict['ip'],
68  port=ip_dict['port'],
69  timeout=ip_dict['timeout'],
70  count=ip_dict['count'],
71  interval=ip_dict['interval'])
72  # Adds the ROS Info_ping message to the message list for the ip
73  self.msg_list[ip_dict['_id']].update({'msg': self.ping2msg(ping=aping)})
74  except Exception as e:
75  rospy.logerr("Error on ping to " + ip_dict['ip'] + ':' + str(ip_dict['port']))
76  rospy.logerr("An exception occurred:", type(e).__name__,e.args)
77  finally:
78  # Wait one more interval cycle to release finish the function
79  await asyncio.sleep(delay=ip_dict['interval'])
80  # Add to ip_list the dictionary that was removed
81  self.ip_list.append(ip_dict)
82  # Deletes the task from the task list
83  del self.ping_tasks[ip_dict['_id']]
84 
85 # Converts the ping values to the ROS message Info_ping
86  def ping2msg(self, ping: models.TCPHost):
87  try:
88  # Starts the message
89  _msg = Info_ping()
90  # Fill in the message
91  _msg.is_alive = int(ping.is_alive)
92  _msg.packets_sent = int(ping.packets_sent)
93  _msg.packets_loss = int(ping.packet_loss)
94  _msg.packets_received = int(ping.packets_received)
95  _msg.port = ping.port
96  _msg.rtt_max = ping.max_rtt
97  _msg.rtt_min = ping.min_rtt
98  _msg.rtt_avg = ping.avg_rtt
99  _msg.ip_target = ping.ip_address
100  # Returns the converted message
101  return _msg
102  except Exception as e:
103  rospy.logerr("Error on convert ping to message: " + ping.ip_address + ':' + ping.port)
104  rospy.logerr("An exception occurred:", type(e).__name__,e.args)
105 
106 # Publishes the ROS SignalInfomation message to the defined topic via the publisher
107  async def publish(self):
108 
109  # Keeps the loop going as long as ROS coreprint is running
110  while not rospy.is_shutdown():
111  try:
112  # Initiates the SignalInformation message
113  msg = SignalInformation()
114  # Create a list with the informations
115  list_msg = [message['msg'] for message in self.msg_list]
116  # Adds the message list to the ping field in the ROS message
117  msg.list = list_msg
118  except KeyError:
119  await asyncio.sleep(1)
120  continue
121  except Exception as e:
122  rospy.logerr("Error on convert ROS message")
123  rospy.logerr("An exception occurred:", type(e).__name__,e.args)
124 
125  # Publishes the message to the publisher
126  try:
127  self.message_pub.publish(msg)
128  except Exception as e:
129  rospy.logerr("Error on publish the message")
130  rospy.logerr("An exception occurred:", type(e).__name__,e.args)
131  finally:
132  await asyncio.sleep(0.5)
133 
134 # Performs a read of the listed ips
135  async def ping_ips(self):
136  # Keeps the loop going as long as ROS coreprint is running
137  while not rospy.is_shutdown():
138  # For all items of ip_list
139  for item in self.ip_list:
140  try:
141  # If no ping task exists for the _id of item create a task
142  if item['_id'] not in self.ping_tasks:
143  # Create a ping job for the item
144  self.ping_tasks[item['_id']] = asyncio.ensure_future(self.ping(ip_dict=item))
145  # Remove item from ip_list to decrease operations
146  self.ip_list.remove(item)
147  except Exception as e:
148  rospy.logerr("Error create the ping task to " + item['ip'] + ':' + str(item['port']))
149  rospy.logerr("An exception occurred:", type(e).__name__,e.args)
150 
151  # Wait 0.1 s to start a new round of forcing so as not to overload processing
152  await asyncio.sleep(0.1)
153 
154 # Main function
155  async def main(self):
156  # Run the collect function and the publish
157  await asyncio.gather(self.ping_ips(), self.publish())
158 
159 # On program interruption terminates asynchronous tasks
160  def __del__(self):
161  self.loop.stop()
162  rospy.rospy.loginfo("Interrupted asynchronous tasks")
163 
164 if __name__ == '__main__':
165  try:
166  getSignal()
167  except rospy.ROSInterruptException:
168  pass
getSignal.getSignal.__init__
None __init__(self)
Definition: getSignal.py:15
getSignal.getSignal.ping2msg
def ping2msg(self, models.TCPHost ping)
Definition: getSignal.py:86
getSignal.getSignal
Definition: getSignal.py:14
getSignal.getSignal.__del__
def __del__(self)
Definition: getSignal.py:160
getSignal.getSignal.loop
loop
Definition: getSignal.py:28
getSignal.getSignal.ping
def ping(self, dict ip_dict)
Definition: getSignal.py:63
getSignal.getSignal.msg_list
msg_list
Definition: getSignal.py:38
getSignal.getSignal.ping_tasks
ping_tasks
Definition: getSignal.py:40
getSignal.getSignal.main
def main(self)
Definition: getSignal.py:155
getSignal.getSignal.message_pub
message_pub
Definition: getSignal.py:21
getSignal.getSignal.ping_ips
def ping_ips(self)
Definition: getSignal.py:135
getSignal.getSignal.ip_list
ip_list
Definition: getSignal.py:36
getSignal.getSignal.publish
def publish(self)
Definition: getSignal.py:107


cedri_ros_monitoring
Author(s): Andre Luis Frana
autogenerated on Sun Jul 2 2023 02:45:41