add callback for service response

This commit is contained in:
Sem van der Hoeven
2023-05-30 13:04:52 +02:00
parent 5843575649
commit bc1bc0dae6

View File

@@ -10,6 +10,7 @@ import websockets.server
import threading import threading
import json import json
from enum import Enum from enum import Enum
from functools import partial
# communication: client always sends commands that have a command id. # communication: client always sends commands that have a command id.
# server always sends messages back that have a message type # server always sends messages back that have a message type
@@ -120,15 +121,23 @@ class ApiListener(Node):
self.get_logger().info( self.get_logger().info(
f'Filename: {message_json["filename"]}') f'Filename: {message_json["filename"]}')
self.take_picture_request.input_name = message_json['filename'] self.take_picture_request.input_name = message_json['filename']
self.future = self.take_picture_client.call_async(self.take_picture_request) self.get_logger().info('Calling take picture service')
rclpy.spin_until_future_complete(self, self.future) future = self.take_picture_client.call_async(self.take_picture_request)
result_filename = self.future.result() future.add_done_callback(partial(self.image_request_callback))
self.get_logger().info("Received result filename: " + result_filename)
with open(result_filename, 'rb') as f:
self.get_logger().info('Reading image') def image_request_callback(self, future):
image_data = f.read() try:
self.message_queue.append(json.dumps( result_filename = future.result()
{'type': ResponseMessage.IMAGE.name, 'image': image_data})) self.get_logger().info("Received result filename: " + result_filename)
with open(result_filename, 'rb') as f:
self.get_logger().info('Reading image')
image_data = f.read()
self.message_queue.append(json.dumps(
{'type': ResponseMessage.IMAGE.name, 'image': image_data}))
except Exception as e:
self.get_logger().error('Something went wrong while sending a take picture request and waiting for the response: %r' % (e))
def send_available_commands(self): def send_available_commands(self):
print('Sending available commands') print('Sending available commands')
@@ -228,7 +237,7 @@ class ApiListener(Node):
self.get_logger().error('Received unknown command ' + str(message_json['command']) ) self.get_logger().error('Received unknown command ' + str(message_json['command']) )
self.send_available_commands() self.send_available_commands()
except TypeError: except TypeError:
self.get_logger().error('Received unknown type') self.get_logger().error('Received unknown type: ' +str(type(message)) + " " + str(message))
self.send_available_commands() self.send_available_commands()
except json.JSONDecodeError: except json.JSONDecodeError:
self.get_logger().error('Received invalid JSON') self.get_logger().error('Received invalid JSON')