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


rosbridge_library
Author(s): Jonathan Mace
autogenerated on Mon Oct 6 2014 06:58:09