def monitor_pb(self): first_run = True obj = {} ident = self.config['pb_key'] url = "wss://stream.pushbullet.com/websocket/%s" % ident websocket = yield from websockets.connect(url) irc.util.log("websocket %s connected" % websocket) last = 0 while True: obj = yield from websocket.recv() if obj is None: irc.util.log("websocket %s closed" % websocket) irc.util.log("reconnecting") websocket = yield from websockets.connect(url) irc.util.log("websocket %s connected" % websocket) obj = json.loads(obj) if first_run or obj['type'] == 'tickle' and obj['subtype'] == 'push': first_run = False irc.util.log("event stream recieved %s" % obj) pushes = yield from irc.aiopb.get_pushes(ident, last) #pushes = irc.pb.get_pushes(ident, last) irc.util.log("%s new pushes" % len(pushes)) if len(pushes) > 0 and 'modified' in pushes[0]: last = pushes[0]['modified'] for push in pushes: ret = yield from irc.aiopb.push_to_s(push) self.privmsg(ret) status = yield from irc.aiopb.dismiss_push(push, ident) if status == 200: irc.util.log("dismissed %s" % push['iden']) else: irc.util.log("error dismissing %s: %s" % (push['iden'], status))
def hello(): websocket = yield from websockets.connect('ws://192.168.1.106:81/') ws = yield from websockets.connect('ws://192.168.1.107:81/') while True: try: option = input("What Do you want to do? ") if option == "Led on": yield from websocket.send(option) print("> {}".format(option)) greeting = yield from websocket.recv() print("< {}".format(greeting)) elif option == "Led off": yield from websocket.send(option) print("> {}".format(option)) greeting = yield from websocket.recv() print("< {}".format(greeting)) elif option == "Lamp on": yield from websocket.send(option) print("> {}".format(option)) greeting = yield from websocket.recv() print("< {}".format(greeting)) elif option == "Lamp off": yield from websocket.send(option) print("> {}".format(option)) greeting = yield from websocket.recv() print("< {}".format(greeting)) elif option == "Computer on": yield from ws.send(option) print("> {}".format(option)) greeting = yield from ws.recv() print("< {}".format(greeting)) elif option == "Computer off": yield from ws.send(option) print("> {}".format(option)) greeting = yield from ws.recv() print("< {}".format(greeting)) elif option == "Exit" or option == "quit": break else: print("Invalid option") finally: print("") yield from websocket.close() yield from ws.close()
def listen_for_event_messages(self, options, loop): attempts = 10 websocket = None while not websocket and attempts > 0: try: if options['reset_mc']: secure_client.delete_auth_tokens() ak, ak_id = secure_client.get_auth_tokens() ws_url = secure_client.get_websocket_url(ak, ak_id) websocket = yield from websockets.connect(ws_url) except Exception as e: attempts -= 1 logger.error(e) logger.error("Attempt failed to connect to Secure Systems websocket server") time.sleep(1) if not websocket: raise Exception("Could not connect to Secure Systems websocket server.") try: self.is_alive = True self.tasks.append(asyncio.ensure_future(self.alive(websocket))) while True: try: message = yield from websocket.recv() res = json.loads(message) logger.debug("Received push message from websocket", extra={'data': res}) if res['DataType'] == 0: process_push_data(res['Data']) else: logger.info("Received error from websocket", extra={'data': res}) logger.info("Restarting websocket listener") yield from websocket.close() secure_client.delete_auth_tokens() ak, ak_id = secure_client.get_auth_tokens() ws_url = secure_client.get_websocket_url(ak, ak_id) websocket = yield from websockets.connect(ws_url) except Exception as e: logger.warn('ConnectionClosed %s' % e) self.is_alive = False break except Exception as e: logger.warn('Could not connect: %s' % e) finally: logger.warn("Importer is stopping") if websocket: yield from websocket.close() self.is_alive = False
def connect(): global initTime, authkey_control, endpoint_control, user_id websocket = yield from websockets.connect(endpoint_control) content = [22085, user_id, authkey_control] ret = yield from messages.sendMsg(websocket, content, is_auth=True) ret = ret.split('"id"')[0][:-1] + "}" ret = json.loads(ret) if ret["error"] != None: print("CONTROL CHANNEL") print("Error:\t", ret["error"]) print("Error - Non-None error returned!") quit() curTime = str(datetime.now().strftime("%H.%M.%S")) + " - " + str(datetime.now().strftime("%D")) msg_to_send = "Bot online - Current Date/Time: {}".format(str(curTime)) ret_msg = yield from messages.sendMsg(websocket, msg_to_send) ret_msg = json.loads(ret_msg) yield from messages.close(websocket) websocket = yield from websockets.connect(endpoint) content = [channel, user_id, authkey] ret = yield from messages.sendMsg(websocket, content, is_auth=True) ret = ret.split('"id"')[0][:-1] + "}" ret = json.loads(ret) if ret["error"] != None: print("MAIN CHANNEL") print(ret["error"]) print("Error - Non-None error returned!") quit() if not args.nostartmsg: if int(datetime.now().strftime("%H")) < 12: # It's before 12 PM - morning timeStr = "mornin'" elif int(datetime.now().strftime("%H")) >= 12 and int(datetime.now().strftime("%H")) < 17: # It's afternoon timeStr = "afternoon" elif int(datetime.now().strftime("%H")) >= 17: # It's after 5 - evening timeStr = "evenin'" msg_to_send = "Top o' the {} to you!".format(timeStr) ret_msg = yield from messages.sendMsg(websocket, msg_to_send) yield from messages.close(websocket) else: yield from messages.close(websocket)
def hello(): websocket = '' try: websocket = yield from websockets.connect('ws://localhost:9000/') except: print("Can't initialize the connection") i = 0 while True: i+=1 print(i) try: dataJS = yield from websocket.recv() data = json.loads(dataJS) print("< {}".format(data)) if 'DataInfo' in data: for val in data['DataInfo']: logs.insert_one(val) elif 'DataInfoReq' in data: msg = {"DataInfo":[ { "id":40, "sname":"SOG", "lname":"Speed Over Ground", "unit":"Knts", "min":0, "max":99.9, "numInstances":2, "instanceInfo":[ {"inst":0, "location":0, "str":"Port" }, {"inst":1, "location":3, "str":"Starboard"}] }]} websocket.send(msg) elif 'export' in data: mongoExport() elif 'exit' in data: break except: print('No Connection Available') t.sleep(1) # try to (re)connect try: websocket = yield from websockets.connect('ws://localhost:9000/') except: pass yield from websocket.close()
def send_pl_id(conns): pl_id = 0 for conn in conns: websocket = yield from websockets.connect('ws://' + conn + '/') yield from websocket.send("pl_id:" + str(pl_id)) yield from websocket.close() pl_id += 1
def get_transactions(): blockchain_websocket = yield from websockets.connect(BLOCKCHAIN_URL) print("connecting to {}".format(BLOCKCHAIN_URL)) connection_text = '{"op": "unconfirmed_sub"}' yield from blockchain_websocket.send(connection_text) while True: resp = yield from blockchain_websocket.recv() resp_dict = json.loads(resp) ip_address = resp_dict['x']['relayed_by'] amount = BLOCKCHAIN_SCALING * sum([t['value'] for t in resp_dict['x']['out']]) pprint.pprint(resp_dict) print("IP: {0}, amount: {1} BTC".format(ip_address, amount)) location = yield from geolocate_ip(ip_address) pprint.pprint(location) if location['status'] != 'success': continue payload = dict( lat=location['lat'], lng=location['lon'], amount=amount ) pprint.pprint(payload) for client in clients: if client and client.open: yield from client.send(json.dumps(payload))
async def read(uri): print(uri) async with websockets.connect(uri) as websocket: while True: data = await websocket.recv() print(f"< {data}") print()
async def proxy(ws, path): try: if 'http' in path: target = path.replace('http://', 'ws://').replace('https://', 'wss://') async with websockets.connect(target) as ws2: while True: recver_task = asyncio.ensure_future(ws2.recv()) sender_task = asyncio.ensure_future(ws.recv()) done, pending = await asyncio.wait( [recver_task, sender_task], return_when=asyncio.FIRST_COMPLETED ) if recver_task in done: msg = recver_task.result() for patch in patches: msg = patch.call('onrecv', ws, msg) print("< {}".format(msg)) await ws.send(msg) else: recver_task.cancel() if sender_task in done: msg = sender_task.result() print("> {}".format(msg)) for patch in patches: msg = patch.call('onsend', ws, msg) await ws2.send(msg) else: sender_task.cancel() except websockets.exceptions.ConnectionClosed: pass
async def service_callback(): async with websockets.connect('ws://localhost:9090') as websocket: # advertise the message/topic await websocket.send("{ \"op\": \"advertise\",\ \"type\": \"vision_service/msg/NewFacialFeatures\",\ \"topic\": \"/roboy/cognition/vision/NewFacialFeatures\"\ }") i = 1 # counter for the service request IDs while True: float64[128] ff = 0 message["values"] = ff message["op"] = "service_response" message["id"] = "message:/roboy/cognition/vision/coordinates:" + str(i) message["service"] = "/roboy/cognition/vision/coordinates" i += 1 await websocket.send(json.dumps(message)) except Exception as e: logging.exception("Oopsie! Got an exception in vision/NewFacialFeatures") logging.basicConfig(level=logging.INFO) asyncio.get_event_loop().run_until_complete(service_callback())
def _ws_read(self): """Read from websocket.""" import websockets as wslib try: if not self._ws: self._ws = yield from wslib.connect(self._ws_url) _LOGGER.info("Connected to websocket at %s", self._ws_url) except Exception as ws_exc: # pylint: disable=broad-except _LOGGER.error("Failed to connect to websocket: %s", ws_exc) return result = None try: result = yield from self._ws.recv() _LOGGER.debug("Data from websocket: %s", result) except Exception as ws_exc: # pylint: disable=broad-except _LOGGER.error("Failed to read from websocket: %s", ws_exc) try: yield from self._ws.close() finally: self._ws = None return result
async def launch_shard(self, gateway, shard_id): try: coro = websockets.connect(gateway, loop=self.loop, klass=DiscordWebSocket, compression=None) ws = await asyncio.wait_for(coro, loop=self.loop, timeout=180.0) except Exception: log.info('Failed to connect for shard_id: %s. Retrying...', shard_id) await asyncio.sleep(5.0, loop=self.loop) return await self.launch_shard(gateway, shard_id) ws.token = self.http.token ws._connection = self._connection ws._dispatch = self.dispatch ws.gateway = gateway ws.shard_id = shard_id ws.shard_count = self.shard_count ws._max_heartbeat_timeout = self._connection.heartbeat_timeout try: # OP HELLO await asyncio.wait_for(ws.poll_event(), loop=self.loop, timeout=180.0) await asyncio.wait_for(ws.identify(), loop=self.loop, timeout=180.0) except asyncio.TimeoutError: log.info('Timed out when connecting for shard_id: %s. Retrying...', shard_id) await asyncio.sleep(5.0, loop=self.loop) return await self.launch_shard(gateway, shard_id) # keep reading the shard while others connect self.shards[shard_id] = ret = Shard(ws, self) ret.launch_pending_reads() await asyncio.sleep(5.0, loop=self.loop)
def hello(): websocket = yield from websockets.connect('ws://127.0.0.1:9021/') while True: yield from websocket.send('all') result = yield from websocket.recv() print(result)
async def bot(get, token=TOKEN): '''Create a bot that joins Slack.''' rtm = await api_call("rtm.start") assert 'ok' in rtm and rtm['ok'], "Error connecting to RTM." async with websockets.connect(rtm["url"]) as ws: while RUNNING: listener_task = asyncio.ensure_future(ws.recv()) producer_task = asyncio.ensure_future(get()) done, pending = await asyncio.wait( [listener_task, producer_task], return_when=asyncio.FIRST_COMPLETED ) for task in pending: task.cancel() if listener_task in done: message = listener_task.result() asyncio.ensure_future(consumer(message)) if producer_task in done: message = producer_task.result() await ws.send(message)
def mainloop(): ws = yield from websockets.connect('ws://localhost:8090/') entropy = struct.unpack("<Q", os.urandom(8))[0] rand = random.Random(entropy) my_account_id = rand.randrange(0, 90000) gpo_get = {"id":1, "method":"call", "params":[0, "get_objects", ["2.0.0"]]} dgpo_sub = {"id":2, "method":"call", "params":[0, "subscribe_to_objects", [111, ["2.1.0"]]]} acct_sub = {"id":3, "method":"call", "params":[0, "get_full_accounts", [222, ["1.2."+str(my_account_id)], True]]} yield from ws.send(json.dumps(gpo_get)) yield from ws.send(json.dumps(dgpo_sub)) yield from ws.send(json.dumps(acct_sub)) next_call_id = 4 def peek_random_account(): nonlocal next_call_id asyncio.get_event_loop().call_later(rand.uniform(0, 3), peek_random_account) peek_account_id = rand.randrange(0, 90000) acct_peek = {"id" : next_call_id, "method" : "call", "params": [0, "get_objects", [["1.2."+str(peek_account_id)], True]]} next_call_id += 1 yield from ws.send(json.dumps(acct_peek)) return yield from peek_random_account() while True: result = yield from ws.recv() #print(result) if result is None: break yield from ws.close()
async def send_message(msg_name, code_string): async with websockets.connect('ws://localhost:12345') as websocket: client_id = 4 data = code_string await websocket.send(str(client_id) + '|' + msg_name + '|' + code_string) print('Message sent!') response = await websocket.recv() a = response.split('|') name = a[0] if name == 'class': print('Registered Class') elif name == 'main': print('Registered main') elif name == 'run': output = a[1] errors = a[2] print('Output: \n%s\n' % output) print('Errors: \n%s\n' % errors) else: print(name) asyncio.ensure_future(keep_alive_client(websocket, 1))
def _command(self, msg): """Send a command to the tv.""" logger.debug('send command to %s', "ws://{}:{}".format(self.ip, self.port)); try: websocket = yield from websockets.connect( "ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect) except: logger.debug('command failed to connect to %s', "ws://{}:{}".format(self.ip, self.port)); return False logger.debug('command websocket connected to %s', "ws://{}:{}".format(self.ip, self.port)); try: yield from self._send_register_payload(websocket) if not self.client_key: raise PyLGTVPairException("Unable to pair") yield from websocket.send(json.dumps(msg)) if msg['type'] == 'request': raw_response = yield from websocket.recv() self.last_response = json.loads(raw_response) finally: logger.debug('close command connection to %s', "ws://{}:{}".format(self.ip, self.port)); yield from websocket.close()
def hello(): websocket = yield from websockets.connect("ws://localhost:8765/hello") # name = input("What's your name? ") name = "test" yield from websocket.send(name) # print("c:> {}".format(name)) greeting = yield from websocket.recv()
async def hello(): async with websockets.connect('ws://localhost:5678') as websocket: print("Please type username password") q = asyncio.Queue() asyncio.get_event_loop().add_reader(sys.stdin, got_stdin_data, q) if len(sys.argv) == 2: await websocket.send(sys.argv[1]) while True: listener_task = asyncio.ensure_future(websocket.recv()) producer_task = asyncio.ensure_future(q.get()) done, pending = await asyncio.wait( [listener_task, producer_task], return_when=asyncio.FIRST_COMPLETED ) if listener_task in done: message = listener_task.result() print("< {}".format(message)) else: listener_task.cancel() if producer_task in done: raw = producer_task.result() print("Sending {0}".format(raw)) await websocket.send(raw) else: producer_task.cancel()
def run(self, uri, code="print('Hello, world!')", interp='python3', filename='hello.py', argv=[]): try: websocket = yield from websockets.connect(uri) self.ws_protocol = websocket # Get the remote version string message = message_pb2.PrexMessage() message.type = message_pb2.PrexMessage.VERSION yield from websocket.send(message.SerializeToString()) payload = yield from self.ws_protocol.recv() message = message_pb2.PrexMessage() message.ParseFromString(payload) assert( message.type == message_pb2.PrexMessage.VERSION ) print( 'Prex server version: {}'.format(message.payload.decode()) ) message = message_pb2.PrexMessage() message.type = message_pb2.PrexMessage.LOAD_PROGRAM message_program = message_pb2.LoadProgram() message_program.filename = filename message_program.code = code message_program.interpreter = interp for arg in argv: new_arg = message_program.argv.append(arg) message.payload = message_program.SerializeToString() yield from websocket.send(message.SerializeToString()) yield from self.consumer() websocket.close() except Exception as exc: raise
def start(self): d = yield from self._fetch('rtm.start') if not d['ok']: raise SlackError(d.get('error')) self._init_login_data(d) log.debug(d) log.info('Channels: %s', ', '.join(self.channel_names.values())) log.info('Users: %s', ', '.join(self.user_names.values())) self.ws_url = d['url'] ws = yield from websockets.connect(self.ws_url) response_id = 1 while True: msg = yield from ws.recv() msg = json.loads(msg) log.debug('Recieved %s', msg) msg_type = msg.get('type') if msg_type == 'message': user_id = msg['user'] if user_id != self.bot_id: response = self._calculate_response(msg, response_id) if response: log.info('Sending %s', response) yield from ws.send(json.dumps(response)) response_id += 1 elif msg_type == 'channel_joined' or msg_type == 'group_joined': self._upsert_channel(msg['channel']) log.info('Channels: %s', ', '.join(self.channel_names.values()))
async def hello(): async with websockets.connect('ws://localhost:8080/ws') as websocket: while True: data = input(">") await websocket.send(data) msg = await websocket.recv() print('Message received from server:', msg)
def hello(): websocket = yield from websockets.connect('ws://localhost:8765/') name = input("What's your name? ") yield from websocket.send(name) print("> {}".format(name)) greeting = yield from websocket.recv() print("< {}".format(greeting))
def hello(): websocket = yield from websockets.connect('ws://localhost:8765/') while True: lat_lon_amount = (yield from websocket.recv()) if lat_lon_amount: stuff = json.loads(lat_lon_amount) pprint.pprint(stuff)
def hello(): websocket = yield from websockets.connect('ws://{}:{}/'.format(HOST, PORT)) name = input("What's your name? ") yield from websocket.send(name) print("> {}".format(name)) greeting = yield from websocket.recv() print("< {}".format(greeting))
def echo_ws(): websocket = yield from websockets.connect('ws://localhost:8765/') while True: data = yield from websocket.recv() if data is None: break print(data)
async def query(self): async with websockets.connect( StockUrl(account=Player.get().account, stock=Player.get().stock, is_execution=True).str()) as websocket: while True: # print(json.loads(await websocket.recv())) execution = json.loads(await websocket.recv()) await self.callback(execution)
def websocket_to_database(): try: websocket = yield from websockets.connect("wss://ws-feed.exchange.coinbase.com") except gaierror: db_logger.error('socket.gaierror - had a problem connecting to Coinbase feed') return yield from websocket.send('{"type": "subscribe", "product_id": "BTC-USD"}') while True: message = yield from websocket.recv() if message is None: file_logger.error('Websocket message is None!') break try: message = json.loads(message) except TypeError: db_logger.error('JSON did not load, see ' + str(message)) continue if message['type'] != 'match': continue new_message = Messages() for key in message: if hasattr(new_message, key): setattr(new_message, key, message[key]) else: db_logger.error(str(key) + ' is missing, see ' + str(message)) continue try: session.add(new_message) session.commit() except IntegrityError: session.rollback() except DatabaseError: file_logger.error('Database Error') session.rollback()
def ws_handler(self, url, handler): self.ws = yield from websockets.connect(url) self.running = True # Fix keepalives as long as we're ``running``. asyncio.async(self.ws_keepalive()) while True: content = yield from self.ws.recv() if content is None: break message = json.loads(content) if 'ok' in message: continue message_type = message['type'] type_handlers = self.handlers[message_type] for handler in itertools.chain(self.handlers[ALL], type_handlers): asyncio.async(handler(self, message)) self.running = False
async def query(self): async with websockets.connect(StockUrl(account=Player.get().account, stock=Player.get().stock, is_ticker_tape=True).str()) as websocket: while True: # print(json.loads(await websocket.recv())) quote = json.loads(await websocket.recv())['quote'] await self.callback(quote)
async def request(uri, data): async with websockets.connect(uri) as websocket: await websocket.send(data) return dict(json.loads(await websocket.recv()))
def reset(size): ws = yield from websockets.connect('ws://localhost:8000/reset/') ws.send(str(size)) yield from ws.wait_close()
async def start(): uri = "ws://192.168.114.18:8887" actor_info = { 'clazz' : '', 'name' : '', 'uuid' : None, 'parent_uuid' : None } port_info = { 'clazzname': '', 'Longitude': None, 'latitude': None, 'UTM East': None, 'UTM North': None, 'course': None, 'speed':[], 'rudderP': None, 'rpmP': None, 'rudderS': None, 'rpmS': None } port_name_ls = [] for name in port_info: port_name_ls.append(name) # port's name gps_gunnerus = actor_info.copy() gps_gunnerus['clazz'] = 'GPSController' gps_gunnerus['name'] = 'GPS1' gps_target_ship_1 = actor_info.copy() gps_target_ship_1['clazz'] = 'GPSController' gps_target_ship_1['name'] = 'Target Ship 1' gps_target_ship_2 = actor_info.copy() gps_target_ship_2['clazz'] = 'GPSController' gps_target_ship_2['name'] = 'Target Ship 2' gunnerus_thruster_port = actor_info.copy() gunnerus_thruster_port['clazz'] = 'ThrusterActor' gunnerus_thruster_port['name'] = 'Port' gunnerus_thruster_starboard = actor_info.copy() gunnerus_thruster_starboard['clazz'] = 'ThrusterActor' gunnerus_thruster_starboard['name'] = 'Starboard' actor_info_list = [gps_gunnerus, gps_target_ship_1, gps_target_ship_2, gunnerus_thruster_port, gunnerus_thruster_starboard] actor_list = [None for i in range(5)] async with websockets.connect(uri, ping_timeout=None) as websocket: while True: if not websocket.open: print('reconnecting') websocket = await websockets.connect(uri) else: resp = await websocket.recv() #print(f"{resp}") try: data_dic = json.loads(resp[resp.index('{'):]) for i in range(len(actor_list)): actor_info = actor_info_list[i] actor = await evaluate(data_dic, actor_info['clazz'], actor_info['name']) if actor != None: port_info['clazzname'] == actor_info['name'] for i in range(len(port_name_ls)): index = find_port_index_by_name(actor, 'output', port_name_ls[i].upper()) get_port_data_by_index(actor, 'output', index) port_info[][] except: traceback.print_exc() await sendmessage()
def connect(self): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) log.debug("Connecting to websocket") self.websocket = unasyncio( websockets.connect( self.bbb_server.replace("https", "wss") + "/html5client/sockjs/494/" + secrets.token_urlsafe(8) + "/websocket")) _ = self.recv() _ = self.recv() log.debug("Sending initial control messages") self.send({ 'msg': 'connect', 'version': '1', 'support': ['1', 'pre1', 'pre2'] }) self.send({ 'msg': 'method', 'method': 'userChangedLocalSettings', 'params': [{ 'application': { 'animations': True, 'chatAudioAlerts': False, 'chatPushAlerts': False, 'fallbackLocale': 'en', 'overrideLocale': None, 'userJoinAudioAlerts': False, 'userJoinPushAlerts': False, 'locale': 'en-US' }, 'audio': { 'inputDeviceId': 'undefined', 'outputDeviceId': 'undefined' }, 'dataSaving': { 'viewParticipantsWebcams': True, 'viewScreenshare': True } }], 'id': '1' }) self.send({ 'msg': 'method', 'method': 'validateAuthToken', 'params': [ self.bbb_info['meetingID'], self.bbb_info['internalUserID'], self.bbb_info['authToken'], self.bbb_info['externUserID'] ], 'id': '2' }) #for sub in ['annotations', 'breakouts', 'captions', 'current-user', 'group-chat', 'group-chat-msg', 'guestUser', 'local-settings', 'meetings', 'meetings', 'meeting-time-remaining', 'meteor_autoupdate_clientVersions', 'network-information', 'note', 'ping-pong', 'polls', 'presentation-pods', 'presentations', 'record-meetings', 'screenshare', 'slide-positions', 'slides', 'users', 'users', 'users-infos', 'users-settings', 'video-streams', 'voice-call-states', 'voiceUsers', 'whiteboard-multi-user']: for sub in [ 'annotations', 'current-user', 'group-chat', 'group-chat-msg', 'guestUser', 'local-settings', 'meetings', 'network-information', 'note', 'ping-pong', 'presentations', 'screenshare', 'slide-positions', 'slides', 'users', 'users-infos', 'video-streams', 'voice-call-states', 'voiceUsers' ]: log.debug("Subscribing to %s messages" % sub) self.send({ 'msg': 'sub', 'id': 'fnord-' + sub, 'name': sub, 'params': [] })
async def __aenter__(self) -> 'ROS': self._conn = websockets.connect(self._url) self._socket = await self._conn.__aenter__() return self
async def produce(message: str, host: str, port: int) -> None: async with websockets.connect(f"ws://{host}:{port}") as ws: await ws.send(message) await ws.recv()
async def main(): uri = "ws://localhost:5678" async with websockets.connect(uri) as websocket:
def create(cls, serial_id): my_config = util.Config() if serial_id is None: serial_id = my_config.linkbot logging.info( 'Creating async Linkbot handle to ID:{}'.format(serial_id)) logger = logging.getLogger('RBProxy.' + serial_id) self = cls(os.path.join(_dirname, 'robot_pb2.py'), logger=logger) serial_id = serial_id.upper() self._serial_id = serial_id self._loop = asyncio.get_event_loop() self.__daemon = _DaemonProxy(os.path.join(_dirname, 'daemon_pb2.py')) if my_config.use_websockets: self.__log('Creating Websocket connection to daemon...') protocol = yield from websockets.connect( 'ws://' + my_config.daemon_host[0] + ':' + my_config.daemon_host[1], loop=self._loop) else: self.__log('Creating tcp connection to daemon...') (transport, protocol) = yield from sfp.client.connect( my_config.daemon_host[0], my_config.daemon_host[1], loop=self._loop) self.__log('Daemon TCP connection established.') protocol.connection_lost = self.__connection_closed self.__daemon.set_protocol(protocol) self._daemon_protocol = protocol daemon_consumer = asyncio.ensure_future( self.__daemon_consumer(protocol)) self.__log('Initiating daemon handshake...') yield from asyncio.sleep(0.5) yield from self.__daemon.rb_connect() self.__log('Daemon handshake finished.') yield from asyncio.sleep(0.5) self.__log('Resolving serial id: ' + serial_id) args = self.__daemon.rb_get_args_obj('resolveSerialId') args.serialId.value = serial_id result_fut = yield from self.__daemon.resolveSerialId(args) tcp_endpoint = yield from result_fut if tcp_endpoint.status != rbcommon.OK: self.logger.warning('Could not connect to robot: {}'.format( rbcommon.Status.Name(tcp_endpoint.status))) raise RuntimeError('Could not connect to remote robot: {}'.format( rbcommon.Status.Name(tcp_endpoint.status))) self.__log('Connecting to robot endpoint:' + my_config.daemon_host[0] + ':' + str(tcp_endpoint.endpoint.port)) if my_config.use_websockets: linkbot_protocol = yield from websockets.client.connect( 'ws://' + my_config.daemon_host[0] + ':' + str(tcp_endpoint.endpoint.port), loop=self._loop) else: (_, linkbot_protocol) = \ yield from sfp.client.connect( tcp_endpoint.endpoint.address, tcp_endpoint.endpoint.port) self.__linkbot_consumer_handle = \ asyncio.ensure_future(self.__linkbot_consumer(linkbot_protocol)) self.__log('Connected to robot endpoint.') self._linkbot_protocol = linkbot_protocol self.__log('Sending connect request to robot...') yield from asyncio.sleep(0.5) yield from self.rb_connect() self.__log('Done sending connect request to robot.') #Get the form factor fut = yield from self.getFormFactor() result_obj = yield from fut self.form_factor = result_obj.value return self
def create(cls, serial_id): my_config = util.Config() if serial_id is None: serial_id = my_config.linkbot logging.info( 'Creating async Linkbot handle to ID:{}'.format(serial_id)) logger = logging.getLogger('RBProxy.' + serial_id) self = cls(load_pb2_file('daemon_pb2.py').robot__pb2, 'RobotProxy') serial_id = serial_id.upper() self._serial_id = serial_id self._loop = asyncio.get_event_loop() self.__daemon = Daemon() self.__daemon.on('receive', self.on_receive) if my_config.use_websockets: self.__log('Creating Websocket connection to daemon...') protocol = yield from websockets.connect( 'ws://' + my_config.daemon_host[0] + ':' + my_config.daemon_host[1], loop=self._loop) else: import sfp self.__log('Creating tcp connection to daemon...') (transport, protocol) = yield from sfp.client.connect( my_config.daemon_host[0], my_config.daemon_host[1], loop=self._loop) self.__log('Daemon TCP connection established.') protocol.connection_lost = self.__connection_closed self.__daemon.set_io(protocol) self._daemon_protocol = protocol ''' self.__log('Initiating daemon handshake...') yield from asyncio.sleep(0.5) yield from self.__daemon.rb_connect() self.__log('Daemon handshake finished.') ''' #yield from asyncio.sleep(0.5) self.__log('Resolving serial id: ' + serial_id) args = self.__daemon._pb_module.addRobotRefs.In() _serial_id = args.serialIds.add() _serial_id.value = serial_id result_fut = yield from self.__daemon.addRobotRefs(args) self.__log('Waiting for addRobotRefs result...') status_result = yield from result_fut self.__log('Waiting for addRobotRefs result...done') try: assert (status_result.status == self.__daemon._pb_module.OK) except: self.__log('Received unexpected status from daemon: {}'.format( repr(status))) raise return self
async def subscribe_without_login(url, channels): while True: try: async with websockets.connect(url) as ws: sub_param = {"op": "subscribe", "args": channels} sub_str = json.dumps(sub_param) await ws.send(sub_str) while True: try: res_b = await asyncio.wait_for(ws.recv(), timeout=25) except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed) as e: try: await ws.send('ping') res_b = await ws.recv() timestamp = get_timestamp() res = inflate(res_b).decode('utf-8') print(timestamp + res) continue except Exception as e: timestamp = get_timestamp() print(timestamp + "正在重连……") print(e) break timestamp = get_timestamp() res = inflate(res_b).decode('utf-8') print("time:" + timestamp) res = eval(res) try: process(res, timestamp) except Exception as e: print(traceback.format_exc()) print(e) # if 'event' in res: # continue # for i in res: # if 'depth' in res[i] and 'depth5' not in res[i]: # # 订阅频道是深度频道 # if res['action'] == 'partial': # for m in l: # if res['data'][0]['instrument_id'] == m['instrument_id']: # l.remove(m) # # 获取首次全量深度数据 # bids_p, asks_p, instrument_id = partial(res, timestamp) # d = {} # d['instrument_id'] = instrument_id # d['bids_p'] = bids_p # d['asks_p'] = asks_p # l.append(d) # # # 校验checksum # checksum = res['data'][0]['checksum'] # # print(timestamp + '推送数据的checksum为:' + str(checksum)) # check_num = check(bids_p, asks_p) # # print(timestamp + '校验后的checksum为:' + str(check_num)) # if check_num == checksum: # print("校验结果为:True") # else: # print("校验结果为:False,正在重新订阅……") # # # 取消订阅 # await unsubscribe_without_login(url, channels, timestamp) # # 发送订阅 # async with websockets.connect(url) as ws: # sub_param = {"op": "subscribe", "args": channels} # sub_str = json.dumps(sub_param) # await ws.send(sub_str) # timestamp = get_timestamp() # print(timestamp + f"send: {sub_str}") # # elif res['action'] == 'update': # for j in l: # if res['data'][0]['instrument_id'] == j['instrument_id']: # # 获取全量数据 # bids_p = j['bids_p'] # asks_p = j['asks_p'] # # 获取合并后数据 # bids_p = update_bids(res, bids_p, timestamp) # asks_p = update_asks(res, asks_p, timestamp) # # # 校验checksum # checksum = res['data'][0]['checksum'] # # print(timestamp + '推送数据的checksum为:' + str(checksum)) # check_num = check(bids_p, asks_p) # # print(timestamp + '校验后的checksum为:' + str(check_num)) # if check_num == checksum: # print("校验结果为:True") # else: # print("校验结果为:False,正在重新订阅……") # # # 取消订阅 # await unsubscribe_without_login(url, channels, timestamp) # # 发送订阅 # async with websockets.connect(url) as ws: # sub_param = {"op": "subscribe", "args": channels} # sub_str = json.dumps(sub_param) # await ws.send(sub_str) # timestamp = get_timestamp() # print(timestamp + f"send: {sub_str}") except Exception as e: timestamp = get_timestamp() print(timestamp + "连接断开,正在重连……") print(e) continue
async def test_websocket(server_port): async with websockets.connect( f"ws://127.0.0.1:{server_port}/test/websocket") as ws: await ws.send("hello,") assert await ws.recv() == '{"success": "ok"}'
def connect(self) -> None: def _wait(): for i in range(self.config.retry_wait_time): log.show_value( self.config, log.level.INFO, [ i18n.Prepare, i18n.Again, i18n.Connect, i18n.PTT, ], str(self.config.retry_wait_time - i) ) time.sleep(1) log.show_value( self.config, log.level.INFO, [ i18n.connect_core, ], i18n.Active ) if self.config.connect_mode == connect_mode.TELNET: log.show_value( self.config, log.level.INFO, i18n.ConnectMode, i18n.ConnectMode_Telnet ) elif self.config.connect_mode == connect_mode.WEBSOCKET: log.show_value( self.config, log.level.INFO, i18n.ConnectMode, i18n.ConnectMode_WebSocket ) connect_success = False global new_event_loop thread_id = threading.get_ident() for _ in range(2): try: if self.config.connect_mode == connect_mode.TELNET: if self.config.host == data_type.host_type.PTT1: self._core = telnetlib.Telnet('ptt.cc', self.config.port) elif self.config.host == data_type.host_type.PTT2: self._core = telnetlib.Telnet('ptt2.cc', self.config.port) else: self._core = telnetlib.Telnet('localhost', self.config.port) else: if thread_id not in new_event_loop: new_event_loop.append(thread_id) try: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) except Exception as e: pass if self.config.host == data_type.host_type.PTT1: self._core = asyncio.get_event_loop().run_until_complete( websockets.connect( 'wss://ws.ptt.cc/bbs/', origin='https://term.ptt.cc' ) ) elif self.config.host == data_type.host_type.PTT2: self._core = asyncio.get_event_loop().run_until_complete( websockets.connect( 'wss://ws.ptt2.cc/bbs', origin='https://term.ptt2.cc' ) ) else: self._core = asyncio.get_event_loop().run_until_complete( websockets.connect( 'wss://localhost', origin='https://term.ptt.cc' ) ) connect_success = True except Exception as e: traceback.print_tb(e.__traceback__) print(e) if self.config.host == data_type.host_type.PTT1: log.show_value( self.config, log.level.INFO, [ i18n.Connect, i18n.PTT, ], i18n.Fail ) else: log.show_value( self.config, log.level.INFO, [ i18n.Connect, i18n.PTT2, ], i18n.Fail ) _wait() continue break if not connect_success: raise exceptions.ConnectError(self.config)
async def connect_forever(): path = '/spotWS' url = BTSE_WSEndpoint + path async with websockets.connect(url) as websocket: # Authentication auth = gen_auth(keypair['API-KEY'], keypair['API-PASSPHRASE']) print("***** GEN AUTH: *****" + str(auth)) auth_payload = ujson.dumps(auth) await websocket.send(auth_payload) # Subscription - order notifications user_payload = subscription_payload() #ob_payload = orderbook_payload() trade_payload = tradehistory_payload() await websocket.send(ujson.dumps(user_payload)) #await websocket.send(ujson.dumps(ob_payload)) await websocket.send(ujson.dumps(trade_payload)) MESSAGE_TIMEOUT = 30.0 while True: try: response: Dict[Any] = await asyncio.wait_for( websocket.recv(), timeout=MESSAGE_TIMEOUT) print("\n======= WEBSOCKET DATA RECEIVED: ======= \n") print(response) code = get_event_responses(response) #print(f'Event status: {str(code)}') ''' if 'topic' in response: print(type(response)) r = ujson.loads(str(response)) topic = r['topic'] print(f'topic: {topic}') ''' if "topic" in response: r = ujson.loads(str(response)) if "orderBookApi" in r['topic']: process_orderbook_data(r) pp.pprint(r) elif "tradeHistoryApi" in r['topic']: # pp.pprint(r) data = r['data'] # pp.pprint(data) for trade in r["data"]: trade: Dict[Any] = trade print(trade) elif "notificationsApi" in r['topic']: print("notifications") data = r['data'] pp.pprint('data') else: print("No topic in response") print(response) #code = get_auth_responses(response) #print(type(code)) #print(code) except Exception as e: print(e) if ping_checker.check(): payload = {"op": "ping"} print("==== Keep Alive HEART BEAT === sending a ping: " + str(payload)) await websocket.send(ujson.dumps(payload))
def connect(cls, **kwargs): """Equivalent to `websockets.connect`, with `uri` and client preconfigured for EtherDelta""" if 'create_protocol' in kwargs: raise ValueError('`create_protocol` is preset to {}'.format(cls)) return websockets.connect(cls.URI, create_protocol=cls, **kwargs)
async def main(): async with websockets.connect('ws://localhost:9000/CP_1', subprotocols=['ocpp1.6']) as ws: await asyncio.gather(remote_start(ws))
async def main_logic(): async with websockets.connect('ws://127.0.0.1:8896') as websocket: await send_msg(websocket)
async def control(): while True: async with websockets.connect('ws://localhost:9989') as websocket: num = input("[tms_rc_bed control number] >") await websocket.send(num) print(f"> send {num}")
async def receive_client(target, id): async with websockets.connect(f'ws://{target}/receive/{id}') as websocket: for _ in range(100): msg = await websocket.recv() print(f"< {msg}")
async def __aenter__(self): if self.handler_binance_websocket_api_manager.is_stop_request( self.stream_id): self.handler_binance_websocket_api_manager.stream_is_stopping( self.stream_id) sys.exit(0) uri = self.handler_binance_websocket_api_manager.create_websocket_uri( self.channels, self.markets, self.stream_id, self.api_key, self.api_secret, symbol=self.symbol) if uri is False: # cant get a valid URI, so this stream has to crash error_msg = "Probably no internet connection?" logging.critical( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ") - " + " error: 5 - " + str(error_msg)) self.handler_binance_websocket_api_manager.stream_is_crashing( self.stream_id, str(error_msg)) self.handler_binance_websocket_api_manager.set_restart_request( self.stream_id) sys.exit(1) try: if isinstance(uri, dict): if uri['code'] == -2014 or uri['code'] == -2015 or uri[ 'code'] == -2008: # -2014 = API-key format invalid # -2015 = Invalid API-key, IP, or permissions for action # -2008 = Invalid Api-Key ID # cant get a valid listen_key, so this stream has to crash logging.critical( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ") - " + " error: 4 - " + str(uri['msg'])) try: del self.handler_binance_websocket_api_manager.restart_requests[ self.stream_id] except KeyError as error_msg: logging.debug( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ")" + " connecting to " + str(uri) + " error: 6 - " + str(error_msg)) except TypeError as error_msg: logging.error( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ")" + " connecting to " + str(uri) + " error: 3 - " + str(error_msg)) self.handler_binance_websocket_api_manager.stream_is_crashing( self.stream_id, str(uri['msg'])) if self.handler_binance_websocket_api_manager.throw_exception_if_unrepairable: raise StreamRecoveryError("stream_id " + str(self.stream_id) + ": " + str(uri['msg'])) sys.exit(1) except KeyError: logging.error("BinanceWebSocketApiConnection->__enter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ")" + " connecting to " + str(uri) + " error: 1") self._conn = connect( uri, ping_interval=20, close_timeout=10, extra_headers={ 'User-Agent': 'oliver-zehentleitner/unicorn-binance-websocket-api/' + self.handler_binance_websocket_api_manager.version }) try: try: self.handler_binance_websocket_api_manager.websocket_list[ self.stream_id] = await self._conn.__aenter__() except websockets.exceptions.InvalidMessage as error_msg: logging.error( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ") InvalidMessage " + str(error_msg)) self.handler_binance_websocket_api_manager.stream_is_crashing( self.stream_id, str(error_msg)) time.sleep(2) self.handler_binance_websocket_api_manager.set_restart_request( self.stream_id) sys.exit(1) except websockets.exceptions.InvalidStatusCode as error_msg: if "HTTP 429" in str(error_msg): logging.error( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ") InvalidStatusCode-HTTP429" + str(error_msg)) self.handler_binance_websocket_api_manager.stream_is_crashing( self.stream_id, str(error_msg)) time.sleep(2) self.handler_binance_websocket_api_manager.set_restart_request( self.stream_id) sys.exit(1) else: logging.error( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ") InvalidStatusCode" + str(error_msg)) while self.handler_binance_websocket_api_manager.stream_list[ self.stream_id]['payload']: payload = self.handler_binance_websocket_api_manager.stream_list[ self.stream_id]['payload'].pop(0) await self.send(json.dumps(payload, ensure_ascii=False)) self.handler_binance_websocket_api_manager.stream_list[ self.stream_id]['status'] = "running" self.handler_binance_websocket_api_manager.stream_list[ self.stream_id]['has_stopped'] = False try: if self.handler_binance_websocket_api_manager.restart_requests[ self.stream_id]['status'] == "restarted": self.handler_binance_websocket_api_manager.increase_reconnect_counter( self.stream_id) del self.handler_binance_websocket_api_manager.restart_requests[ self.stream_id] except KeyError: pass self.handler_binance_websocket_api_manager.set_heartbeat( self.stream_id) except ConnectionResetError as error_msg: logging.error( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ")" + " - ConnectionResetError - " + str(error_msg)) except OSError as error_msg: logging.critical( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ")" + " - OSError - " + str(error_msg)) self.handler_binance_websocket_api_manager.stream_is_crashing( self.stream_id, (str(error_msg))) self.handler_binance_websocket_api_manager.set_restart_request( self.stream_id) sys.exit(1) except socket.gaierror as error_msg: logging.critical( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ")" + " - No internet connection? " "- " + str(error_msg)) self.handler_binance_websocket_api_manager.stream_is_crashing( self.stream_id, (str(error_msg) + " - No internet connection?")) self.handler_binance_websocket_api_manager.set_restart_request( self.stream_id) sys.exit(1) except websockets.exceptions.InvalidStatusCode as error_msg: if "Status code not 101: 414" in str(error_msg): # Since we subscribe via websocket.send() and not with URI anymore, this is obsolete code I guess. self.handler_binance_websocket_api_manager.stream_is_crashing( self.stream_id, str(error_msg) + " --> URI too long?") logging.critical( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ")" + " - URI Too Long? - " + str(error_msg)) try: self.handler_binance_websocket_api_manager.websocket_list[ self.stream_id].close() except KeyError: pass sys.exit(1) elif "Status code not 101: 400" in str(error_msg): logging.critical( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ") " + str(error_msg)) elif "Status code not 101: 429" in str(error_msg): logging.error( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ") " + str(error_msg)) self.handler_binance_websocket_api_manager.stream_is_crashing( self.stream_id, str(error_msg)) time.sleep(2) self.handler_binance_websocket_api_manager.set_restart_request( self.stream_id) sys.exit(1) elif "Status code not 101: 500" in str(error_msg): logging.critical( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ") " + str(error_msg)) self.handler_binance_websocket_api_manager.stream_is_crashing( self.stream_id, str(error_msg)) sys.exit(1) else: logging.error( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ") " + str(error_msg)) try: self.handler_binance_websocket_api_manager.websocket_list[ self.stream_id].close() except KeyError: pass self.handler_binance_websocket_api_manager.stream_is_crashing( self.stream_id, str(error_msg)) self.handler_binance_websocket_api_manager.set_restart_request( self.stream_id) sys.exit(1) except websockets.exceptions.ConnectionClosed as error_msg: logging.error( "BinanceWebSocketApiSocket->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ") Exception ConnectionClosed " "Info: " + str(error_msg)) if "WebSocket connection is closed: code = 1006" in str(error_msg): self.handler_binance_websocket_api_manager.websocket_list[ self.stream_id].close() self.handler_binance_websocket_api_manager.stream_is_crashing( self.stream_id, str(error_msg)) sys.exit(1) else: logging.critical( "BinanceWebSocketApiConnection->await._conn.__aenter__(" + str(self.stream_id) + ", " + str(self.channels) + ", " + str(self.markets) + ") UnhandledException " "ConnectionClosed" + str(error_msg)) return self
async def __aenter__(self): self._conn = connect("wss://wsv1.1fox.com") self.websocket = await self._conn.__aenter__() return self
async def cf_sub(): global ws, bin_ws # Connect to CoinFLEX's websocket and subscribe to the orderbook, order and position channels. max_pos_timer = time.time() while True: async with websockets.connect(Env.ws_url) as ws: # Authenticate the websocket connection. await ws.send(json.dumps(await cfWS.auth(Env.api_key, Env.api_secret))) # Connect to the orderbook, order, and position channels. await ws.send(json.dumps(BVars.cf_markets)) login, markets, orders = False, False, False setup = False # Ensure all of the channels have been connected to prior to trading. while not setup: try: response = await ws.recv() msg = json.loads(response) BVars.logger.info("setup " + str(msg)) if "event" in msg and "success" in msg: if msg["event"] == "login" and msg["success"]: login = True if "channel" in msg: if ( msg["channel"] == "futures/depth:" + BVars.market and msg["event"] == "subscribe" ): markets = True if ( msg["channel"] == "order:" + BVars.market and msg["event"] == "subscribe" ): orders = True if ( msg["channel"] == "position:" + BVars.market and msg["event"] == "subscribe" ): positions = True if login and markets and orders: setup = True except Exception as error: BVars.logger.info("setup caught this error: " + repr(error)) BVars.logger.info("successfully connected to CoinFLEX") i = 1 while ws.open: await asyncio.sleep(3) # If reconnecting to Binance's websocket fails for over a minute (e.g. maintenance), kill the bot. if i > 20: BVars.logger.info("Halting Trading: Restarting Derp BLP") exit() # Use os.execv(__file__, sys.argv) if you would like to restart the bot completely instead. i += 1 # This is where the trading logic starts. while BVars.BIN_WS_FLAG: i = 1 try: # Await a message from CoinFLEX's websocket. response = await ws.recv() msg = json.loads(response) # Catch orders that may be cancelled by CancelAll. if "data" in msg and "table" in msg: if msg["table"] == "order": new_msg = msg["data"][0] BVars.logger.info("new_msg" + str(new_msg)) if ( new_msg["notice"] == "OrderClosed" and new_msg["status"] == "CANCELED_BY_USER" ): if ( new_msg["side"] == "BUY" and new_msg["clientOrderId"] == BVars.order_ids[0] ): BVars.BID_QUOTING_FLAG = False BVars.bid_id, BVars.working_bid, BVars.working_bidq = ( 0, 0, 0, ) continue elif ( new_msg["side"] == "SELL" and new_msg["clientOrderId"] == BVars.order_ids[1] ): BVars.ASK_QUOTING_FLAG = False BVars.ask_id, BVars.working_ask, BVars.working_askq = ( 0, 0, 0, ) continue elif ( new_msg["clientOrderId"] == BVars.order_ids[2] or new_msg["clientOrderId"] == BVars.order_ids[3] ): BVars.FLATTEN_FLAG = False BVars.FLATTEN_MOD_FLAG = False BVars.flatten_p, BVars.flatten_q, BVars.flatten_id = ( 0, 0, 0, ) continue # Parse new orderbook data and check for an OrderMatched message. if "data" in msg: msg = msg["data"][0] # Track CoinFLEX prices and check for position changes skip = await cfWS.parse_message(BVars, ws, msg, mgmt=False) if skip: continue # Ensure that position size isn't growing too large for your personal risk tolerance ;). if ( abs(BVars.working_position) >= BVars.max_position and time.time() > max_pos_timer + 30 ): BVars.logger.info("Max Position Reached") max_pos_timer = time.time() # Update active bids if the fair value of the contract has changed by 2 basis points. if ( BVars.BID_QUOTING_FLAG and BVars.working_position < BVars.max_position ): if ( BVars.mid * (1 - BVars.spread + 0.0002) <= BVars.working_bid or BVars.mid * (1 - BVars.spread - 0.0002) >= BVars.working_bid or BVars.working_bidq < BVars.bid_size * 0.5 ): # Calculate the new bid_price to use then cancel and replace the working order. bid_price = ( math.floor(BVars.mid * (1 - BVars.spread) * 2) / 2 ) await cfWS.CancelOrder( BVars, ws, BVars.bid_id, BVars.market ) await cfWS.PlaceOrder( BVars, ws, BVars.order_ids[0], BVars.market, "BUY", "LIMIT", BVars.bid_size, "MAKER_ONLY_REPRICE", bid_price, ) # cfModifyOrder(BVars, ws, BVars.bid_id, BVars.market, "BUY", BVars.bid_size, bid_price) # Update active asks if the fair value of the contract has changed by 2 basis points. if ( BVars.ASK_QUOTING_FLAG and BVars.working_position > -BVars.max_position ): if ( BVars.mid * (1 + BVars.spread + 0.0002) <= BVars.working_ask or BVars.mid * (1 + BVars.spread - 0.0002) >= BVars.working_ask or BVars.working_askq < BVars.ask_size * 0.5 ): # Calculate the new ask_price to use then cancel and replace the working order. ask_price = ( math.ceil(BVars.mid * (1 + BVars.spread) * 2) / 2 ) await cfWS.CancelOrder( BVars, ws, BVars.ask_id, BVars.market ) await cfWS.PlaceOrder( BVars, ws, BVars.order_ids[1], BVars.market, "SELL", "LIMIT", BVars.ask_size, "MAKER_ONLY_REPRICE", ask_price, ) # await cfModifyOrder(BVars, ws, BVars.ask_id, BVars.market, "SELL", BVars.ask_size, ask_price) # Place orders if there are no working orders. if not BVars.BIN_FIRST_RUN_FLAG: if ( not BVars.BID_QUOTING_FLAG and BVars.working_position < BVars.max_position ): # Calculate the bid_price to use then place an order. bid_price = ( math.floor(BVars.mid * (1 - BVars.spread) * 2) / 2 ) await cfWS.PlaceOrder( BVars, ws, BVars.order_ids[0], BVars.market, "BUY", "LIMIT", BVars.bid_size, "MAKER_ONLY_REPRICE", bid_price, ) if ( not BVars.ASK_QUOTING_FLAG and BVars.working_position > -BVars.max_position ): # Calculate the ask_price to use then place an order. ask_price = ( round(BVars.mid * (1 + BVars.spread) * 2) / 2 ) await cfWS.PlaceOrder( BVars, ws, BVars.order_ids[1], BVars.market, "SELL", "LIMIT", BVars.ask_size, "MAKER_ONLY_REPRICE", ask_price, ) except Exception as err: traceback.print_exc(file=sys.stdout) BVars.logger.info("error: CF WS loop failed " + repr(err)) await ws.close() # Binance's websocket has disconnected, cancel all working orders and wait to reconnect. if ( not bin_ws.open and (BVars.bid_id != 0 or BVars.ask_id != 0 or BVars.flatten_id != 0) ): cfRest.cancelAll(111, Env.rest_short, Env.rest_url, Env.api_key, Env.api_secret) BVars.working_bid, BVars.working_bidq, BVars.bid_id = 0, 0, 0 BVars.working_ask, BVars.working_askq, BVars.ask_id = 0, 0, 0 BVars.flatten_p, BVars.flatten_q, BVars.flatten_id = 0, 0, 0 BVars.BID_QUOTING_FLAG, BVars.ASK_QUOTING_FLAG, BVars.FLATTEN_FLAG = ( False, False, False, ) await asyncio.sleep(10) # CoinFLEX's websocket has disconnected, cancel all working orders and attempt to reconnect. cfRest.cancelAll(111, Env.rest_short, Env.rest_url, Env.api_key, Env.api_secret) await asyncio.sleep(5) BVars.working_bid, BVars.working_bidq, BVars.bid_id = 0, 0, 0 BVars.working_ask, BVars.working_askq, BVars.ask_id = 0, 0, 0 BVars.flatten_p, BVars.flatten_q, BVars.flatten_id = 0, 0, 0 BVars.BID_QUOTING_FLAG, BVars.ASK_QUOTING_FLAG, BVars.FLATTEN_FLAG = ( False, False, False, ) BVars.logger.info("error: CF WS disconnected, reconnecting")
async def hello(uri): async with websockets.connect(uri) as websocket: await websocket.send("Hello world!")
async def __aenter__(self): """ """ self._conn = websockets.connect(self.uri, subprotocols=['graphql-ws']) self.websocket = await self._conn.__aenter__() return self
async def sample_handler(): async with websockets.connect(uri=ws_url) as ws: while True: sample = Sample() sample.MergeFromString(await ws.recv()) on_sample(sample)
async def message(): async with websockets.connect("ws://127.0.0.1:1234") as socket: while True: p_s = input("Enter 1 to request server public key:") await socket.send(p_s) public_e = int(await socket.recv()) public_n = int(await socket.recv()) print('The public key of server is(e,n):', (public_e, public_n)) while True: try: p = int(input('Enter the value of prime number p = ')) except ValueError: print("InValid Input") continue if not isPrime(p): print("Enter a prime number") continue else: break while True: try: q = int(input('Enter the value of prime number q = ')) except ValueError: print("InValid Input") continue if not isPrime(q): print("Enter a prime number") continue else: break # Calculate n=pq n = p * q # Calculate f(n) ( denoted by f in code ) =(p-1)(q-1) f = (p - 1) * (q - 1) e, d, n = generate_keypair(p, q, f, n) # print('The value at client [e] = ',e) # print('The value at client [d] = ',d) # print('The value at client [n] = ',n) print('private key of Client (e,n)', (e, n)) print('public key of Client (d,n)', (d, n)) msg = int(input("Enter text : ")) key = int(input("Input Cipher key : ")) public_key = (public_e, public_n) encr_key = r_encrypt(public_key, key) print('Encrypted Secret key is:', encr_key) await socket.send(str(encr_key)) ciphertext = encrypt(msg, key) ciphertext = int(ciphertext, 2) print("ciphertext = ", ciphertext) d_s = await socket.recv() if (d_s == '2'): await socket.send(str(e)) await socket.send(str(n)) # message = str(ciphertext)+" "+str(key) message = str(ciphertext) await socket.send(message) result = hashlib.sha256(str(msg).encode()) # printing the equivalent hexadecimal value. print("The hexadecimal Digest generated : ") t = result.hexdigest() print(result.hexdigest()) private_key = (d, n) dig = r_encrypt(private_key, t) print("Digital signature of client is:\n", dig) dig = json.dumps(dig) await socket.send(dig) exit()
async def subscribe(): uri = 'ws://localhost:8989' async with websockets.connect(uri) as websocket: await process_messages(websocket)
async def hello(): uri = "ws://localhost:8765/" async with websockets.connect(uri) as websocket: # print('something working') message = await websocket.recv() print(message)
import sys import re import traceback import paramiko from websocket import create_connection import websockets HOSTNAME = "192.168.0.117" USERNAME = "******" PASSWORD = "******" SERVER_URL = "ws://localhost:8000/ws/0" p = re.compile('msg: "Setting throttle to (\d+\.\d+)"') ws = create_connection(SERVER_URL) ws2 = websockets.connect(SERVER_URL, timeout=0.1) try: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(HOSTNAME, 22, USERNAME, PASSWORD) print("connected") stdin, stdout, stderr = client.exec_command( "source /opt/ros/kinetic/setup.bash; rostopic echo /rosout_agg") stdin.close() for line in iter(lambda: stdout.readline(2048), ""): # print(line, end="") if "Setting throttle to" in line: match = p.match(line)
async def run(self, websocket_url, user_id, bot_id, game_id): async with websockets.connect(websocket_url, ssl=self.ssl_context) as websocket: msg = RequestGame(user_id, bot_id, game_id) print("OUT >>> Request Game") await websocket.send(msg.send_message()) await self.handler(websocket)
async def connect_ws(access_token): headers = {'Authorization': f'Bearer {access_token}'} params = {'fields': 'streamerSubscriptionKeys,streamerConnectionInfo'} resp = requests.get(url=f'{endpoint}/userprincipals', params=params, headers=headers).json() token_ts = resp['streamerInfo']['tokenTimestamp'] date = dateutil.parser.isoparse(token_ts) creds = { 'userid': resp['accounts'][0]['accountId'], 'token': resp['streamerInfo']['token'], 'company': resp['accounts'][0]['company'], 'segment': resp['accounts'][0]['segment'], 'cddomain': resp['accounts'][0]['accountCdDomainId'], 'usergroup': resp['streamerInfo']['userGroup'], 'accesslevel': resp['streamerInfo']['accessLevel'], 'authorized': 'Y', 'timestamp': int(to_millis(date)), 'appid': resp['streamerInfo']['appId'], 'acl': resp['streamerInfo']['acl'], } login_req = { 'requests': [{ 'requestid': 0, 'account': resp['accounts'][0]['accountId'], 'source': resp['streamerInfo']['appId'], 'service': 'ADMIN', 'command': 'LOGIN', 'parameters': { 'credential': urllib.parse.urlencode(creds), 'token': resp['streamerInfo']['token'], 'version': '1.0', } }] } data_req = { 'requests': [ { "requestid": 1, 'account': resp['accounts'][0]['accountId'], 'source': resp['streamerInfo']['appId'], 'service': 'OPTION', 'command': 'SUBS', 'parameter': { 'keys': 'TSLA', 'fields': '0,2,3,4,20,21,24,29,32,33,34,39', }, }, ] } ws_url = f"wss://{resp['streamerInfo']['streamerSocketUrl']}/ws" async with websockets.connect(ws_url) as ws: await ws.send(json.dumps(login_req)) login_resp = await ws.recv() print('login resp', login_resp) print('send data', await ws.send(json.dumps(data_req))) while True: try: data_resp = await ws.recv() print(login_resp) except: break