def main(): configure_logger() logging.info('Daemon started.') time.sleep(3) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((HOST, PORT)) sock.listen(0) logging.info('Listening on tcp://{}:{}'.format(HOST, PORT)) try: next_id = 0 while True: conn, addr = sock.accept() logging.info('Connection from {}'.format(addr)) try: # Read only one request req = read(conn.recv) req['id'] = next_id next_id += 1 send(req) resp = read() send(resp, conn.sendall) finally: conn.close() finally: sock.close() logging.info('Daemon exitting gracefully.')
def send_to_key_server(message): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((common.HOST, common.SERVER_PORT)) common.send(s, message) rec = common.receive(s) s.close() return rec
def history_order(socket): request = order_pb2.History_Order_Request() common.send(socket, common_pb2.HISTORY_ORDER, request) (protocol, data) = common.get(socket) response = order_pb2.History_Order_Response() response.ParseFromString(data) print(response)
def logout(socket): request = washer_pb2.Logout_Request() common.send(socket, common_pb2.LOGOUT, request) (_, body) = common.get(socket) if body: response = washer_pb2.Logout_Response() response.ParseFromString(body) print(response)
def order_detail(socket): request = order_pb2.Order_Detail_Request() request.order_id = "58bfabef7f439e2303a20426" common.send(socket, common_pb2.ORDER_DETAIL, request) (protocol, data) = common.get(socket) response = order_pb2.Order_Detail_Response() response.ParseFromString(data) print(response)
def cancel_order(socket): request = order_pb2.Cancel_Order_Request() request.order_id = "58bfad717f439e23288ac4e2" common.send(socket, common_pb2.CANCEL_ORDER, request) (protocol, data) = common.get(socket) response = order_pb2.Cancel_Order_Response() response.ParseFromString(data) print(response)
def stop_work(socket): request = washer_pb2.Stop_Work_Request() common.send(socket, common_pb2.STOP_WORK, request) body = common.get(socket) if body: (protocol, data) = body response = washer_pb2.Stop_Work_Response() response.ParseFromString(data) print(response)
def onData(imgMsg): img = bridge.imgmsg_to_cv2(imgMsg, 'bgr8') img = cv.resize(img, (640, 480)) jpgImg = cv.imencode('.jpg', img)[1] data = np.array(jpgImg) send(s, dataInfo, data, 'array') dataInfo['sequence'] += 1 dataInfo['timestamp'] += 1
def order_feedback(socket): print("protocol: order_feedback") request = order_pb2.Order_Feedback_Request() request.order_id = "58bfabef7f439e2303a20426" request.score = 5 common.send(socket, common_pb2.ORDER_FEEDBACK, request) (protocol, data) = common.get(socket) response = order_pb2.Order_Feedback_Response() response.ParseFromString(data) print(response)
def main(): req = json.load(sys.stdin) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((HOST, PORT)) send(req, sock.sendall) resp = read(sock.recv) print(json.dumps(resp, indent=4))
def get_near_washer(socket): pb = washer_pb2.Near_Washer_Request() pb.city_code = 179 pb.longitude = 120.21937542 pb.latitude = 30.25924446 common.send(socket, washer_pb2.NEAR_WASHER, pb) body = common.get(socket) if body: resp = washer_pb2.Near_Washer_Response() resp.ParseFromString(body) print(resp)
def request_authcode(socket): requestAuthcode = washer_pb2.Request_Authcode_Request() requestAuthcode.phone = WASHER_PHONE requestAuthcode.signature = 'signature' common.send(socket, common_pb2.REQUEST_AUTHCODE, requestAuthcode) (protocol, body) = common.get(socket) if body: raResponse = washer_pb2.Request_Authcode_Response() raResponse.ParseFromString(body) print('request_authcode response:{!r}'.format(raResponse)) return raResponse.authcode return False
def insidethenout(): zero() for i in range(4): j = (i + 1) * 2 k = 3 - i for z in range(j): for y in range(j): for x in range(j): common.grid(x + k, y + k, z + k, 1) common.send() shifty.execute() if i != 4: zero()
def outsidethenin(): fill() for i in range(5): j = (4 - i) * 2 k = i for z in range(j): for y in range(j): for x in range(j): common.grid(x + k, y + k, z + k, 1) common.send() shifty.execute() if i != 4: zero()
def fillfrombottom(): maxz = 0 for x in range(8): for y in range(8): for z in range(8): if common.gridfindstate(x, y, z) == 1: maxz = z for z2 in range(8): if z2 < maxz: common.grid(x, y, z2, 1) maxz = 0 common.send() shifty.execute()
def fresh_location(socket): pb = washer_pb2.Fresh_Location_Request() pb.longitude = 120.21937542 pb.latitude = 30.25924446 pb.city_code = 179 common.send(socket, common_pb2.FRESH_LOCATION, pb) (protocol, body) = common.get(socket) if body: resp = washer_pb2.Fresh_Location_Response() resp.ParseFromString(body) print('fresh_location result:') print(resp.error_code)
def layerbylayer(): for z in range(8): for y in range(8): for x in range(8): common.grid(x, y, z, 1) common.send() # Has a sleep within it shifty.execute() time.sleep(1) for j in range(8): for i in range(8): common.grid(j, i, z, 0) common.send() shifty.execute() time.sleep()
def main(): socket = connect() if not common.__dict__.has_key(sys.argv[1]): raise Exception("Invalid request type") req_type = common.__dict__[sys.argv[1]] args = [] for pair in sys.argv[2:]: pair_parts = pair.split(':', 1) if len(pair_parts) == 1 or pair_parts[0] == 's': args.append(pair_parts[-1]) elif pair_parts[0] == 'i': args.append(int(pair_parts[1])) send(socket, req_type, *args) resp = recv_all(socket) print resp print "PAYLOAD SIZE: %d" % (len(resp['payload']),)
def staysame(self): z = self.currentfreq for x in range(8): for y in range(8): common.grid(x, y, z, 1) common.send() shifty.execute() for x in range(8): for y in range(8): common.grid(x, y, z, 0) common.send() shifty.execute()
def login(socket): washer = washer_pb2.Login_Request() washer.phone = WASHER_PHONE washer.password = '******' washer.signature = 'signature' #washer.city_code = 179 #washer.longitude = 120.025806 #washer.latitude = 30.246185 common.send(socket, common_pb2.LOGIN, washer) (protocol, body) = common.get(socket) if body: washerResponse = washer_pb2.Login_Response() washerResponse.ParseFromString(body) print(washerResponse) return True print('login failure')
def onVSlamData(msg): # get json data jsonData = {'observers': {}, 'marks': []} jsonData['observer'] = { 'id': msg.key_frame.key_frame_id, 'location': { 'x': msg.key_frame.camera_pose.position.x, 'y': msg.key_frame.camera_pose.position.y, 'z': msg.key_frame.camera_pose.position.z }, 'orientation': { 'x': msg.key_frame.camera_pose.orientation.x, 'y': msg.key_frame.camera_pose.orientation.y, 'z': msg.key_frame.camera_pose.orientation.z, 'w': msg.key_frame.camera_pose.orientation.w } } # for data in msg.key_frame: # jsonData['observers'].append({ # 'location': { # 'x': data.camera_pose.position.x, # 'y': data.camera_pose.position.y, # 'z': data.camera_pose.position.z # }, # 'orientation': { # 'x': data.camera_pose.orientation.x, # 'y': data.camera_pose.orientation.y, # 'z': data.camera_pose.orientation.z, # 'w': data.camera_pose.orientation.w # } # }) for data in msg.map_points: jsonData['marks'].append({ 'id': data.card_id, 'code': data.code_id, 'current': data.current, 'location': { 'x': data.card_pose.position.x, 'y': data.card_pose.position.y, 'z': data.card_pose.position.z } }) send(s, dataInfo, json.dumps(jsonData), 'string') dataInfo['sequence'] += 1 dataInfo['timestamp'] += 1
def fillfromtop(): for x in range(8): x = 7 - x for y in range(8): minz = 7 y = 7 - y for z in range(8): z = 7 - z if common.gridfindstate(x, y, z) == 1: minz = z for z2 in range(8): z2 = 7 - z2 if z2 > minz: common.grid(x, y, z2, 1) minz = 0 common.send() shifty.execute()
def outsidetheninhollow(): zero() for i in range(5): j = (4 - i) * 2 pastj = j - 2 k = i pastk = k + 1 for z in range(j): for y in range(j): for x in range(j): common.grid(x + k, y + k, z + k, 1) for z in range(pastj): for y in range(pastj): for x in range(pastj): common.grid(x + pastk, y + pastk, z + pastk, 0) common.send() shifty.execute() zero()
def send_changes(self, line_no, action, payload=''): '''Send changes in local file to the server :param line_no: int, Line number to be changed (line numbers start from 0) :param action: int, Editing control code (valid values: common.EDIT_REPLACE, common.EDIT_INSERT, common.EDIT_DELETE) :param payload: string, Value for the line (ignored if `action' is set to common.EDIT_DELETE) :return: True, if the request was successfully sent False, otherwise The file and client ID relevant to this request are defined in instance variables `self.id' and `self.fn' ''' if self.id is None: logging.error( "Yo, what's up! You have no ID and should request one " "from the server before initiating the session (use: req_id())" ) return False if self.fn is None: logging.error( "You haven't requested any files from the server. SMH") return False msg = common.marshall(line_no, action, payload, self.id) try: logging.debug("Send the changes made in file '%s' to the server" % self.fn) common.send(self.sock, msg) except socket.timeout as err: logging.debug('Socket timeout error: %s' % err) return False except socket.error as err: logging.debug('Socket error: %s' % err) return False except struct.error as err: logging.debug('Struct un/packing error: %s' % err) return False except RuntimeError as err: logging.debug('Runtime error: %s' % err) return False except KeyboardInterrupt: logging.debug('Caught SIGINT') return False except BaseException as err: logging.debug('Unknown error: %s' % err) return False return True
def register(socket): authcode = verify_authcode(socket) if not authcode: return pb = washer_pb2.Register_Request() pb.phone = WASHER_PHONE pb.authcode = authcode pb.password = '******' pb.password2 = 'iwasher' pb.nick = 'iwasher' pb.signature = 'signature' pb.type = common_pb2.PERSONAL common.send(socket, common_pb2.REGISTER, pb) (protocol, body) = common.get(socket) if body: res = washer_pb2.Register_Response() res.ParseFromString(body) print(res) print('finish register')
def verify_authcode(socket): authcode = request_authcode(socket) if not authcode: print('get request authcode failure..') return verifyAuthcode = washer_pb2.Verify_Authcode_Request() verifyAuthcode.phone = WASHER_PHONE verifyAuthcode.authcode = authcode verifyAuthcode.signature = 'signature' common.send(socket, common_pb2.VERIFY_AUTHCODE, verifyAuthcode) (protocol, body) = common.get(socket) if body: va = washer_pb2.Verify_Authcode_Response() va.ParseFromString(body) if va.error_code == common_pb2.SUCCESS: print("verify authcode success:%s" % va.error_code) return authcode print('verify authcode failure') return False
def start_work(socket): result = login(socket) if result is None: print('login first') return request = washer_pb2.Start_Work_Request() request.city_code = 179 request.longitude = 120.025806 request.latitude = 30.246185 common.send(socket, common_pb2.START_WORK, request) print("start work, protocol:{}".format(common_pb2.START_WORK)) while True: body = common.get(socket) if not body: break else: (protocol, data) = body if protocol == common_pb2.START_WORK: print("protocol: start_work") response = washer_pb2.Start_Work_Response() response.ParseFromString(data) print(response) print("protocol: fresh_location") request = washer_pb2.Fresh_Location_Request() request.city_code = 179 request.longitude = 120.025806 request.latitude = 30.246185 common.send(socket, common_pb2.FRESH_LOCATION, request) break elif protocol == common_pb2.ALLOCATE_ORDER: print("protocol: allocate_order") response = order_pb2.Allocate_Order_Push() response.ParseFromString(data) print(response) print("protocol: processing_order") request = order_pb2.Processing_Order_Request() request.order_id = response.order_id common.send(socket, common_pb2.PROCESSING_ORDER, request) print("protocol: finish_order") request = order_pb2.Finish_Order_Request() request.order_id = response.order_id common.send(socket, common_pb2.FINISH_ORDER, request) elif protocol == common_pb2.FINISH_ORDER: print("protocol: finish_order") response = order_pb2.Finish_Order_Response() response.ParseFromString(data) print(response)
def insidethenouthollow(): zero() for i in range(4): j = (i + 1) * 2 pastj = j - 2 k = 3 - i pastk = k + 1 for z in range(j): for y in range(j): for x in range(j): common.grid(x + k, y + k, z + k, 1) for z in range(pastj): for y in range(pastj): for x in range(pastj): common.grid(x + pastk, y + pastk, z + pastk, 0) common.send() shifty.execute() if i != 3: zero()
def onGMapData(msg): jsonData = { 'gmap': { 'info': { 'resolution': msg.info.resolution, 'width': msg.info.width, 'height': msg.info.height, 'location': { 'x': msg.info.origin.position.x, 'y': msg.info.origin.position.y, 'z': msg.info.origin.position.z } }, 'data': msg.data } } send(s, dataInfo, json.dumps(jsonData), 'string') dataInfo['sequence'] += 1 dataInfo['timestamp'] += 1
def lowtohigh(self): z = self.currentfreq for i in range(6): j = (i + 1) * 2 pastj = j - 2 pasterj = j - 4 k = 3 - i pastk = k + 1 pasterk = k + 2 # Turn on the inside circle of a layer if j > 10: for x in range(8): for y in range(8): common.grid(x, y, z + 1, 0) elif j > 8: for x in range(8): for y in range(8): common.grid(x + k, y + k, z, 0) common.grid(x + k, y + k, z + 1, 1) else: for x in range(j): for y in range(j): common.grid(x + k, y + k, z, 1) common.grid(x + k, y + k, z + 1, 0) # Turn off the past inside ring and turn on ring layer of the lower layer if j < 10: for x in range(pastj): for y in range(pastj): common.grid(x + pastk, y + pastk, z, 0) common.grid(x + pastk, y + pastk, z + 1, 1) if pasterj >= 0: for x in range(pasterj): for y in range(pasterj): common.grid(x + pasterk, y + pasterk, z + 1, 0) common.send() shifty.execute()
def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((common.HOST, common.SERVER_PORT)) s.listen() print("KeyServer started") dictionary = {} while True: clientsocket, address = s.accept() request = common.receive(clientsocket) if request["type"] == 1: port = request["port"] public_key = request["public_key"] dictionary[port] = public_key print("Client registred: ", port, public_key) common.send(clientsocket, {"status": "ok"}) else: port = request["port"] if port in dictionary: common.send(clientsocket, { "status": "ok", "public_key": dictionary[port] }) print("Request for", port, "-> ok, public key:", dictionary[port]) else: common.send(clientsocket, {"status": "not found"}) print("Request for", port, "-> not found") clientsocket.close()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import socket from time import sleep from common import send import config if '__main__' == __name__: conn = ('localhost', 6969) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind(conn) server.listen(1) print("Waiting client") (client, address) = server.accept() config.serverside_login(client, config.hello) while True: msg = config.heartbeat_msg print("Sending: " + msg) send(client, msg) sleep(config.heartbeat_interval)