test_non-ros_service_client_complex-srv.py
Go to the documentation of this file.
00001 #!/usr/bin/python
00002 from __future__ import print_function
00003 import socket
00004 from rosbridge_library.util import json
00005 
00006 
00007 
00008 ####################### variables begin ########################################
00009 # these parameters should be changed to match the actual environment           #
00010 ################################################################################
00011 
00012 client_socket_timeout = 6                       # seconds
00013 max_msg_length = 2000000                        # bytes
00014 
00015 rosbridge_ip = "localhost"                      # hostname or ip
00016 rosbridge_port = 9090                           # port as integer
00017 
00018 service_name = "nested_srv"                     # service name
00019 #request_byte_count = 5000
00020 receiving_fragment_size = 1000
00021 receive_message_intervall = 0.0
00022 
00023 ####################### variables end ##########################################
00024 
00025 
00026 ################################################################################
00027 
00028 def request_service():
00029     service_request_object = { "op" : "call_service",                           # op-code for rosbridge
00030                                "service": "/"+service_name,                     # select service
00031                                "fragment_size": receiving_fragment_size,        # optional: tells rosbridge to send fragments if message size is bigger than requested
00032                                "message_intervall": receive_message_intervall,
00033                                "args": { "pose": {"position": {"y": 0.0, "x": 0.0, "z": 0.0}, "orientation": {"y": 0.0, "x": 0.0, "z": 0.0, "w": 0.0}}}
00034                                         #"count" : request_byte_count           # count is the parameter for send_bytes as defined in srv-file (always put into args field!)
00035                               }
00036     service_request = json.dumps(service_request_object)
00037     print("sending JSON-message to rosbridge:", service_request)
00038     sock.send(service_request)
00039 
00040 ################################################################################
00041 
00042 
00043 ####################### script begin ###########################################
00044 # should not need to be changed (but could be improved ;) )                    #
00045 ################################################################################
00046 try:
00047     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)                    #connect to rosbridge
00048     sock.settimeout(client_socket_timeout)
00049     sock.connect((rosbridge_ip, rosbridge_port))
00050 
00051     request_service()                                                           # send service_request
00052 
00053     incoming = None
00054     buffer = ""
00055     done = False
00056     result = None
00057     reconstructed = None
00058     while not done:     # should not need a loop (maximum wait can be set by client_socket_timeout), but since its for test/demonstration only .. leave it as it is for now
00059         try:
00060             incoming = sock.recv(max_msg_length)                                # receive service_response from rosbridge
00061             if buffer == "":
00062                 buffer = incoming
00063                 if incoming == "":
00064                     print("closing socket")
00065                     sock.close()
00066                     break
00067             else:
00068                 buffer = buffer + incoming
00069             #print "buffer-length:", len(buffer)
00070             try:                                                                # try to access service_request directly (not fragmented)
00071                 data_object = json.loads(buffer)
00072                 if data_object["op"] == "service_response":
00073                     reconstructed = buffer
00074                     done = True
00075             except Exception as e:
00076                 #print "direct access to JSON failed.."
00077                 #print e
00078                 pass
00079             try:                                        
00080                 #print "defragmenting incoming messages"
00081                 result_string = buffer.split("}{")                              # split buffer into fragments and re-fill curly brackets
00082                 result = []
00083                 for fragment in result_string:
00084                     if fragment[0] != "{":
00085                         fragment = "{"+fragment
00086                     if fragment[len(fragment)-1] != "}":
00087                         fragment = fragment + "}"
00088                     try:
00089                         result.append(json.loads(fragment))                     # try to parse json from string, and append if successful
00090                     except Exception as e:
00091                         #print e
00092                         #print result_string
00093                         raise                                                   # re-raise the last exception, allows to see and continue with processing of exception
00094 
00095                 fragment_count = len(result)
00096                 print("fragment_count:", fragment_count)
00097                 announced = int(result[0]["total"])
00098                 if fragment_count == announced:                                 # if all fragments received --> sort and defragment
00099                     # sort fragments
00100                     sorted_result = [None] * fragment_count
00101                     unsorted_result = []
00102                     for fragment in result:
00103                         unsorted_result.append(fragment)
00104                         sorted_result[int(fragment["num"])] = fragment
00105                     reconstructed = ''
00106                     for fragment in sorted_result:
00107                         reconstructed = reconstructed + fragment["data"]
00108                     done = True
00109             except Exception as e:
00110                 #print e
00111                 pass
00112         except Exception as e:
00113 #            print e
00114             pass
00115 
00116 
00117     returned_data = json.loads(reconstructed)                                   # when service response is received --> access it (as defined in srv-file)
00118     if returned_data["values"] == None:
00119         print("response was None -> service was not available")
00120     else:
00121         print("received:")
00122         print(returned_data)#["values"]#["data"].decode('base64','strict')         # decode values-field
00123     
00124 except Exception as e:
00125     print("ERROR - could not receive service_response")
00126     print(e)
00127 
00128 sock.close()                                                                    # close socket


rosbridge_library
Author(s): Jonathan Mace
autogenerated on Thu Jun 6 2019 21:51:43