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


rosbridge_library
Author(s): Jonathan Mace
autogenerated on Thu Aug 27 2015 14:50:35