def __init__(self, address, port): self.address = address self.port = port self.seq = 0 self.session_id = random.randint(0, sys.maxint) self.socket = SocketClient(self.address, self.port) self.status = CubeStatus.UNKNOW
def __init__(self, HOST, PORT, music): super().__init__() self.username = str() self._run = True self._s = SocketClient(HOST, PORT) self._s.set_irc(self) self.music = music
def test_mock_500(self, set_up_mock_500): client = SocketClient(port=settings.APP_PORT, host=settings.APP_HOST) wait_until(client.connect) data, headers = self.get_info(sort='Apple') response = client.request(method='POST', headers=headers, url='/setnew', data=data) assert response[-1] == 'Server internal error'
def __init__(self): self.video_stream = VideoStream( src=0, usePiCamera=True, resolution=(640, 480), framerate=32).start() self.fire_cascade = cv2.CascadeClassifier('fire_detection.xml') self.host = '192.168.1.223' self.port = 8486 time.sleep(2.0) self.timeCheck = time.time() self.socket_client = SocketClient()
class Detector(object): def __init__(self): # self.video_stream = VideoStream( # src=0, usePiCamera=True, width=640, height=480, framerate=32) self.video_stream = cv2.VideoCapture(0) self.video_stream.set(cv2.CAP_PROP_FRAME_WIDTH, 640) self.video_stream.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) self.fire_cascade = cv2.CascadeClassifier('fire_detection.xml') self.host = '192.168.43.52' self.port = 24485 time.sleep(2) self.timeCheck = time.time() self.socket_client = SocketClient() print("init success...") def start(self): self.socket_client.connect(self.host, self.port) print('Connected...') while True: # Get the next frame. success, frame = self.video_stream.read() if not success: break # Show video stream #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #fire = self.fire_cascade.detectMultiScale(frame, 1.2, 5) #for (x, y, w, h) in fire: # cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2) # font = cv2.FONT_HERSHEY_SIMPLEX # roi_gray = gray[y:y+h, x:x+w] # roi_color = frame[y:y+h, x:x+w] # time.sleep(0.2) # print('Detected') # cv2.imwrite('sector2.png', frame) # self.send_frame(frame) #cv2.imshow('out', frame) self.send_frame(frame) key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop. if key == ord("q"): break self.timeCheck = time.time() self.stop() def send_frame(self, frame): encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90] #90的压缩率 result, frame = cv2.imencode('.jpg', frame, encode_param) self.socket_client.send_frame(frame) def stop(self): self.video_stream.release() cv2.destroyAllWindows()
def test_mock_timeout(self, set_up_mock_timeout): client = SocketClient(port=settings.APP_PORT, host=settings.APP_HOST) wait_until(client.connect) client.sock.settimeout(3.1) data, headers = self.get_info(sort='Apple') response = client.request(method='POST', headers=headers, url='/setnew', data=data) assert response[-1] == 'Server timed out'
def test_mock_unavailable(self, set_up_without_mock): client = SocketClient(port=settings.APP_PORT, host=settings.APP_HOST) wait_until(client.connect) data = {'sort': 'Apple'} data = json.dumps(data) headers = self.get_headers(len(data.encode())) response = client.request(method='POST', headers=headers, url='/setnew', data=data) assert response[-1] == 'Connection refused'
def init(clid): global client_socket global client_id client_socket = SocketClient(sc.ser_ip, sc.ser_port) # sign in recv_msg_1 = client_socket.send({"signal": "sign", "client_id": clid}) if recv_msg_1.get("client_id"): client_id = recv_msg_1.get("client_id") logging.info("client_id: %s" % client_id) else: sys.exit(recv_msg_1.get("erro")) logging.info("Line 44: client_id = %s" % client_id)
def experiment_code(experiment=None, time=None, logfile=None, offset=0): experiment_param = { 'experiment': experiment, #the experiment number determines the experiment type, with 'experiment_time': time, #this is the trial length 'logfile_name': logfile or 'Z:/Wilson Lab/Mel/FlyOnTheBall/data/data.hdf5', #this file will be saved in the experiment directory we choose in the GUI I believe, because of the matlab code 'logfile_auto_incr': True, 'logfile_auto_incr_format': '{0:06d}', 'logfile_dt': 0.01, 'offset': offset } client = SocketClient(experiment_param) client.run()
def __init__(self): # self.video_stream = VideoStream( # src=0, usePiCamera=True, width=640, height=480, framerate=32) self.video_stream = cv2.VideoCapture(0) self.video_stream.set(cv2.CAP_PROP_FRAME_WIDTH, 640) self.video_stream.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) self.fire_cascade = cv2.CascadeClassifier('fire_detection.xml') self.host = '192.168.43.52' self.port = 24485 time.sleep(2) self.timeCheck = time.time() self.socket_client = SocketClient() print("init success...")
def __init__(self, configuration, mark_processed, debug=False): """ Initialize the camera object. :param configuration: object containing parameters set by the user :param mark_processed: a method in moon_panorama_maker which marks tiles as processed :param debug: if True, the socket_client (FireCapture connection) is replaced with a mockup object with the same interface. It does not capture videos, but returns the acknowledgement as the real object does. """ QtCore.QThread.__init__(self) self.configuration = configuration # Register method in StartQT5 (module moon_panorama_maker) for marking tile as processed. self.mark_processed = mark_processed # The "triggered" flag is set to True in "workflow" to start an exposure. self.triggered = False # The "active" flag is looked up in "workflow" to find out if a video is being acquired. self.active = False self.terminate = False self.active_tile_number = -1 # Set the parameters for the socket connection to FireCapture. FireCapture might run on a # different computer. self.host = self.configuration.conf.get("Camera", "ip address") self.port = self.configuration.fire_capture_port_number # For debugging purposes, the connection to FireCapture can be replaced with a mockup class # which reads still images from files. These can be used to test the autoaligh mechanism. if debug: self.mysocket = SocketClientDebug( self.host, self.port, self.configuration.camera_debug_delay) if self.configuration.protocol_level > 0: Miscellaneous.protocol( "Camera in debug mode, still camera emulated.") else: try: self.mysocket = SocketClient(self.host, self.port) except: raise CameraException( "Unable to establish socket connection to FireCapture, host: " + self.host + ", port: " + str(self.port) + ".") if self.configuration.protocol_level > 0: Miscellaneous.protocol( "Camera: Connection to FireCapture program established.")
def listen_fn(sock, clients, flags): """ Function to handle the socket server. Args: sock clients ssl_context flags Returns: None. """ while flags['is_running']: sub_addr = None sub_sock = None try: sub_sock, sub_addr = sock.accept() except Exception as ex: print( 'Server has exception when accept new connection: {}'. format(ex)) if sub_sock is not None: client = SocketClient(socket=sub_sock, last_active_ts=datetime.now(), flags={ 'is_running': True, 'is_recording': False, 'flush_num': 0, 'recording_start_ts': None }) # client.start() # start the sub thread handling the client clients.append(client) # save client to the `clients` list
class Detector(object): def __init__(self): self.video_stream = VideoStream( src=0, usePiCamera=True, resolution=(640, 480), framerate=32).start() self.fire_cascade = cv2.CascadeClassifier('fire_detection.xml') self.host = '192.168.1.223' self.port = 8486 time.sleep(2.0) self.timeCheck = time.time() self.socket_client = SocketClient() def start(self): self.socket_client.connect(self.host, self.port) print('Connected') while True: # Get the next frame. frame = self.video_stream.read() # Show video stream gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) fire = self.fire_cascade.detectMultiScale(frame, 1.2, 5) for (x, y, w, h) in fire: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2) font = cv2.FONT_HERSHEY_SIMPLEX roi_gray = gray[y:y+h, x:x+w] roi_color = frame[y:y+h, x:x+w] time.sleep(0.2) print('Detected') cv2.imwrite('sector2.png', frame) self.send_frame(frame) cv2.imshow('out', frame) key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop. if key == ord("q"): break self.timeCheck = time.time() def send_frame(self, frame): encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90] result, frame = cv2.imencode('.jpg', frame, encode_param) self.socket_client.send_frame(frame) def stop(self): cv2.destroyAllWindows() self.video_stream.stop()
def init(debug=False): global sock sock = SocketClient(timeout=1) global capture capture = CaptureThread(debug) capture.start() global markerDict markerDict = aruco.getPredefinedDictionary(aruco.DICT_4X4_250)
def demo(): # Start Example TCP socket client for message in samplelist: # see samplelist in /data_streams/samples.py SocketClient(message=message).start() # Start HTTP example client HTTPClient().start() # Start Example Random Number Stream DataStream(random_nr_config, random_nr).start()
class IRCClient(patterns.Subscriber): def __init__(self, HOST, PORT, music): super().__init__() self.username = str() self._run = True self._s = SocketClient(HOST, PORT) self._s.set_irc(self) self.music = music def set_view(self, view): self.view = view def set_username(self, username): self.username = username def update(self, msg): # TODO Will need to modify this if not isinstance(msg, str): raise TypeError(f"Update argument needs to be a string") elif not len(msg): # Empty string return logger.info(f"IRCClient.update -> msg: {msg}") self.process_input(msg) def process_input(self, msg): # TODO Will need to modify this self.add_msg(msg) self._s.setMsg(msg) if msg.lower().startswith('/quit'): # Command that leads to the closure of the process raise KeyboardInterrupt def add_msg(self, msg): self.view.add_msg(self.username, msg) async def run(self): """ Driver of your IRC Client """ self._s.start() def close(self): # Terminate connection logger.debug(f"Closing IRC Client object") pass
class Gamepad(threading.Thread): def __init__(self, window): threading.Thread.__init__(self) self.done = False self.window = window self.socket = None self.socket = SocketClient('localhost', 10000, self.window.set_status) def run(self): self.socket.connect() if self.socket.is_connected: pygame.init() pygame.joystick.init() while not self.done: pygame.event.get() joystick_count = pygame.joystick.get_count() if joystick_count > 0: joystick = pygame.joystick.Joystick(0) joystick.init() self.send_value(Gamepad.sanitize_digital(joystick.get_axis(1)), self.window.update_left_analog) self.send_value(Gamepad.sanitize_digital(joystick.get_axis(3)), self.window.update_right_analog) self.send_value(joystick.get_hat(0), self.window.update_digital) sleep(0.05) pygame.quit() @staticmethod def sanitize_digital(value): rounded = round(value * -10) if rounded == 1 or rounded == -1: return 0 return rounded def send_value(self, value, callback): message = [value, int(round(time.time() * 1000))] self.socket.send(message, callback) def stop(self): self.socket.disconnect() self.window.set_status('Disconnected') self.done = True
def run(self): # 引入爬虫模块 m = importlib.import_module(self.site_name) import pdb pdb.set_trace() seeds = Queue() if self.task_type == "spec_crawl_index": mc = settings.getMCInstance() db = mc['automotor_ershouche'] if self.site_name == "ganji_ershouche": cur = db['%s_city' % self.site_name].find({}, { 'url': 1, 'pinyin': 1, "name": 1 }) else: cur = db['%s_city' % self.site_name].find({}, { 'url': 1, "name": 1 }) for c in cur: seeds.put(c) import pdb pdb.set_trace() for x in range(self.thread_num): sock = SocketClient(host=self.server_ip, port=self.server_port, key=settings.tcp_login_key, user_name=self.name, logger=self.logger) crawler = m.Crawler(x, self.logger, self.task_type, self.proxy_type, sock, seeds, self.register, self.login) self.threads.append(gevent.spawn(crawler.run)) import pdb pdb.set_trace() gevent.joinall(self.threads)
#dir_name = 'mfw/' # db manager webdrivers = {} dbmanager = MongoRedisUrlManager() is_root_page = True threads = [] options = webdriver.ChromeOptions() # 设置中文 options.add_argument('lang=zh_CN.UTF-8') prefs = {"profile.managed_default_content_settings.images": 2} options.add_experimental_option("prefs", prefs) # use hdfs to save pages # hdfs_client = InsecureClient('http://54.223.92.169:50070', user='******') socket_client = SocketClient('localhost', 20012) client_id = 0 hb_period = 5 run_heartbeat = True server_status = pc.STATUS_RUNNING init() start_heart_beat_thread() crawl() finish() for dr in webdrivers: dr.close() dr.quit()
def __init__(self, window): threading.Thread.__init__(self) self.done = False self.window = window self.socket = None self.socket = SocketClient('localhost', 10000, self.window.set_status)
class Camera(QtCore.QThread): """ This class provides an asynchronous interface to the video camera for the acquisition of videos. A separate thread waits for triggers from the workflow object to start the camera. It then sends a request to the MoonPanoramaMaker plugin in FireCapture via the socket_client, and waits for the acknowledgement message which confirms that the video has been captured. Please note that the socket interface to FireCapture is also used in synchronous mode for still picture capturing used by the autoalignment mechanism. """ # During camera initialization (in class "workflow") the signal is connected with method # "signal_from_camera" in moon_panormaa_maker. camera_signal = QtCore.pyqtSignal() def __init__(self, configuration, mark_processed, debug=False): """ Initialize the camera object. :param configuration: object containing parameters set by the user :param mark_processed: a method in moon_panorama_maker which marks tiles as processed :param debug: if True, the socket_client (FireCapture connection) is replaced with a mockup object with the same interface. It does not capture videos, but returns the acknowledgement as the real object does. """ QtCore.QThread.__init__(self) self.configuration = configuration # Register method in StartQT5 (module moon_panorama_maker) for marking tile as processed. self.mark_processed = mark_processed # The "triggered" flag is set to True in "workflow" to start an exposure. self.triggered = False # The "active" flag is looked up in "workflow" to find out if a video is being acquired. self.active = False self.terminate = False self.active_tile_number = -1 # Set the parameters for the socket connection to FireCapture. FireCapture might run on a # different computer. self.host = self.configuration.conf.get("Camera", "ip address") self.port = self.configuration.fire_capture_port_number # For debugging purposes, the connection to FireCapture can be replaced with a mockup class # which reads still images from files. These can be used to test the autoaligh mechanism. if debug: self.mysocket = SocketClientDebug( self.host, self.port, self.configuration.camera_debug_delay) if self.configuration.protocol_level > 0: Miscellaneous.protocol( "Camera in debug mode, still camera emulated.") else: try: self.mysocket = SocketClient(self.host, self.port) except: raise CameraException( "Unable to establish socket connection to FireCapture, host: " + self.host + ", port: " + str(self.port) + ".") if self.configuration.protocol_level > 0: Miscellaneous.protocol( "Camera: Connection to FireCapture program established.") def run(self): while not self.terminate: if self.triggered: self.triggered = False self.active = True # Acquire "repetition_count" videos by triggering FireCapture through the socket. # Setting a repetition count > 1 allows the consecutive acquisition of more than # one video (e.g. for exposures with different filters. repetition_count = self.configuration.conf.getint( "Camera", "repetition count") for video_number in range(repetition_count): if video_number > 0: # If more than one video per tile is to be recorded, insert a short wait # time. Otherwise FireCapture might get stuck. time.sleep(self.configuration. camera_time_between_multiple_exposures) if self.configuration.protocol_level > 0: Miscellaneous.protocol( "Camera: Send trigger to FireCapture, tile: " + str(self.active_tile_number) + ", repetition number: " + str(video_number) + ".") try: # The tile number is encoded in the message. The FireCapture plugin appends # this message to the video file names (to keep the files apart later). msg = "_Tile-{0:0>3}".format(self.active_tile_number) self.mysocket.mysend(msg) except Exception as e: if self.configuration.protocol_level > 0: Miscellaneous.protocol( "Camera, Error message in trigger: " + str(e)) if self.configuration.protocol_level > 2: Miscellaneous.protocol( "Camera: Wait for FireCapture to finish exposure" + ".") try: # Wait for FireCapture to finish the exposure. ack_length = 1 ack = self.mysocket.myreceive(ack_length) except Exception as e: if self.configuration.protocol_level > 0: Miscellaneous.protocol( "Camera, Error message in ack: " + str(e)) if self.configuration.protocol_level > 2: Miscellaneous.protocol( "Camera: acknowledgement from FireCapture = " + str(ack) + ".") # All videos for this tile are acquired, mark tile as processed. self.mark_processed() # Trigger method "signal_from_camera" in moon_panorama_maker self.camera_signal.emit() if self.configuration.protocol_level > 0: Miscellaneous.protocol( "Camera, all videos for tile " + str(self.active_tile_number) + " captured, signal (tile processed) emitted.") self.active = False # Insert a wait time to keep the CPU usage low. time.sleep(self.configuration.polling_interval) self.mysocket.close() if self.configuration.protocol_level > 0: Miscellaneous.protocol( "Camera: Connection to FireCapture program closed.")
class HeartBeatClient(): server_status = pc.STATUS_RUNNING run_heartbeat = False client_id = -1 hb_period = 5 socket_client = SocketClient('localhost', '9900') def __init__(self): self.run_heartbeat = False def connect(self): register_request = {} register_request[pc.MSG_TYPE] = pc.REGISTER self.client_id = self.socket_client.send(json.dumps(register_request)) if self.client_id is None: raise IOError('Connection Failed') def disconnect(self): register_request = {} register_request[pc.MSG_TYPE] = pc.UNREGISTER self.socket_client.send(json.dumps(register_request)) def start(self): try: t = threading.Thread(target=self.heartbeat, name=None) # set daemon so main thread can exit when receives ctrl-c t.setDaemon(True) t.start() except Exception as err: print("Error: unable to start thread", err) raise def heartbeat(self): skip_wait = False while self.run_heartbeat: if skip_wait is False: time.sleep(self.hb_period) else: skip_wait = False try: hb_request = {} hb_request[pc.MSG_TYPE] = pc.HEARTBEAT hb_request[pc.CLIENT_ID] = self.client_id hb_response_data = self.socket_client.send( json.dumps(hb_request)) # should be network error if hb_response_data is None: continue # print( 'Heart Beat response' + json.dumps(hb_response_data)) response = json.loads(hb_response_data) err = response.get(pc.ERROR) if err is not None: if err == pc.ERR_NOT_FOUND: register_request = {} register_request[pc.MSG_TYPE] = pc.REGISTER self.client_id = self.socket_client.send( json.dumps(register_request)) # skip heartbeat period and send next heartbeat immediately skip_wait = True self.heartbeat() return return action = response.get(pc.ACTION_REQUIRED) if action is not None: action_request = {} if action == pc.PAUSE_REQUIRED: self.server_status = pc.PAUSED action_request[pc.MSG_TYPE] = pc.PAUSED elif action == pc.PAUSE_REQUIRED: self.server_status = pc.RESUMED action_request[pc.MSG_TYPE] = pc.RESUMED elif action == pc.SHUTDOWN_REQUIRED: self.server_status = pc.SHUTDOWN # stop heartbeat thread return action_request[pc.CLIENT_ID] = self.client_id self.socket_client.send(json.dumps(action_request)) else: self.server_status = response[pc.SERVER_STATUS] except socket.error as msg: print('Send Data Error. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]) self.server_status = pc.STATUS_CONNECTION_LOST def get_target_items(self, type): hb_request = {} hb_request[pc.MSG_TYPE] = type hb_request[pc.CLIENT_ID] = self.client_id response = self.socket_client.send(json.dumps(hb_request)) return response[pc.DATA] def finish_target_items(self, type, items): hb_request = {} hb_request[pc.MSG_TYPE] = type hb_request[pc.CLIENT_ID] = self.client_id hb_request[pc.FINISHED_ITEMS] = json.dumps(items) self.socket_client.send(json.dumps(hb_request))
def create_new_client(self, rower_index): self.clients.append(SocketClient(rower_index))
class CubeClient(object): def __init__(self, address, port): self.address = address self.port = port self.seq = 0 self.session_id = random.randint(0, sys.maxint) self.socket = SocketClient(self.address, self.port) self.status = CubeStatus.UNKNOW def __get_session_id(self): return self.session_id def __get_seq(self): self.seq += 1 return self.seq def __dec_seq(self): self.seq -= 1 return self.seq def __get_user_name(self): return self.user_name def __get_msg_list(self, _server_type): msg_list = {} msg_list['session_id'] = self.__get_session_id() msg_list['serve_type'] = _server_type return msg_list def __send_command(self, _msg_list): for retry in range(0, 2): try: while True: _msg_list["seq"] = self.__get_seq() ret = self.socket.send_message(_msg_list, 100) if ret['reply_type'] == CubeReplyCode.EXECUTING: time.sleep(1) else: break if ret['reply_type'] != CubeReplyCode.SUCCESS: self.__dec_seq() message = "Error code: " + str( ret['reply_type']) + " msg: " + ret['error_msg'] logger.error(message) if ret['reply_type'] == CubeRunErrorCode.DEVICE_NEED_ROOT: raise DeviceNotRootError("手机未ROOT,无法使用CUBE服务") elif ret[ 'reply_type'] == CubeRunErrorCode.GET_MONITOR_FILE_ERROR: raise GetMonitorFileError( "由于游戏崩溃或其他原因,导致本次测试失败,需重新测试。") else: return ret, CubeRunErrorCode.SUCCESS except DeviceNotRootError: stack = traceback.format_exc() logger.exception(stack) raise DeviceNotRootError("手机未ROOT,无法使用CUBE服务") except GetMonitorFileError: stack = traceback.format_exc() logger.exception(stack) return None, CubeRunErrorCode.CUBE_STOP_APP_ERROR except: stack = traceback.format_exc() logger.exception(stack) # os.system("adb shell ps") ret = self.recover_data() if ret is True: return json.loads("{}"), CubeRunErrorCode.SUCCESS return None, CubeRunErrorCode.CUBE_ERROR def __detect_status(self): pass def connect_cube(self, _user_name): """ 连接cubex,与之沟通sessionid、seq、username :param _user_name: wetest用户id,用于上传报告 :return: 成功:cubex返回数据,失败:None """ logger.debug("connect cube server.") msg_list = self.__get_msg_list(CubeServerType.CONNECTION_BUILD) self.user_name = _user_name # '133870' msg_list['user_name'] = self.user_name return self.__send_command(msg_list) def begin_cube_test(self, _game_name, _comment="", _test_type=CubeTestLevel.LIGHT, _snapshots=CubeSnapshots.OPEN): """ 开始测试,提供游戏包名、测试场景名,以及其他测试参数等,完成测试。 :param _game_name: 待测游戏包名 :param _comment: 测试场景名称 :param _test_type: 测试类型(整形)。0:表示轻度性能,1:表示重度性能,2:表示资源测试,3:表示mono内存 :param _snapshots: 截图功能(整形)。0:表示关闭截图,1:表示开启截图(截图暂时功能未开放); :param _ :return: 成功:cubex返回数据,失败:None """ logger.debug("begin cube test.") msg_list = self.__get_msg_list(CubeServerType.BEGIN_TEST) msg_list['comment'] = _comment msg_list['target_name'] = _game_name msg_list['test_type'] = _test_type msg_list['snapshots'] = _snapshots ret, status = self.__send_command(msg_list) if ret is None: raise CubeRuntimeError("Can not launch the app!") else: return status def begin_unity_test(self, _game_name, _comment="", _test_type=CubeTestLevel.UNITY_PROFILE, _snapshots=CubeSnapshots.OPEN, _before5d6=0): """ 开始测试,提供游戏包名、测试场景名,以及其他测试参数等,完成测试。 :param _game_name: 待测游戏包名 :param _comment: 测试场景名称 :param _test_type: 测试类型(整形)。0:表示轻度性能,1:表示重度性能,2:表示资源测试,3:表示mono内存 :param _snapshots: 截图功能(整形)。0:表示关闭截图,1:表示开启截图(截图暂时功能未开放); :param _before5d6: unity版本是否高于5.6 :return: 成功:cubex返回数据,失败:None """ logger.debug("begin cube test.") msg_list = self.__get_msg_list(CubeServerType.BEGIN_TEST) msg_list['comment'] = _comment msg_list['target_name'] = _game_name msg_list['test_type'] = _test_type msg_list['snapshots'] = _snapshots msg_list['before5d6'] = _before5d6 ret, status = self.__send_command(msg_list) if ret is None: raise CubeRuntimeError("Can not launch the app!") else: return status def mark_tag(self): """ 打标记 :return: 成功:cubex返回数据,失败:None """ logger.debug("cube scene tag.") msg_list = self.__get_msg_list(CubeServerType.SCENE_TAG) ret, status = self.__send_command(msg_list) if ret is None: raise CubeRuntimeError("Can not mark scene tag!") else: return status def scene_tag(self): """ Deprecated function. 兼容老版本保留。 打标记,请使用mark_tag()函数。 :return: """ self.mark_tag() def stop_cube_test(self): """ 停止测试 :return: 成功:cubex返回数据,失败:None """ logger.debug("stop cube test.") msg_list = self.__get_msg_list(CubeServerType.STOP_TEST) # print "msg_list=" + msg_list ret, status = self.__send_command(msg_list) if ret is None: raise CubeRuntimeError("Can not stop test!") else: return status def upload_record(self): """ 上传报告 :return: 成功:cubex返回数据,失败:None """ logger.debug("upload record.") msg_list = self.__get_msg_list(CubeServerType.UPLOAD_OR_DELETE_RECORD) msg_list['dealt_type'] = CubeUploadDelete.UPLOAD ret, status = self.__send_command(msg_list) if ret is None: raise CubeRuntimeError( "Can not upload record. Please check your username or network!" ) else: return status def delete_record(self): """ 删除报告 :return: 成功:cubex返回数据,失败:None """ logger.debug("delete cube.") msg_list = self.__get_msg_list(CubeServerType.UPLOAD_OR_DELETE_RECORD) msg_list['dealt_type'] = CubeUploadDelete.DELETE ret, status = self.__send_command(msg_list) if ret is None: raise CubeRuntimeError("Can not delete record!") else: return status def _restart_cube_service(self): logger.debug("restart cube service..") for retry in range(0, 2): file = os.popen( "adb shell am startservice " + "com.tencent.cubex/com.tencent.cubex.service.CubeService") file.readline() result = 0 while True: line = file.readline() logger.debug(line) if not line: result = 1 break else: if "Error" in line: result = -1 if result == 1: break return result def recover_data(self): """ 恢复数据 :return: 成功恢复:cubex返回数据,失败:None """ logger.debug("revocer cube data.") result = self._restart_cube_service() if result != 1: raise CubeServiceStartError("Cube服务无法启动,请检查是否正确安装Cube服务并使能相关权限。") for retry in range(0, 2): try: msg_list = self.__get_msg_list(CubeServerType.RECOVER_DATA) while True: msg_list["seq"] = self.__get_seq() ret = self.socket.send_message(msg_list) if ret['reply_type'] == CubeReplyCode.EXECUTING: time.sleep(1) else: break if ret['reply_type'] != CubeReplyCode.RESEND_CMD and ret[ 'reply_type'] != CubeReplyCode.CONTINUE_CMD: message = "Error code: " + str( ret['reply_type']) # + " msg: " + ret['error_msg'] logger.error(message) self.session_id = ret['session_id'] self.seq = ret['seq'] - 1 raise CubeServiceError( "Can not recover the data, please check your phone or restart the test to try!" ) elif ret['reply_type'] == CubeReplyCode.RESEND_CMD: # 最近操作未完成,需重新操作 self.session_id = ret['session_id'] self.seq = ret['seq'] - 1 return False elif ret['reply_type'] == CubeReplyCode.CONTINUE_CMD: # 最近操作已完成,进入下一步操作 self.session_id = ret['session_id'] self.seq = ret['seq'] return True except: stack = traceback.format_exc() logger.exception(stack) self._restart_cube_service() raise CubeRecoverError( "Can not recover data! Please check your phone!")
from socket_client import SocketClient socket_client = SocketClient() socket_client.start("192.168.0.15", 65432)
class HeartBeatClient(object): server_status = pc.STATUS_RUNNING client_id = -1 hb_period = 5 skip_wait = False socket_client = SocketClient('192.168.1.105', 9000) def __init__(self): self.run_heartbeat = True def connect(self): register_request = {} register_request[pc.MSG_TYPE] = pc.REGISTER self.client_id = self.socket_client.send( json.dumps(register_request)).decode() print('this is the client id :', self.client_id) if self.client_id is None: raise IOError('Connection Failed!') def disconnect(self): register_request = {} register_request[pc.MSG_TYPE] = pc.REGISTER self.socket_client.send(json.dumps(register_request)) def heartbeat(self): while self.run_heartbeat: if self.skip_wait is False: time.sleep(self.hb_period) else: self.skip_wait = False try: hb_request = {} hb_request[pc.MSG_TYPE] = pc.HEARTBEAT hb_request[pc.CLIENT_ID] = self.client_id hb_response_data = self.socket_client.send( json.dumps(hb_request)) # should be network error if hb_response_data is None: continue response = json.loads(hb_response_data) err = response.get(pc.ERROR) if err is not None: # client_id is not register if err == pc.ERR_NOT_FOUND: register_request = {} register_request[pc.MSG_TYPE] = pc.REGISTER self.client_id = self.socket_client.send( register_request).decode() # skip heartbeat period and send next heartbeat immediately self.skip_wait = True self.heartbeat() return return action = response.get(pc.ACTION_REQUIRED) if action is not None: action_request = {} if action == pc.PAUSE_REQUIRED: action_request[pc.MSG_TYPE] = pc.PAUSED elif action == pc.RESUME_REQUIRED: action_request[pc.MSG_TYPE] = pc.RESUMED elif action == pc.SHUTDOWN_REQUIRED: # stop heartbeat thread return action_request[pc.CLIENT_ID] = self.client_id action_response = self.socket_client.send( json.dumps(action_request)) self.server_status = action_response.get(pc.SERVER_STATUS) else: # a normal heart beat self.server_status = response[pc.SERVER_STATUS] except socket.error as msg: print('Send Data Error. Error Code: ' + str(msg[0]) + 'Message' + msg[1]) self.server_status = pc.STATUS_CONNECTION_LOST def get_target_urls(self, type=pc.LOCATIONS): ''' :param type: pc.LOCATIONS or pc.TRIPLES ''' hb_request = {} hb_request[pc.MSG_TYPE] = type hb_request[pc.CLIENT_ID] = self.client_id response = self.socket_client.send(json.dumps(hb_request)) response = json.loads(response) crawl_delay = response.get(pc.CRAWL_DELAY) response_dict = {} if crawl_delay is not None: response_dict[pc.DATA] = response[pc.DATA] response_dict[pc.CRAWL_DELAY] = crawl_delay return response_dict else: response_dict[pc.DATA] = response[pc.DATA] return response_dict def finish_target_urls(self, items, _type=pc.FINISHED_ITEMS): ''' :param items: new url list ''' hb_request = {} hb_request[pc.MSG_TYPE] = _type hb_request[pc.CLIENT_ID] = self.client_id hb_request[pc.FINISHED_ITEMS] = items self.socket_client.send(json.dumps(hb_request))
def __init__(self): #Color initializations self.BLACK = (0, 0, 0) self.WHITE = (255, 255, 255) self.BALL_COLOR = (255, 255, 255) #Pygame initializations pygame.init() pygame.mixer.init(22050, -8, 16, 65536) self.size = (500, 500) self.screen = pygame.display.set_mode(self.size) self.clock = pygame.time.Clock() pygame.display.set_caption("PyPong") #Block position initializations self.left_y = self.size[1] / 2 self.right_y = self.size[1] / 2 self.pos_dict = {0: self.left_y, 1: self.right_y} self.block_size = 50 #Block movement booleans self.left_down = False self.right_down = False self.left_up = False self.right_up = False #Ball velocity variables self.ball_xv = 6 self.ball_yv = 6 self.ball_x = self.size[0] / 2 self.ball_y = self.size[1] / 2 self.abs_vel = 4 self.ball_time = 0 self.flip = 0 #Side Score Variables self.side_score = {0: 0, 1: 0} #Text Variables self.font = pygame.font.Font('freesansbold.ttf', 15) socket = SocketClient(self.pos_dict[1]) done = False self.ballInit() while not done: socket.pos = self.pos_dict[1] socket.send_msg() socket.recv_msg() self.pos_dict[0] = int(socket.pos_other) self.ball_x = socket.ball[0] self.ball_y = socket.ball[1] for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_s: self.left_down = True elif event.key == pygame.K_DOWN: self.right_down = True elif event.key == pygame.K_w: self.left_up = True elif event.key == pygame.K_UP: self.right_up = True elif event.type == pygame.KEYUP: if event.key == pygame.K_s: self.left_down = False elif event.key == pygame.K_DOWN: self.right_down = False elif event.key == pygame.K_w: self.left_up = False elif event.key == pygame.K_UP: self.right_up = False self.screen.fill(self.BLACK) self.checkMovement() self.drawBlocks() self.drawBall() self.checkColl() self.ballMove() self.clock.tick(120) pygame.display.flip() pygame.quit()
async def on_client_message(message, host): client = SocketClient(host, int(os.getenv("CORE_PORT"))) client.write(message)
from socket_client import SocketClient socket_client = SocketClient(socket_numbers=2) socket_client.add_socket({ "host": "192.168.1.163", "port": 12345 }).add_socket({ "host": "192.168.1.211", "port": 12345 }) socket_client.start()
constants = { 'MAX_PAGE_TRIED': 2, 'HB_PERIOD': 5, 'MAX_SIZE_THREADPOOL': 3, 'CRAWL_DELAY': 2 } # db manager dbmanager = MongoRedisUrlManager() start_time = time.time() threads = {} webdrivers = {} socket_client = SocketClient('localhost', 20100) register_request = {} register_request[pc.MSG_TYPE] = pc.REGISTER client_id = socket_client.send(json.dumps(register_request)) run_heartbeat = True server_status = pc.STATUS_RUNNING re_compiled_obj = re.compile('\d{7}') hbase = HBaseManager(host='54.223.92.169') thread_pool_drivers = {} if __name__ == '__main__': # start heartbeat thread