def send_message(self, command, value): """Generic send message.""" from websocket import _exceptions ws_auth = False for attempt in range(5): try: websocket = self._connection( 'wss://{host_uri}/{device_set_endpoint}'.format( host_uri=self.HOST_URI, device_set_endpoint=self.DEVICE_SET_ENDPOINT), timeout=self.REQUEST_TIMEOUT) auth_mssg = json.dumps({ 'jsonrpc': '2.0', 'id': 3, 'method': 'srvWebSocketAuth', 'params': { 'varName': self.username, 'apiKey': self.api_key } }) websocket.send(auth_mssg) result = websocket.recv() except Exception as ex: print("Exception during websocket authentification") websocket.close() else: ws_auth = True break if (ws_auth == True): for attempt in range(5): try: pay_load = json.dumps({ 'jsonrpc': '2.0', 'method': 'gdoModuleCommand', 'params': { 'msgType': 16, 'moduleType': 5, 'portId': 7, 'moduleMsg': { command: value }, 'topic': self.device_id } }) websocket.send(pay_load) pay_load = "" result = websocket.recv() except Exception as ex: print("Exception during sending message") websocket.close() else: break websocket.close()
def testProxyConnect(self): ws = websocket.WebSocket() ws.connect("ws://127.0.0.1:" + LOCAL_WS_SERVER_PORT, http_proxy_host="127.0.0.1", http_proxy_port="8899", proxy_type="http") ws.send("Hello, Server") server_response = ws.recv() self.assertEqual(server_response, "Hello, Server") # self.assertEqual(_start_proxied_socket("wss://api.bitfinex.com/ws/2", OptsList(), proxy_info(http_proxy_host="127.0.0.1", http_proxy_port="8899", proxy_type="http"))[1], ("api.bitfinex.com", 443, '/ws/2')) self.assertEqual( _get_addrinfo_list( "api.bitfinex.com", 443, True, proxy_info(http_proxy_host="127.0.0.1", http_proxy_port="8899", proxy_type="http")), (socket.getaddrinfo("127.0.0.1", 8899, 0, socket.SOCK_STREAM, socket.SOL_TCP), True, None)) self.assertEqual( connect( "wss://api.bitfinex.com/ws/2", OptsList(), proxy_info(http_proxy_host="127.0.0.1", http_proxy_port=8899, proxy_type="http"), None)[1], ("api.bitfinex.com", 443, '/ws/2'))
def receive_messages(q, websocket, ignore_pong=True, donotdie=True): logger = logging.getLogger(__name__) while True: try: msg = json.loads(websocket.recv()) if msg['type'] == 'pong' and ignore_pong: continue else: q.put(msg) raise RuntimeError except ssl.SSLError as e: if e.errno == 2: logger.debug( "Something went wrong in the message receiver: {}".format( e), exc_info=True) continue except Exception as e: if donotdie: logger.debug( "Something went wrong in the message receiver: {}".format( e), exc_info=True) continue else: logger.exception(e) raise e
def listen(websocket, user, cookie): blank_string='' while(1): result = websocket.recv() print "hit" blank_string += blank_string+time.ctime(time.time())+'\n'+json.dumps(json.loads(result), indent=2)+'\n\n' f = open('Sub_Output.txt','w') f.write(blank_string) f.close() key = str((json.loads(result))["subscriptionId"])[3:-2] #checks the event that the subscription ID we received is mapped tp #if we have a fault event, this will extract which tenant the fault was triggered by and then update the user of the change in health score if subDict[key] == 'fault': time.sleep(20) # we need to look into how to handle the delay-- the apic itself takes a while to update-- im fine leaving a buffer time for now print "\n\n\n\n++++++++++++++++Event Generated+++++++++++++++++\n" print "Event: "+subDict[str(json.loads(result)["subscriptionId"])[3:-2]] temp = str(json.loads(result)["imdata"][0]["faultDelegate"]["attributes"]["dn"]).split('/') print "dn --> "+temp[0]+'/'+temp[1] url = "https://10.122.143.24/api/mo/"+temp[0]+'/'+temp[1]+".json?rsp-subtree-include=health" response = get(url, user, cookie) print "Tenant Score Change: "+str(json.loads(response.text)["imdata"][0]['fvTenant']['children'][0]['healthInst']['attributes']['chng']) print "New Tenant Health Score: "+str(json.loads(response.text)["imdata"][0]['fvTenant']['children'][0]['healthInst']['attributes']['cur']) print "\n++++++++++++++++++++++++++++++++++++++++++++++++\n\n"
def binance_test_uri_length(query): websocket = create_connection("wss://stream.binance.com:9443/stream?streams=" + query) while True: result = websocket.recv() websocket.close() print("Received '%s'\r\n" % result) break
def __check_response__(websocket=None, count=0): while True: try: response = websocket.recv() rep = json.loads(response) if "error" in rep: return rep elif "id" in rep: if rep["id"] == count: return rep elif rep["method"] == "status_update": continue else: # Unknown return return rep except: print("An error occured on receiving") return None
def send_jsonrpc_command(websocket: websocket.WebSocket, cmd: dict) -> tuple[bool, dict]: """ Send a jsonrpc command, wait for the response and return it. """ cmd_id = random.randint(10000, 90000) cmd_json = {"jsonrpc": "2.0", "id": cmd_id, **cmd} logging.debug(f"sending cmd: {cmd} id: {cmd_id}") websocket.send(json.dumps(cmd_json)) while True: ret = websocket.recv() ret_json = json.loads(ret) if ret_json["id"] == cmd_id: return "result" in ret_json, ret_json else: # print('waiting for ', my_cmd_id) pass
import click_spinner import websocket websocket = websocket.WebSocket() websocket.connect('ws://0.0.0.0:8000/api/stt/ws') try: print('Performing speech-to-text with WebSocket...') with click_spinner.spinner(): with open('audio/8455-210777-0068.wav', mode='rb') as file: websocket.send('{"power":1000, "paris":-1000}') audio = file.read() websocket.send_binary(audio) result = websocket.recv() print() print(result) websocket.close() except Exception as ex: print(ex)
def receive(self): return websocket.recv()