def connect(self): screepsConnection = API(u=self.user,p=self.password,ptr=self.ptr,host=self.host,secure=self.secure, token=self.atoken) me = screepsConnection.me() self.user_id = me['_id'] self.token = screepsConnection.token if self.logging: logging.getLogger('websocket').addHandler(logging.StreamHandler()) websocket.enableTrace(True) else: logging.getLogger('websocket').addHandler(logging.NullHandler()) websocket.enableTrace(False) if self.host: url = 'wss://' if self.secure else 'ws://' url += self.host + '/socket/websocket' elif not self.ptr: url = 'wss://screeps.com/socket/websocket' else: url = 'wss://screeps.com/ptr/socket/websocket' self.ws = websocket.WebSocketApp(url=url, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, on_open=self.on_open) ssl_defaults = ssl.get_default_verify_paths() sslopt_ca_certs = {'ca_certs': ssl_defaults.cafile} if 'http_proxy' in self.settings and self.settings['http_proxy'] is not None: http_proxy_port = self.settings['http_proxy_port'] if 'http_proxy_port' in self.settings else 8080 self.ws.run_forever(http_proxy_host=self.settings['http_proxy'], http_proxy_port=http_proxy_port, ping_interval=1, sslopt=sslopt_ca_certs) else: self.ws.run_forever(ping_interval=1, sslopt=sslopt_ca_certs)
def connect(self): if self.state != State.DISCONNECTED: self.disconnect() print "Connecting..." # start new connection websocket.enableTrace(self.enable_trace) ws = websocket.WebSocketApp( "ws://localhost:8888/", on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, on_open=self.on_open, on_ping=self.on_ping, on_pong=self.on_pong) socket_options = [ (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), (socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 10), (socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5), (socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 1) ] ssl_options = { 'cert_reqs': ssl.CERT_NONE } ws.run_forever(sockopt=socket_options, sslopt=ssl_options)
def update_client(task_queue): def on_message(ws, message): print message def on_error(ws, error): print error def on_close(ws): print "### closed ###" def on_open(ws): def run(*args): while True: next_task = task_queue.get() time.sleep(5) if next_task: # Poison pill means shutdown #print '%s: Exiting' % proc_name ws.send(str(next_task)) print value_global task_queue.task_done() print "something" websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://localhost:8888/ws", on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever()
def connect(self, apiKey, secretKey, trace=False): """ 连接网关 :param apiKey : 申请的API key :param secretKey: 签名key :param trace : 是否开启websocket的日志跟踪功能,输出到StreamHandler :return: """ # 更新websocket服务器地址/API key/ self.host = OKEX_USD_SPOT self.apiKey = apiKey self.secretKey = secretKey # 是否开启日志 websocket.enableTrace(trace) # 创建websocket,绑定本地回调函数 onMessage/onError/onClose/onOpen self.ws = websocket.WebSocketApp(self.host, on_message=self.onMessage, on_error=self.onError, on_close=self.onClose, on_open=self.onOpen) self.thread = Thread(target=self.ws.run_forever) self.thread.start()
def main(): while True: # infinite loop websocket.enableTrace(False) url = "ws://websocket.mtgox.com/mtgox" ws = websocket.WebSocket() ws.LASTTICKER = time.time() - 15 # sets the last ticker 30 seconds prior to now, so it shows up on first run. ws.LASTLAG = time.time() - 30 # same for the lag counter try: ws.connect(url) # try to connect except (socket.error, websocket.WebSocketConnectionClosedException) as error: on_error(error) on_reconnect() continue on_open() subscribeto = serialize({"op": "mtgox.subscribe", "type": "lag"}) # serialize({"op":"unsubscribe", "channel":"24e67e0d-1cad-4cc0-9e7a-f8523ef460fe"}) ws.send(subscribeto) try: while True: data = ws.recv() # start receiving data on_message(ws, data) except KeyboardInterrupt as e: on_close(ws) return except Exception as error: traceback.print_exc() on_error(error) on_close(ws) on_reconnect() # try to reconnect
def __init__(self): #create database # file = "myDB.db" # self.path = "d:/git/bitbot/"+file # self.db = sqlite3.connect(self.path) # self.cursor = self.db.cursor() # self.cursor.execute( # """CREATE TABLE ok_btcusd_depth( # bid REAL, # bid_amount REAL, # ask REAL, # ask_amount REAL) # """) # self.cursor.execute( # """CREATE TABLE ok_btcusd_trades( # price REAL, # amount REAL, # time TEXT, # type TEXT) # """) # self.db.commit() #connect to websocket websocket.enableTrace(True) url = "wss://ws-feed.exchange.coinbase.com" self.ws = websocket.WebSocketApp(url, on_message=self.on_message, on_error=self.on_error ) self.ws.on_open = self.on_open self.ws.run_forever()
def main(): config = configparser.ConfigParser() config.read('config.ini') url = "https://slack.com/api/rtm.start" token = config['slack']['token'] parameters = { "token": token } data = urllib.parse.urlencode(parameters) data = data.encode('utf-8') req = urllib.request.Request(url, data) with urllib.request.urlopen(req) as response: downloadedPage = response.read() pageJson = json.loads(downloadedPage.decode('utf-8')) websocket.enableTrace(True) ws = websocket.WebSocketApp(pageJson.get('url'), on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever()
def send_request_to_agent(ip_host, instance_data, task): distribution, version, arch = instance_data['operating_system'].split('-') data = {'task_uuid': task['uuid'], 'instance_uuid': task['object_uuid'], 'action': 'create', 'driver': instance_data['driver'], 'name': instance_data['name'], 'distribution': distribution, 'version': version, 'arch': arch, 'launch':1, 'cpus':1, 'provisioner': instance_data['provisioner'], 'executor': instance_data['executor'], 'user':'******', 'password':'******', 'memory':1024} websocket.enableTrace(True) ws = websocket.create_connection("ws://%s:8080/" % (ip_host)) ws.send(json.dumps(data)) result = ws.recv() ws.close() return result
def ws_run(): if __name__ == "__main__": global play_args # check args play_args = play_args_aplay if len(sys.argv) == 2: if sys.argv[1] == 'sox': play_args = play_args_sox global WS_DEBUG if WS_DEBUG: websocket.enableTrace(True) else: websocket.enableTrace(False) ws = websocket.WebSocketApp("ws://aprs.hamclub.net:20880/mtracker/talkbox0?type=sub&udid=bg5hhp-1", #ws = websocket.WebSocketApp("ws://localhost:8080/mclub/talk0?type=sub&udid=bg5hxe", #on_message = ws_on_message, on_data = ws_on_data, on_error = ws_on_error, on_close = ws_on_close) ws.on_open = ws_on_open stopFlag = Event() timer = KeepAliveThread(stopFlag,ws) timer.start() gpio_init() ws.run_forever() stopFlag.set() #stop the timer gpio_reset()
def on_connect(self): print "Servidor conectado" if not self.ws == None: websocket.enableTrace(True) # code that runs when a connection is created # (to init the serivce, if needed) pass
def main(): global WEB_SOCKET data_dir = os.path.join(os.getcwd(), DATA_DIRECTORY) if not os.path.exists(data_dir): os.makedirs(data_dir) while(RUNNING): retry_time = 0 if WEB_SOCKET is not None: if hasattr(WEB_SOCKET, 'retry_time'): retry_time = WEB_SOCKET.retry_time else: retry_time = 10 print("Retry wait time: " + str(retry_time)) # sys.stdout.flush() time.sleep(retry_time) token = _get_token() url = STATS_API + "?jwt=" +token # url = "ws://192.168.1.2:9999/" print(url) websocket.enableTrace(True) WEB_SOCKET = websocket.WebSocketApp(url, on_message = _on_message, on_error = _on_error, on_close = _on_close) WEB_SOCKET.retry_time = retry_time WEB_SOCKET.on_open = _on_open WEB_SOCKET.run_forever(ping_interval=None)
def send_request_to_agent(ip_host, instance_data, image_data, provisioner_data, task): # For example: ubuntu_server_14.04.2_amd64 operating_system, type_operating_system, version, architecture = provisioner_data["image"].split("_") launch = instance_data["launch"] if "launch" in instance_data else 1 data = { "task_uuid": task["uuid"], "instance_uuid": task["object_uuid"], "action": "create", "driver": instance_data["driver"], "name": instance_data["name"], "distribution": operating_system, "version": version, "arch": architecture, "launch": launch, "cpus": instance_data["cpus"], "builder": provisioner_data["builder"], "executor": provisioner_data["executor"], "image": image_data["container_resource"] if "container_resource" in image_data else "", "user": USER, "password": PASSWORD, "memory": instance_data["memory"], } websocket.enableTrace(True) ws = websocket.create_connection("ws://%s:8080/" % (ip_host)) ws.send(json.dumps(data)) result = ws.recv() ws.close() return result
def main(*args): p = ProtoMGMT() if len(args) > 0: if args[0] == "--list": try: get_list() except: print "Cannot get list" return 0 for a in args: p.add_proto(a) if len(p.l_proto) == 0: print "Listen ALL protocols" else: print "Listen :", p.l_proto websocket.enableTrace(False) ws = websocket.WebSocketApp("ws://192.168.1.137:9000/admin", on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open try: ws.run_forever() except KeyboardInterrupt: print "Stopping..." return 0
def main(api_url, ws_url, teamname): global_things['API_URL'] = api_url global_things['WS_URL'] = ws_url global_things['TEAMNAME'] = teamname log("API Url: {}".format(global_things['API_URL'])) log("WS Url: {}".format(global_things['WS_URL'])) log("Teamname: {}".format(global_things['TEAMNAME'])) print("API Url: {}".format(global_things['API_URL'])) print("WS Url: {}".format(global_things['WS_URL'])) print("Teamname: {}".format(global_things['TEAMNAME'])) register_team() websocket.enableTrace(True) ws = websocket.WebSocketApp( global_things['WS_URL'], on_message = receive_message, on_error = receive_error, on_close = connection_closed ) ws.on_open = open_connection try: ws.run_forever() except KeyboardInterrupt: log("Terminating") print("Terminating")
def run(self): if self.ws is None: ari_url = self.config.get('default', 'ari_url') ari_login = self.config.get('default', 'ari_login') ari_pass = self.config.get('default', 'ari_pass') if self.mode == 1: websocket.enableTrace(True) try: self.ws = websocket.WebSocketApp("ws://{0}/ari/events?api_key={1}:{2}&app=NameResolver".format(ari_url, ari_login, ari_pass), on_message = self.on_message, on_error = self.on_error, on_close = self.on_close) self.ws.on_close = self.on_close logging.info( "Service start " ) logging.info( "-=============================================================================================-" ) self.ws.run_forever() except: logging.debug( 'Erorr websocket:' ) finally: if self.ws is not None: logging.debug( "Socket close" ) self.ws.close() self.ws = None
def run_websocket_watcher(): global ws Log('Starting websocket listener') websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://" + Prefs['PLEX_ADDRESS'] + "/:/websockets/notifications?X-Plex-Token=" + ACCESS_TOKEN, on_message = on_message) Log("Up and running, listening") ws.run_forever()
def main(): config = read_config('config.ini') url = config.get('server', 'url') websocket.enableTrace(config.get('debug', 'trace')) ws = websocket.WebSocketApp(url, on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close) ws.state = "initialize" ws.chid = chid ws.version = version ws.success = False ws.run_forever() print("leaving") print "==============" result = True if ws.success: print "Smoke test was successful" else: print "Smoke test failed." result = False; print "==============" if not result: sys.exit(-1)
def load_justdice(secret_url=None, proxy=None, headers=None, debug=False): """ "proxy" is expected to be a map from protocol to a proxy server. e.g., proxy={'https': 'myproxy:port'} would use a proxy for https requests. "headers" should be a sequence of tuples to be added in each request. e.g, headers=[('User-Agent', 'bot')] """ handler = [] if debug: websocket.enableTrace(True) handler.append(urllib2.HTTPSHandler(debuglevel=1)) cookie_handler = urllib2.HTTPCookieProcessor(cj) handler.append(cookie_handler) if proxy is not None: proxy_handler = urllib2.ProxyHandler(proxy) handler.append(proxy_handler) opener = urllib2.build_opener(*handler) headers = headers or [] headers.append(('Origin', BASE_URL)) opener.addheaders = headers if secret_url is not None: opener.open('%s/%s' % (BASE_URL, secret_url)) else: opener.open(BASE_URL) req = opener.open('%s/socket.io/1' % BASE_URL) # Grab the session in order to allow the websocket connection. response = req.read() return response
def pqrgn_pull(): def cycle(ws): print 'Starting pull cycle...' print 'Starting Pull Messages of Shard [%s - %s] from CM...' % (0, 7) ws.send(json.dumps(range(8))) def on_message(ws, message): print 'Got Response from CM Side. Response is %s' % message # Simulate Persisting message time.sleep(2) print 'Finish Persisting Message from CM Side' cycle(ws) def on_error(ws, error): print error def on_close(ws): print "#Connection Closed..." def on_open(ws): cycle(ws) websocket.enableTrace(True) ws = websocket.WebSocketApp("%s/pull/" % HOST, on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever()
def start_socket(idk,stop_event): while(not stop_event.is_set()): websocket.enableTrace(False) url = 'ws://websocket.mtgox.com/mtgox' ws = websocket.WebSocket() #ws.LASTTICKER = time.time() - 15 #sets the last ticker 30 seconds prior to now, so it shows up on first run. #ws.LASTLAG = time.time() - 30 #same for the lag counter try: ws.connect(url) #try to connect except socket.error as error: on_error(error) on_reconnect() continue on_open() #subscribeto = serialize({"op":"mtgox.subscribe", "type":"lag"}) #serialize({"op":"unsubscribe", "channel":"24e67e0d-1cad-4cc0-9e7a-f8523ef460fe"}) #ws.send(subscribeto) try: while(not stop_event.is_set()): data = ws.recv() #start receiving data on_message(ws,data) except KeyboardInterrupt as e: on_close(ws) return except Exception as error: on_error(error) on_close(ws) on_reconnect() #try to reconnect
def pqrgn_push(): def cycle(ws): print 'Starting push cycle...' # Simulate Query Message for CM time.sleep(2) rec = ['rec3', 'rec4'] print 'Starting Push Message %s to CM...' % rec ws.send(json.dumps(rec)) print 'Finish Pushing Message %s to CM...' % rec def on_message(ws, message): print 'Got Response from CM Side. Response is %s' % message cycle(ws) def on_error(ws, error): print error def on_close(ws): print "#Connection Closed..." def on_open(ws): cycle(ws) websocket.enableTrace(True) ws = websocket.WebSocketApp("%s/push/" % HOST, on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever()
def connect(self): #Connect to the websocket server websocket.enableTrace(True) ws=websocket.WebSocketApp("ws://"+self.theurl+"?id="+self.id+"&type="+self.type, on_open=self.on_open, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close) print self.theurl ws.run_forever() self.connected=0
def getDisplay(startTime,endValue,userInput): global data, reference, time,command,iterations,ydisplay,xdisplay,i,cumulTime,target # Initialize variables iterations = 0 ydisplay = [0] xdisplay =[0] i=1 cumulTime=0 #Set globals data = userInput reference = endValue time = startTime command = pvsCommand(data[0]['im'],data[0]['btn']) print command if(data[0]['im'] == "mousedown"): target = data[1]['v'] print "Target value: ", target websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://localhost:8080/", on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever() return (xdisplay, ydisplay)
def main(): config = ConfigParser.ConfigParser() config.read('config.ini') url = config.get('server', 'url') websocket.enableTrace(config.get('debug', 'trace')) ws = websocket.WebSocketApp(url, on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close) ws.state = "initialize" ws.appid = appid ws.version = version ws.success = False ws.run_forever() print("leaving") print "==============" if ws.success: print "Smoke test was successful" else: print "Smoke test failed." print "=============="
def start(self): self.closed = False websocket.enableTrace(True) ws = websocket.WebSocketApp(self.websocket_link, on_open=self.on_open, on_error=self.on_error, on_close=self.on_close, on_message=self.on_message) ws_thread = threading.Thread(target = ws.run_forever) ws_thread.start() self.ws = ws self.ws_thread = ws_thread
def open_connection(): websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://exp.endoflow.com:3102/socket", on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever()
def __init__(self, host, room_id, player_id, credential, poker_player): websocket.enableTrace(True) self.host = host self.state = WantedPhaseHandler.CONNECTING self.pb = ParamsBuilder(player_id, room_id, credential) self.wanted_handler = WantedPhaseHandler(self.pb) self.poker_handler = PokerPhaseHandler(self.pb, poker_player) self.close_handler = CloseHandler(self.pb)
def create_ws(self): websocket.enableTrace(True) self.ws = websocket.WebSocketApp(host, on_message = self.on_ws_message, on_error = self.on_ws_error, on_close = self.on_ws_close) self.ws.on_open = self.on_ws_open self.ws.run_forever()
def app(self): websocket.enableTrace( True ) app = websocket.WebSocketApp(self.socketio_url, on_message = self.on_message, on_error = self.on_error, on_close = self.on_close) app.on_open = self.on_open app.run_forever()
def test_websocket_advance(): websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://192.168.14.7:8888/echo", on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever()
def setUp(self): ws.enableTrace(TRACEABLE) WebSocketAppTest.keep_running_open = WebSocketAppTest.NotSetYet() WebSocketAppTest.keep_running_close = WebSocketAppTest.NotSetYet() WebSocketAppTest.get_mask_key_id = WebSocketAppTest.NotSetYet()
def start_bot(self): """ Signal that we are connected to the Webex Teams Service. Hang around waiting for disconnection request """ try: bot = self.bot print(bot.bot_identifier.displayName) url = bot.device_info['webSocketUrl'] print("Opening websocket connection to %s" % websocket) websocket.enableTrace(True) print("Creating Connection") wsk = websocket.create_connection(url) print(wsk) bot.wsk=wsk print('Connection Created') bot.wsk.on_open = bot.on_open msg = {'id': str(uuid.uuid4()), 'type': 'authorization', 'data': { 'token': 'Bearer ' + bot._bot_token } } bot.wsk.send(json.dumps(msg)) while True: in_data = bot.wsk.recv() message = json.loads(in_data.decode('utf-8')) if message['data']['eventType'] != 'conversation.activity': print('Ignoring msg where Event Type is not conversation.activity') continue print(message) activity = message['data']['activity'] #print(activity) if activity['verb'] == 'cardAction': msg = bot.webex_teams_api.attachment_actions.get(activity['id']) pmsg =bot.webex_teams_api.messages.get(activity['parent']['id']) cmd = self.process_card_action() x=threading.Thread(target=cmd, args=(msg,pmsg,activity,)) x.start() continue if activity['verb'] != 'post': print('Ignoring message where the verb is not type "post"') continue teams_msg = bot.webex_teams_api.messages.get(activity['id']) if teams_msg.personEmail in bot.bot_identifier.emails: print('Ignoring message from myself') continue txt = teams_msg.text botName = bot.bot_identifier.displayName print('Message from %s: %s\n' % (teams_msg.personEmail,txt)) if txt.find(botName) != -1: txt = (txt[len(botName):]).strip() elif txt.find(botName.split(" ")[0]) != -1: txt = (txt[len(botName.split(" ")[0]):]).strip() txt = ((txt.lower()).replace(" ", "")).strip() if txt in self.commands: print("CMD FOUND") command = self.process_command(txt, teams_msg) print(command) x=threading.Thread(target=command, args=(teams_msg,activity)) x.start() except KeyboardInterrupt: print("Interrupt received, shutting down..") bot.wsk.shutdown() return True
def run_request_historical_kline(self, symbol, period, start_epoch, end_epoch, requested_counter=1): """ 请求 KLine 历史数据,直到数据完结 Get the symbol‘s candlestick data by subscription """ websocket.enableTrace(False) ws = websocket.create_connection(self.HUOBIPRO_WEBSOCKET_URL, timeout=10) # QUANTAXIS 系统定义的时间跟火币网WebSocket 接口的有一点偏差 day 火币叫 1day,hour 火币定义为 # 60min,需要查表映射转换。 reqParams = {} reqParams['req'] = requestStr = "market.%s.kline.%s" % ( symbol, self.Huobi2QA_FREQUENCE_DICT[period]) reqParams['from'] = start_epoch reqParams['to'] = end_epoch reqParams['id'] = requestIdx = "%s_#%d" % (self.gen_ws_id( symbol, period), int(random() * 100)) self.__batchReqJobs[requestStr] = QA_Fetch_Job(symbol, period) self.__batchReqJobs[requestStr].withParams( { "req": requestStr, "id": requestIdx, "from": int(start_epoch), }, symbol, self.Shifting_Time(period), QA_Fetch_Job_Type.REQUEST) data = json.dumps(reqParams).encode() QA_util_log_info( 'Sending Message: request kline {:s} part#{} {:s} to {:s}'.format( symbol, requested_counter, QA_util_timestamp_to_str(reqParams['from'])[2:16], QA_util_timestamp_to_str(reqParams['to'])[2:16])) ws.send(data) message = ws.recv() unzipped_data = gzip.decompress(message).decode() msg_dict = json.loads(unzipped_data) ws.close() if (('status' in msg_dict) and (msg_dict['status'] == 'ok') and ('data' in msg_dict)): QA_util_log_info( 'Data message match! Save symbol:{:s} with freq {:s}'.format( symbol, msg_dict['rep'])) # 处理返回的行情数据 ohlcvData = pd.DataFrame(columns=[ 'symbol', 'market', 'type', 'time_stamp', 'open', 'high', 'low', 'close', 'amount', 'trade', 'volume' ]) for t in range(len(msg_dict['data'])): ohlcvData = ohlcvData.append( { 'symbol': symbol, # stock ID 'market': 'huobi', 'type': self.Huobi2QA_FREQUENCE_DICT[period], 'time_stamp': msg_dict['data'][t]['id'], # timestamp 'open': msg_dict['data'][t]['open'], # open, 'high': msg_dict['data'][t]['high'], # high, 'low': msg_dict['data'][t]['low'], # low, 'close': msg_dict['data'][t]['close'], # close, 'amount': msg_dict['data'][t]['amount'], # volume 'trade': msg_dict['data'][t]['count'], # volume 'volume': msg_dict['data'][t]['vol'], # amount }, ignore_index=True) if (len(ohlcvData) == 0): # 火币网的 WebSocket 接口机制很奇特,返回len(data)==0 # 就说明已经超越这个交易对的上架时间,不再有更多数据了。 # 当前 Symbol Klines 抓取已经结束了 #print(QA_util_timestamp_to_str(reqParams['from'])[2:16], 'Return None') return None else: # 归一化数据字段,转换填充必须字段,删除多余字段 GMT+8 ohlcvData['date'] = pd.to_datetime( ohlcvData['time_stamp'], unit='s').dt.tz_localize( 'UTC').dt.tz_convert('Asia/Shanghai') ohlcvData['date'] = ohlcvData['date'].dt.strftime('%Y-%m-%d') ohlcvData['datetime'] = pd.to_datetime( ohlcvData['time_stamp'], unit='s').dt.tz_localize( 'UTC').dt.tz_convert('Asia/Shanghai') ohlcvData['datetime'] = ohlcvData['datetime'].dt.strftime( '%Y-%m-%d %H:%M:%S') ohlcvData['date_stamp'] = pd.to_datetime( ohlcvData['date']).astype(np.int64) // 10**9 ohlcvData['created_at'] = int( time.mktime(datetime.now().utctimetuple())) ohlcvData['updated_at'] = int( time.mktime(datetime.now().utctimetuple())) QA_util_log_info( "rep: %s, id: %s, return %d kiline bar(s)." % (msg_dict['rep'], msg_dict['id'], len(ohlcvData))) return ohlcvData
def __init__(self, event_handler, url, reconnect_handler=None, log_level=None, daemon=True, reconnect_interval=10, socket_kwargs=None, **thread_kwargs): self.event_handler = event_handler self.url = url self.reconnect_handler = reconnect_handler or (lambda: None) self.socket = None self.socket_id = "" self.event_callbacks = defaultdict(list) self.disconnect_called = False self.needs_reconnect = False self.default_reconnect_interval = reconnect_interval self.reconnect_interval = reconnect_interval self.socket_kwargs = socket_kwargs or dict() self.pong_timer = None self.pong_received = False self.pong_timeout = 30 self.bind("pusher:connection_established", self._connect_handler) self.bind("pusher:connection_failed", self._failed_handler) self.bind("pusher:pong", self._pong_handler) self.bind("pusher:ping", self._ping_handler) self.bind("pusher:error", self._pusher_error_handler) self.state = "initialized" self.logger = logging.getLogger(self.__module__) # create a new logger if log_level: self.logger.setLevel(log_level) if log_level == logging.DEBUG: websocket.enableTrace(True) # From Martyn's comment at: # https://pusher.tenderapp.com/discussions/problems/36-no-messages-received-after-1-idle-minute-heartbeat # "We send a ping every 5 minutes in an attempt to keep connections # alive..." # This is why we set the connection timeout to 5 minutes, since we can # expect a pusher heartbeat message every 5 minutes. Adding 5 sec to # account for small timing delays which may cause messages to not be # received in exact 5 minute intervals. self.connection_timeout = 305 self.connection_timer = None self.ping_interval = 120 self.ping_timer = None Thread.__init__(self, **thread_kwargs) self.daemon = daemon
def main(): start_time = time.time() args = parse_args() if args.verbose > 1: websocket.enableTrace(True) options = {} if args.proxy: p = urlparse(args.proxy) options["http_proxy_host"] = p.hostname options["http_proxy_port"] = p.port if args.origin: options["origin"] = args.origin if args.subprotocols: options["subprotocols"] = args.subprotocols opts = {} if args.nocert: opts = {"cert_reqs": ssl.CERT_NONE, "check_hostname": False} if args.headers: options['header'] = map(str.strip, args.headers.split(',')) ws = websocket.create_connection(args.url, sslopt=opts, **options) if args.raw: console = NonInteractive() else: console = InteractiveConsole() print("Press Ctrl+C to quit") def recv(): try: frame = ws.recv_frame() except websocket.WebSocketException: return websocket.ABNF.OPCODE_CLOSE, None if not frame: raise websocket.WebSocketException("Not a valid frame %s" % frame) elif frame.opcode in OPCODE_DATA: return frame.opcode, frame.data elif frame.opcode == websocket.ABNF.OPCODE_CLOSE: ws.send_close() return frame.opcode, None elif frame.opcode == websocket.ABNF.OPCODE_PING: ws.pong(frame.data) return frame.opcode, frame.data return frame.opcode, frame.data def recv_ws(): while True: opcode, data = recv() msg = None if six.PY3 and opcode == websocket.ABNF.OPCODE_TEXT and isinstance( data, bytes): data = str(data, "utf-8") if not args.verbose and opcode in OPCODE_DATA: msg = data elif args.verbose: msg = "%s: %s" % (websocket.ABNF.OPCODE_MAP.get(opcode), data) if msg is not None: if args.timings: console.write(str(time.time() - start_time) + ": " + msg) else: console.write(msg) if opcode == websocket.ABNF.OPCODE_CLOSE: break thread = threading.Thread(target=recv_ws) thread.daemon = True thread.start() if args.text: ws.send(args.text) while True: try: message = console.read() ws.send(message) except KeyboardInterrupt: return except EOFError: time.sleep(args.eof_wait) return
def audio_text(): audio_input_filepath = "/home/baicaitong/trashbin_project_webapi/audioee" output_text = "./out1.txt" #input_filepath默认为./audioee,output_text为翻译出来的内荣保存在out1.txt中,随后被删除 #返回的是翻译出的文字 class Ws_Param(object): # 初始化 def __init__(self, APPID, APIKey, APISecret, AudioFile): self.APPID = APPID self.APIKey = APIKey self.APISecret = APISecret self.AudioFile = AudioFile # 公共参数(common) self.CommonArgs = {"app_id": self.APPID} # 业务参数(business),更多个性化参数可在官网查看 self.BusinessArgs = { "domain": "iat", "language": "zh_cn", "accent": "mandarin", "vinfo": 1, "vad_eos": 10000 } # 生成url def create_url(self): url = 'wss://ws-api.xfyun.cn/v2/iat' # 生成RFC1123格式的时间戳 now = datetime.now() date = format_date_time(mktime(now.timetuple())) # 拼接字符串 signature_origin = "host: " + "ws-api.xfyun.cn" + "\n" signature_origin += "date: " + date + "\n" signature_origin += "GET " + "/v2/iat " + "HTTP/1.1" # 进行hmac-sha256进行加密 signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'), digestmod=hashlib.sha256).digest() signature_sha = base64.b64encode(signature_sha).decode( encoding='utf-8') authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % ( self.APIKey, "hmac-sha256", "host date request-line", signature_sha) authorization = base64.b64encode( authorization_origin.encode('utf-8')).decode(encoding='utf-8') # 将请求的鉴权参数组合为字典 v = { "authorization": authorization, "date": date, "host": "ws-api.xfyun.cn" } # 拼接鉴权参数,生成url url = url + '?' + urlencode(v) # print("date: ",date) # print("v: ",v) # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致 # print('websocket url :', url) return url # 收到websocket消息的处理 def on_message(ws, message): try: code = json.loads(message)["code"] sid = json.loads(message)["sid"] if code != 0: errMsg = json.loads(message)["message"] print("sid:%s call error:%s code is:%s" % (sid, errMsg, code)) else: data = json.loads(message)["data"]["result"]["ws"] #print(json.loads(message)) # result = "" # for i in data: # for w in i["cw"]: # result += w["w"] #cc=json.dumps(data, ensure_ascii=False) phase = '' for x in range(len(data)): phase += data[x]['cw'][0]['w'] #print(phase) tt = str(phase) #将识别的内容保存进文件 with open(output_text, 'a') as file_object: file_object.write(tt) except Exception as e: print("receive msg,but parse exception:", e) # 收到websocket错误的处理 def on_error(ws, error): print("### error:", error) # 收到websocket关闭的处理 def on_close(ws): print("### closed ###") # 收到websocket连接建立的处理 def on_open(ws): def run(*args): frameSize = 8000 # 每一帧的音频大小 intervel = 0.04 # 发送音频间隔(单位:s) status = STATUS_FIRST_FRAME # 音频的状态信息,标识音频是第一帧,还是中间帧、最后一帧 with open(wsParam.AudioFile, "rb") as fp: while True: buf = fp.read(frameSize) # 文件结束 if not buf: status = STATUS_LAST_FRAME # 第一帧处理 # 发送第一帧音频,带business 参数 # appid 必须带上,只需第一帧发送 if status == STATUS_FIRST_FRAME: d = { "common": wsParam.CommonArgs, "business": wsParam.BusinessArgs, "data": { "status": 0, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), 'utf-8'), "encoding": "raw" } } d = json.dumps(d) ws.send(d) status = STATUS_CONTINUE_FRAME # 中间帧处理 elif status == STATUS_CONTINUE_FRAME: d = { "data": { "status": 1, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), 'utf-8'), "encoding": "raw" } } ws.send(json.dumps(d)) # 最后一帧处理 elif status == STATUS_LAST_FRAME: d = { "data": { "status": 2, "format": "audio/L16;rate=16000", "audio": str(base64.b64encode(buf), 'utf-8'), "encoding": "raw" } } ws.send(json.dumps(d)) time.sleep(1) break # 模拟音频采样间隔 time.sleep(intervel) ws.close() thread.start_new_thread(run, ()) input_filename = "input.pcm" # 麦克风采集的语音输入 # 输入文件的path in_path = audio_input_filepath + input_filename get_audio.get_audio(in_path) # 测试时候在此处正确填写相关信息即可运行 time1 = datetime.now() wsParam = Ws_Param(APPID='5d668d4d', APIKey='ff5288cd3fc22ec336b567694e277450', APISecret='25d50b0ee0404f9ea83d611e32e35303', AudioFile=in_path) websocket.enableTrace(False) wsUrl = wsParam.create_url() ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) time2 = datetime.now() print(time2 - time1) with open(output_text, 'r') as file_object: phase = file_object.readlines() #print(len(phase)) if len(phase) == 1: if len(phase[0]) >= 4: text = phase[0][:4] else: text = phase[0] else: text = '0' os.remove(output_text) return text
def setUp(self): ws.enableTrace(TRACEABLE)
def __init__( self, app_token: str, logger: Optional[Logger] = None, web_client: Optional[WebClient] = None, auto_reconnect_enabled: bool = True, ping_interval: float = 10, concurrency: int = 10, trace_enabled: bool = False, http_proxy_host: Optional[str] = None, http_proxy_port: Optional[int] = None, http_proxy_auth: Optional[Tuple[str, str]] = None, proxy_type: Optional[str] = None, on_open_listeners: Optional[List[Callable[[WebSocketApp], None]]] = None, on_message_listeners: Optional[ List[Callable[[WebSocketApp, str], None]] ] = None, on_error_listeners: Optional[ List[Callable[[WebSocketApp, Exception], None]] ] = None, on_close_listeners: Optional[List[Callable[[WebSocketApp], None]]] = None, ): self.app_token = app_token self.logger = logger or logging.getLogger(__name__) self.web_client = web_client or WebClient() self.default_auto_reconnect_enabled = auto_reconnect_enabled self.auto_reconnect_enabled = self.default_auto_reconnect_enabled self.ping_interval = ping_interval self.wss_uri = None self.message_queue = Queue() self.message_listeners = [] self.socket_mode_request_listeners = [] self.current_session = None self.current_session_runner = IntervalRunner( self._run_current_session, 0.5 ).start() self.current_app_monitor_started = False self.current_app_monitor = IntervalRunner( self._monitor_current_session, self.ping_interval ) self.closed = False self.connect_operation_lock = Lock() self.message_processor = IntervalRunner(self.process_messages, 0.001).start() self.message_workers = ThreadPoolExecutor(max_workers=concurrency) # NOTE: only global settings is provided by the library websocket.enableTrace(trace_enabled) self.http_proxy_host = http_proxy_host self.http_proxy_port = http_proxy_port self.http_proxy_auth = http_proxy_auth self.proxy_type = proxy_type self.on_open_listeners = on_open_listeners or [] self.on_message_listeners = on_message_listeners or [] self.on_error_listeners = on_error_listeners or [] self.on_close_listeners = on_close_listeners or []
def __init__(self, address, dbname): self.sendLock = threading.Lock() self.sendReqLock = threading.Lock() self.responseLock = threading.Lock() self.ws_send_lock = threading.Lock() self.response = None self.reqid = None self.isMasterNode = False # db client = MongoClient() db = client[dbname] self.filesCollection = db["files"] self.operations = db["operations"] if self.operations.find().count() == 0: self.operationTime = 0 else: self.operationsTime = self.operations.find().sort("time", pymongo.DESCENDING)[0]["time"] # start socket def on_message(ws, message): print "message:" print message res = json.loads(message) if res["uuid"] != self.reqid: # req from manager if res["url"] == "/master-node": # manager update master node self.isMasterNode = res["data"] self.send_msg(json.dumps({ "uuid": res["uuid"], "status": "OK", })) return if res["url"] == "/db" and res["method"] == "get": self.send_msg(json.dumps({ "uuid": res["uuid"], "data": list(self.filesCollection.find({},{"_id": False})), "time": time.time(), "status": "OK", }, default=json_util.default,indent=4)) return if res["url"] == "/operations" and res["method"] == "get": lastOperationTime = res["time"] self.send_msg(json.dumps({ "uuid": res["uuid"], "data": list(self.operations.find({"time": {"$gt": lastOperationTime}}, {"_id": False}) .sort("time", pymongo.DESCENDING) ), "status": "OK", }, default=json_util.default,indent=4)) return if res["url"] == "/operations" and res["method"] == "post": self.operations.insert_one(res["data"]) self.operationTime = res["data"]["time"] self.exec_operation(res["data"]) self.send_msg(json.dumps({ "uuid": res["uuid"], "status": "OK", }, default=json_util.default,indent=4)) return else: # res from server self.response = res self.responseLock.release() def on_error(ws, error): print error def on_close(ws): print "### closed ###" def on_open(ws): print "Open" pass websocket.enableTrace(True) self.ws = websocket.WebSocketApp(address, on_message=on_message, on_error=on_error, on_close=on_close) self.ws.on_open = on_open
exit() # connect_websocket() def on_error(ws, error): log_to_file(f"ERROR - {error}") exit() # ws.close() # connect_websocket() def on_close(ws): log_to_file('CLOSE') exit() def on_open(ws): log_to_file('OPEN') if __name__ == "__main__": websocket.enableTrace(DEBUG_WS) try: connect_websocket() except Exception as err: if DEBUG: print(err) print("connect failed")
def initiate(self): websocket.enableTrace(True) self.ws = websocket.WebSocketApp("ws://"+self.ip+"/pubsub",on_message = self.on_message,on_error = self.on_error,on_close = self.on_close) self.ws.on_open = self.on_open self.ws.run_forever(ping_timeout=10)
def on_error(ws, error): print(datetime.now(),"on_error",error) def on_close(ws): print(datetime.now(),"on_close") def on_open(ws): ws.send("Hello World") print(datetime.now(),"on_open") if __name__ == "__main__": import websocket websocket.enableTrace(True) # 打印额外信息,属调试功能 # url = "ws://echo.websocket.org/" # 本地并没有这样一个websocket服务器,所以会连接不上,然后会尝试重连 url = "ws://localhost:8001/" ws = ReconnectWebsocketClient(url, on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close) # 重连5次,若为负数,则无限次尝试重连 ws.setReconnectTimes(5) # ws.setReconnectTimes(-1) # 每次重连时间间隔为10s
def run(): debug = False lap_count_dict = {'type': 'lap_count', 'current_lap': 0} eng_toggle_dict = {'type': 'eng_toggle', 'toggle': False} veh_status_dict = {'type': 'engine_stat', 'timestamp': time.clock(), 'running': False, 'rpm': 0, 'speed': 0, 'temp': 0, 'fuel_flow': 0, 'pressure': 0} log_control_dict = {'timestamp': time.clock(), 'type': '', 'recording': False} ax_control_dict = {'type': 'ax_control', 'timestamp': time.clock(), 'source': 'nil', # nil, ax_controller or web 'wipers': False, # 'ptt': False, 'horn': False, 'headlight': False, 'sig_l': False, 'sig_r': False, 'brake': False, 'hazard': False } cam_dict = {'frame': bytearray(), 'running': False } # LCM Handling def eng_toggle_handler(channel, data): msg = eng_toggle_t.decode(data) eng_toggle_dict['toggle'] = msg.toggle def lap_count_handler(channel, data): msg = lap_count_t.decode(data) lap_count_dict['current_lap'] = msg.current_lap def cam_feed_handler(channel, data): msg = cam_feed_t.decode(data) cam_dict['running'] = msg.feed_running cam_dict['frame'] = msg.frame def ax_control_handler(channel, data): msg = ax_control_t.decode(data) ax_control_dict['source'] = msg.source ax_control_dict['wipers'] = msg.wipers # ax_control_dict['ptt'] = msg.ptt ax_control_dict['headlight'] = msg.headlight ax_control_dict['horn'] = msg.horn ax_control_dict['sig_l'] = msg.sig_l ax_control_dict['sig_r'] = msg.sig_r ax_control_dict['brake'] = msg.brake ax_control_dict['hazard'] = msg.hazard def eng_status_handler(channel, data): # global veh_status_dict msg = veh_status_t.decode(data) veh_status_dict['timestamp'] = time.clock() veh_status_dict['running'] = msg.running veh_status_dict['rpm'] = msg.rpm veh_status_dict['speed'] = msg.speed veh_status_dict['temp'] = msg.temp veh_status_dict['fuel_flow'] = msg.fuel_flow veh_status_dict['pressure'] = msg.pressure def log_control_handler(channel, data): global log_control_dict msg = log_control_t.decode(data) log_control_dict['timestamp'] = time.clock() log_control_dict['recording'] = msg.recording if msg.recording: log_control_dict['type'] = 'log_begin' else: log_control_dict['type'] = 'log_end' # LCM object and subscriptions lc = lcm.LCM() eng_sub = lc.subscribe("eng_status", eng_status_handler) cam_sub = lc.subscribe("cam_feed", cam_feed_handler) ax_sub = lc.subscribe("ax_control", ax_control_handler) # Websockets def on_message(ws, message): print(message) def on_error(ws, error): print(error) def on_close(ws): print ('Connection to EVOS_WEB closed.') def on_open(ws): print('Connection to EVOS_WEB established.') def send_video_frame(frame): return ws.send(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') def runner(*args): # global veh_status_dict print('Websocket runner started.') try: # to prevent sending duplicates old_veh_status_dict = {} old_frame = bytearray() while True: rfds, wfds, efds = select.select([lc.fileno()], [], [], 1.5) if rfds: lc.handle() # Log recording # log_record_json = json.dumps(log_record_dict) # ws.send(log_record_json) # Camera feed if cam_dict['running'] and old_frame != cam_dict['frame']: send_video_frame(cam_dict['frame']) old_frame = cam_dict['frame'] # Vehicle status veh_status_json = json.dumps(veh_status_dict) ws.send(veh_status_json) # Engine toggle ws.send(json.dumps(eng_toggle_dict)) # Lap Count ws.send(json.dumps(lap_count_dict)) else: if debug: print("Message queue empty...") except KeyboardInterrupt: ws.close() pass except websocket.WebSocketConnectionClosedException: pass thread.start_new_thread(runner, ()) websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://127.0.0.1:8000/", on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open while True: try: ws.run_forever() print 'Attempting to reconnect in 5s...' time.sleep(5) except KeyboardInterrupt: pass
def enable_trace(self, traceable): if len(self.logger.handlers) > 0: websocket.enableTrace(traceable, self.logger.handlers[0])
def set_trace(self, trace): if trace: websocket.enableTrace(True) # for debugging connection issues
new_req = cfg.request_queue.get() time.sleep(1) while not cfg.battle_message_queue.empty(): new_msg = cfg.battle_message_queue.get() # Random AI (Temporary) valid_choice = helper.process_request(new_req) if not valid_choice[0]: continue result = np.random.choice(valid_choice[0]) ws.send(cfg.game_state["room_id"] + "|/" + result + valid_choice[1]) time.sleep(1) ws.close() _thread.start_new_thread(run, ()) _thread.start_new_thread(run_gui, ()) _thread.start_new_thread(run_ai, ()) if __name__ == "__main__": websocket.enableTrace(True) # default : True ws = websocket.WebSocketApp("ws://sim.smogon.com:8000/showdown/websocket", on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever()
if __name__ == "__main__": sock_adress = "wss://data.tradingview.com/socket.io/websocket?from=chart%2FrP0mQCuj%2F&date=2018_12_18-13_13" cookie = "__utmc=226258911; __utmz=226258911.1545273193.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); sessionid=hlmwt7p6rq6n9hwlprs9evhy61qist4l; cachec=undefined; etg=undefined; km_ni=bingpoli%40gmail.com; km_ai=bingpoli%40gmail.com; km_lv=x; _sp_ses.cf1a=*; km_vs=1; __utma=226258911.1361885574.1545273193.1545279384.1545285783.4; __utmt=1; _sp_id.cf1a=525edd29-fcb4-4ec7-bfb7-ad818db89660.1545273193.4.1545288293.1545281747.8a5590d1-8cc4-47bd-8ef0-9e83eb9d983d; kvcd=1545288293893; __utmb=226258911.58.1.1545288294975" socket_key = "m3TyFV0OnFlomon/Sn8LuQ==" headers = ["Accept-Encoding:gzip, deflate, br", "Accept-Language:zh-CN,zh;q=0.9", "Cache-Control:no-cache", "Connection:Upgrade", "Cookie:{}".format(cookie), "Host:data.tradingview.com", "Origin:https://cn.tradingview.com", "Pragma:no-cache", "Sec-WebSocket-Extensions:permessage-deflate; client_max_window_bits", "Sec-WebSocket-Key:{}".format(socket_key), "Sec-WebSocket-Version:13", "Upgrade:websocket", "User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36", ] # websocket.enableTrace(True) websocket.enableTrace(False) ws = websocket.WebSocketApp(sock_adress, header=headers, on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever(ping_timeout=30)
def bulk_getWikiDataLIST(self, parseResultLIST, indexWithPOS=True): ''' 取出斷詞結果中的 WikiData 標記文字。此處指的是 KNOWLEDGE_wikiData 標記的條目名稱。 每個句子內的條目名稱為一個 list。 ''' resultLIST = [ self.POS.getWikiDataLIST(x, indexWithPOS) for x in parseResultLIST ] return resultLIST if __name__ == "__main__": PORT = 8964 URL = "127.0.0.1" BulkSize = 20 enableTrace(False) userDefinedDICT = {"地球人類補完計劃": ["人類補完計劃", "人類再生計劃", "補完計劃"]} inputLIST = open("{}/as_test_1k.utf8".format( os.path.dirname(os.path.abspath(__file__))), "r", encoding="UTF-8").read().split("\n")[:20] articut = WS_Articut(url=URL, port=PORT, bulkSize=BulkSize) startTime = time.time() # 一次一句 N=1 for inputSTR in inputLIST: resultDICT = articut.parse(inputSTR, "lv2") pprint(resultDICT) pprint(articut.getContentWordLIST(resultDICT))
def eva(): if request.method == 'GET': return render_template("audio_evaluation.html") else: #post #获取文件 file = request.files.get("file") result = json.loads(request.form['result']) category = result[0]["category"] #评测类型 text = result[0]["text"] #评测文本内容 if not file: return render_template("audio_evaluation.html") #获取文件名 filepath = "static/" + file.filename #将文件写入到服务器 file.save(filepath) #调用讯飞的语音评测接口,实现语音评测功能 wsParam = Ws_Param(APPID=APPID, APISecret=APISecret, APIKey=APIKey, AudioFile=filepath, Category=category, Text=text) websocket.enableTrace(False) wsUrl = wsParam.create_url() #鉴权 info_list = [] #存储结果 # 收到websocket消息的处理 def on_message(ws, message): try: code = json.loads(message)["code"] sid = json.loads(message)["sid"] status = json.loads(message)["data"]["status"] if code != 0: errMsg = json.loads(message)["message"] print("sid:%s call error:%s code is:%s" % (sid, errMsg, code)) else: #获取返回的结果 if status == 2: #数据的获取 result = str( base64.b64decode( json.loads(message)["data"]["data"]), "UTF-8") print(result) doc = parseString(result) collection = doc.documentElement #获取xml文档对象 if collection.getElementsByTagName( "read_sentence") != []: #语句评测 node = collection.getElementsByTagName( "read_sentence")[1] flag = 0 elif collection.getElementsByTagName( "read_chapter") != []: #篇章 node = collection.getElementsByTagName( "read_chapter")[1] flag = 0 elif collection.getElementsByTagName( "read_syllable") != []: #字 node = collection.getElementsByTagName( "read_syllable")[1] flag = 1 else: node = collection.getElementsByTagName( "read_word")[1] flag = 1 if flag == 0: info_list.append( {"准确度": node.getAttribute("accuracy_score")}) #准确度 info_list.append( {"整体印象分": node.getAttribute("emotion_score")}) #整体印象分 info_list.append( {"流畅度分": node.getAttribute("fluency_score")}) #流畅度分 info_list.append( {"完整度分": node.getAttribute("integrity_score")}) #完整度分 info_list.append( {"声韵分": node.getAttribute("phone_score")}) #声韵分 info_list.append( {"调型分": node.getAttribute("tone_score")}) #调型分 info_list.append( {"总分": node.getAttribute("total_score")}) #声韵分 info_list.insert( 0, {"时长": node.getAttribute("time_len")}) #时长 #字:read_syllable #词:read_word #句子:read_sentence except Exception as e: print("receive msg,but parse exception:", e) ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close) # 收到websocket连接建立的处理--连接到服务器之后触发open事件 def on_open(ws): def run(*args): frameSize = 8000 # 每一帧的音频大小 intervel = 0.04 # 发送音频间隔(单位:s) status = STATUS_FIRST_FRAME # 音频的状态信息,标识音频是第一帧,还是中间帧、最后一帧 #参数上传阶段 d = { "common": wsParam.CommonArgs, "business": wsParam.BusinessArgs, "data": { "status": 0, "data": "" } } d = json.dumps(d) #转换为json字符串 ws.send(d) #音频上传阶段 with open(wsParam.AudioFile, "rb") as fp: #读取音频文件,上传到语音评测的接口 while True: buf = fp.read(frameSize) # 文件结束 if not buf: status = STATUS_LAST_FRAME # 第一帧处理 # 发送第一帧音频,带business参数 if status == STATUS_FIRST_FRAME: d = { "business": { "cmd": "auw", "aus": 1, "aue": "lame" }, "data": { "status": 1, "data": str(base64.b64encode(buf), 'utf-8') } } d = json.dumps(d) ws.send(d) status = STATUS_CONTINUE_FRAME # 中间帧处理 elif status == STATUS_CONTINUE_FRAME: d = { "business": { "cmd": "auw", "aus": 2, "aue": "lame" }, "data": { "status": 1, "data": str(base64.b64encode(buf), 'utf-8') } } ws.send(json.dumps(d)) # 最后一帧处理 elif status == STATUS_LAST_FRAME: d = { "business": { "cmd": "auw", "aus": 4, "aue": "lame" }, "data": { "status": 2, "data": str(base64.b64encode(buf), 'utf-8') } } ws.send(json.dumps(d)) time.sleep(1) break # 模拟音频采样间隔 time.sleep(intervel) ws.close() thread.start_new_thread(run, ()) ws.on_open = on_open ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE}) return render_template("eva_result.html", result=info_list)
def __init__(self, debug=False): super(SocketIO, self).__init__() websocket.enableTrace(True) self.__ws = websocket.WebSocketApp("ws://192.168.1.111:3000/socket.io/?EIO=3&transport=polling") if debug: self.__debug()
socketio.send(message) def on_message(ws, message): print(message) #emit('echo', message, namespace='/stockdata', broadcast=True, include_self=False) connect(message) def on_error(ws, error): print(error) def on_close(ws): print("### closed ###") def on_open(ws): ws.send('{"type":"subscribe","symbol":"TSLA"}') #^GSPC if __name__ == "__main__": websocket.enableTrace(True) ws = websocket.WebSocketApp("wss://ws.finnhub.io?token=" + os.environ['FINHUB_SECRET_KEY'], on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever() socketio.run(app, debug=True)
def ws_listen(on_transcation, on_block): def ping(*args): time.sleep(30) print(">>> Ping...") ws.send('2') def subscribe(*args): ws.send('2probe') def on_message(ws, message): #print("message received:\n{}".format(message)) if message == "3probe": print("Subscribing to inv...") ws.send("5") ws.send('425["subscribe", "inv"]') if message == '42["subscribed"]': thread.start_new_thread(ping, ()) if message == "3": print("<<< Pong...") thread.start_new_thread(ping, ()) if '["block",' in message: hash = message.replace('42["block","', '') hash = hash.replace('"]', '') if on_block is not None: on_block(hash) #pprint(digi.block(hash)) if '["tx"' in message: tx_info = message.replace('42["tx",', '') tx_info = tx_info.replace(']', '') if on_transcation is not None: on_transcation(json.loads(tx_info)) #print(txid) def on_error(ws, error): print("error") print(error) def on_close(ws): print("### Socket Closed ###") def on_open(ws): print("### Socket Opened ###") thread.start_new_thread(subscribe, ()) millis = int(round(time.time() * 1000)) r = requests.get( API_URL + "socket.io/?EIO=2&transport=polling&t={}-0".format(millis)) sid = r.headers['Set-Cookie'].split('io=')[1] websocket.enableTrace(True) ws = websocket.WebSocketApp( WS_URL + "socket.io/?EIO=2&transport=websocket&sid={}".format(sid), on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever()
def _init_socket(self): def _on_message(ws, message): message = json.loads(message) if(message[0]["channel"] == '/meta/disconnect'): pass elif(message[0]["channel"] == "/meta/handshake"): self._client_id = message[0]["clientId"] send_obj = [{"channel": "/meta/connect", "connectionType": "websocket", "advice": {"timeout": 0}, "clientId": message[0]["clientId"]}] self._send(ws, send_obj) elif(message[0]["channel"] == '/meta/connect'): send_obj = [{"channel": "/meta/connect", "clientId": self._client_id, "connectionType": 'websocket' }] self._send(ws, send_obj) elif(message[0]["channel"] == "/meta/subscribe"): self._subscriptions[message[0]["subscription"] ]["successful"] = message[0]["successful"] elif(message[0]["channel"] in self._subscriptions.keys()): if(self._subscriptions[message[0]["channel"]]["successful"]): # If is_class, call _callback, else call function if(self._subscriptions[message[0]["channel"]]['is_class']): self._subscriptions[message[0]["channel"]]["callback"]._callback( message[0]["data"]) else: self._subscriptions[message[0]["channel"]]["callback"]( message[0]["data"]) def _on_error(ws, error): print(error) def _on_close(ws): print("Socket Closed") def _on_open(ws): def run(*args): auth_message = [{"advice": {"timeout": 60000, "interval": 0}, "channel": "/meta/handshake", "ext": {"subscriptionId": self._push_subscription_id}, "minimumVersion": "1.0", "supportedConnectionTypes": ["websocket", "long-polling", "callback-polling"], "version": "1.0"}] self._send(ws, auth_message) thread.start_new_thread(run, ()) websocket.enableTrace(False) self._socket = websocket.WebSocketApp(SOCKET_URL, on_message=_on_message, on_error=_on_error, on_close=_on_close, on_open=_on_open)
def my_hotbit(): def on_message(ws, message): def receiv(*args): while True: rep2 = zlib.decompress(message, 16 + zlib.MAX_WBITS) rep2 = str(rep2, 'utf-8') rep2 = json.loads(rep2) # print(rep2, '\n', '\n') now = dt.datetime.now() print(now.strftime("%H:%M:%S")) print(rep2, '\n', '\n') if rep2['method'] != 'depth.update': pass else: # print('#################',rep2['params'][2]) if rep2['params'][0] == 'False': pass else: if 'bids' not in rep2['params'][1]: pass elif 'asks' not in rep2['params'][1]: pass else: if rep2['params'][2] == 'PZMBTC': b = rep2['params'][1]["bids"][:5] a = rep2['params'][1]["asks"][:5] # print('############################', rep2['params'][1]["asks"][:2]) # print(rep2, '\n', '\n') # print('########### BBB :',b) # print('########### BBB full:', rep2['params'][1]["bids"]) # # hb = OrderedDict(sorted(b.items(), key=lambda t: t[1]), reverse=False) # hbb = dict((k, v) for k, v in hb.items() if v > 0.1) # # ha = OrderedDict(sorted(a.items(), key=lambda t: t[0]), reverse=True) # haa = dict((k, v) for k, v in ha.items() if v > 0.1) # bh = float(list(hbb.keys())[0]) # ba = float(list(haa.keys())[0]) # # # print(bh) # # print(ba) # # if bh > ba: # del hbb[bh] # else: # pass Hot_buy = {} for i in b: if not Hot_buy: Hot_buy.update({i[0]: float(i[1])}) else: if i[0] == 'reverse': pass else: sump = float(i[1]) + float( list(Hot_buy.values())[-1]) Hot_buy.update({i[0]: float(sump)}) Hot_sell = {} for i in a: if not Hot_sell: Hot_sell.update({i[0]: float(i[1])}) else: if i[0] == 'reverse': pass else: sump = float(i[1]) + float( list(Hot_sell.values())[-1]) Hot_sell.update( {i[0]: float(sump)}) Hot_PU = [] for k, v in Hot_sell.items(): Hot_PU.append( ('hot', 'BTC', 'PZM', 'buy', k, v)) for k, v in Hot_buy.items(): Hot_PU.append( ('hot', 'PZM', 'BTC', 'sell', k, v)) columns = [ 'birga', 'valin', 'valout', 'direction', 'rates', 'volume' ] df = pd.DataFrame(Hot_PU, columns=columns) # print(df) os.remove(main_path_data + "\\hot_bd_PB.csv") df.to_csv(main_path_data + "\\hot_bd_PB.csv", index=False) elif rep2['params'][2] == 'PZMUSDT': # if [*rep2['params'][1].keys()][0] == 'asks': b = rep2['params'][1]["bids"][:5] a = rep2['params'][1]["asks"][:5] # now = dt.datetime.now() # print(now.strftime("%H:%M:%S")) # print('############################', rep2['params'][1]["asks"][:2]) # print(rep2, '\n', '\n') # print('########### USD BBB :', b) # print('########### USD BBB full:', rep2['params'][1]["bids"]) # # hb = OrderedDict(sorted(b.items(), key=lambda t: t[1]), reverse=False) # hbb = dict((k, v) for k, v in hb.items() if v > 0.1) # # ha = OrderedDict(sorted(a.items(), key=lambda t: t[0]), reverse=True) # haa = dict((k, v) for k, v in ha.items() if v > 0.1) # # bh = float(list(hbb.keys())[0]) # ba = float(list(haa.keys())[0]) # # print(bh) # print(ba) # # # if bh > ba: # del hbb[bh] # else: # pass Hot_buy = {} for i in b: if not Hot_buy: if float(i[1]) < 0.1: pass else: Hot_buy.update({i[0]: float(i[1])}) else: sump = float(i[1]) + float( list(Hot_buy.values())[-1]) Hot_buy.update({i[0]: float(sump)}) Hot_sell = {} for i in a: if not Hot_sell: Hot_sell.update({i[0]: float(i[1])}) else: sump = float(i[1]) + float( list(Hot_sell.values())[-1]) Hot_sell.update({i[0]: float(sump)}) Hot_PU = [] for k, v in Hot_sell.items(): Hot_PU.append( ('hot', 'USDT', 'PZM', 'buy', k, v)) for k, v in Hot_buy.items(): Hot_PU.append( ('hot', 'PZM', 'USDT', 'sell', k, v)) columns = [ 'birga', 'valin', 'valout', 'direction', 'rates', 'volume' ] df = pd.DataFrame(Hot_PU, columns=columns) # print(df) os.remove(main_path_data + "\\hot_bd_PU.csv") df.to_csv(main_path_data + "\\hot_bd_PU.csv", index=False) # else: # pass else: pass time.sleep(1) thread.start_new_thread(receiv, ()) # # print(message) # print(zlib.decompress(message, 16 + zlib.MAX_WBITS)) # # print('Compressed data: ', json.load(message)) def on_error(ws, error): print(error) def on_close(ws): print("### closed ###") def on_open(ws): def run(*args): msg = data ws.send(msg) print('################# SEND ##################') while True: time.sleep(1) ws.close() print("thread terminating...") thread.start_new_thread(run, ()) # if __name__ == "__main__": while True: websocket.enableTrace(True) ws = websocket.WebSocketApp('wss://ws.hotbit.io', on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever() time.sleep(1)
def __init__(self, *args, url=None, timeout=None, sslopt=None, http_proxy_host=None, http_proxy_port=None, http_proxy_auth=None, http_no_proxy=None, reconnect_interval=None, log_level=None, **kwargs): """Initialize a WebSocketConnection Instance. :param data_q: Queue(), connection to the Client Class :param args: args for Thread.__init__() :param url: websocket address, defaults to v2 websocket. :param http_proxy_host: proxy host name. :param http_proxy_port: http proxy port. If not set, set to 80. :param http_proxy_auth: http proxy auth information. tuple of username and password. :param http_no_proxy: host names, which doesn't use proxy. :param timeout: timeout for connection; defaults to 10s :param reconnect_interval: interval at which to try reconnecting; defaults to 10s. :param log_level: logging level for the connection Logger. Defaults to logging.INFO. :param kwargs: kwargs for Thread.__ini__() """ # Queue used to pass data up to BTFX client self.q = Queue() # Connection Settings self.socket = None self.url = url if url else 'wss://api.bitfinex.com/ws/2' self.sslopt = sslopt if sslopt else {} # Proxy Settings self.http_proxy_host = http_proxy_host self.http_proxy_port = http_proxy_port self.http_proxy_auth = http_proxy_auth self.http_no_proxy = http_no_proxy # Dict to store all subscribe commands for reconnects self.channel_configs = OrderedDict() # Connection Handling Attributes self.connected = Event() self.disconnect_called = Event() self.reconnect_required = Event() self.reconnect_interval = reconnect_interval if reconnect_interval else 10 self.paused = Event() # Setup Timer attributes # Tracks API Connection & Responses self.ping_timer = None self.ping_interval = 120 # Tracks Websocket Connection self.connection_timer = None self.connection_timeout = timeout if timeout else 10 # Tracks responses from send_ping() self.pong_timer = None self.pong_received = False self.pong_timeout = 30 self.log = logging.getLogger(self.__module__) if log_level == logging.DEBUG: websocket.enableTrace(True) self.log.setLevel(level=log_level if log_level else logging.INFO) # Call init of Thread and pass remaining args and kwargs Thread.__init__(self) self.daemon = True