def main(): with Session() as session: session.auth = HTTPBasicAuth("known", "user") # connection = Connection("http://localhost:16338/signalr", session) connection = Connection("http://netmonsterraspisignalr.azurewebsites.net", session) # connection = Connection("http://localhost:5000/signalr", session) chat = connection.register_hub("raspiGrowHub") def print_received_message(name, message): print("received: ", message) def print_error(error): print("error: ", error) chat.client.on("addNewMessageToPage", print_received_message) # chat.client.on('topicChanged', print_topic) connection.error += print_error with connection: chat.server.invoke("send", "Kris", "Python is here!") # chat.server.invoke('setTopic', 'Welcome python!') # chat.server.invoke('requestError') # chat.server.invoke('send', 'Bye-bye!') connection.wait(1)
def main(): r = requests.get("https://api.bittrex.com/api/v1.1/public/getmarkets") marketData = r.json()["result"] markets = [] for i in marketData: if (i["IsRestricted"] == False): markets.append(i["MarketName"]) createDirectories(markets) while (-1): try: with Session() as session: print("Restarting connection!") connection = Connection("https://socket.bittrex.com/signalr", session) chat = connection.register_hub('corehub') connection.received += handle_received connection.error += print_error connection.start() # You missed this part chat.client.on('updateExchangeState', msg_received) for i in range(10): for market in markets: print("Querying: " + market) #chat.server.invoke('SubscribeToExchangeDeltas', market) chat.server.invoke('QueryExchangeState', market) connection.wait(60) # Value of 1 will not work, you will get disconnected #connection.wait(120000) except KeyboardInterrupt: break except: continue
def main(): with Session() as session: session.auth = HTTPBasicAuth("known", "user") connection = Connection("http://localhost:5000/signalr", session) chat = connection.register_hub('chat') def print_received_message(data): print('received: ', data) def print_topic(topic, user): print('topic: ', topic, user) def print_error(error): print('error: ', error) chat.client.on('newMessageReceived', print_received_message) chat.client.on('topicChanged', print_topic) connection.error += print_error with connection: chat.server.invoke('send', 'Python is here') chat.server.invoke('setTopic', 'Welcome python!') chat.server.invoke('requestError') chat.server.invoke('send', 'Bye-bye!') connection.wait(1)
def request_order_book(self): try: with Session() as session: connection = Connection(self.url, session) self.hub = connection.register_hub(self.hub_name) connection.received += self.on_receive connection.start() while self.order_book_is_received is not True: self.hub.server.invoke( BittrexParameters.QUERY_EXCHANGE_STATE, self.pair_name) connection.wait( 5 ) # otherwise it shoot thousands of query and we will be banned :( connection.close() msg = "Got orderbook for Bittrex!" log_to_file(msg, SOCKET_ERRORS_LOG_FILE_NAME) print(msg) return STATUS.SUCCESS except Exception as e: # log_error_on_receive_from_socket("Bittrex", e) msg = "Error during order book retrieval for Bittrex {}".format( str(e)) log_to_file(msg, SOCKET_ERRORS_LOG_FILE_NAME) print(msg) return STATUS.FAILURE
def collect_ws(this): with Session() as session: connection = Connection(this.WS_URL, session=session) hub = connection.register_hub('c2') connection.start() hub.client.on('uS', this.on_message) hub.server.invoke('SubscribeToSummaryDeltas') connection.wait()
def get_value(self, hub, method): self.res = {} with Session() as session: #create a connection connection = Connection(self.url, session) chat = connection.register_hub(hub) chat.client.on(method, self.update_res) connection.start() connection.wait(3) connection.close() return self.res
def main(): with Session() as session: connection = Connection("https://www.bittrex.com/signalR/", session) chat = connection.register_hub('corehub') connection.start() connection.received += handle_received connection.error += print_error for market in ["BTC-MEME", "BTC-ANS"]: chat.server.invoke('SubscribeToExchangeDeltas', market) chat.server.invoke('QueryExchangeState', market) while True: connection.wait(1)
def signal_r_setup(): with Session() as session: #create a connection connection = Connection("http://localhost:6658/signalr", session) #connection = Connection("https://atbot01.azurewebsites.net/signalr", session) #get chat hub bot = connection.register_hub('BotControl') hub = connection.register_hub('WebRtcHub') #start a connection connection.start() hub.server.invoke('registerBot', 'PyBot') print('connected to SignalR hub... connection id: ' + connection.token) #create new chat message handler def print_received_message(data): print('received: ', data) robot.go(-data['Y'], data['X']) bot.server.invoke('sendLocation', data) print('sent: ', data) #receive new chat messages from the hub bot.client.on('controllerAt', print_received_message) #create error handler def print_error(error): print('error: ', error) #process errors connection.error += print_error #connection.start() #start connection, optionally can be connection.start() with connection: #post new message #bot.server.invoke('sendLocation', 'RaspPi') #wait a second before exit connection.wait(None) # no timeout
def initSignalrConnection(): with Session() as session: #create a connection connection = Connection(HUB_URL, session) #get BoongalooGroupsActivityHub hub boongalooGroupsActivityHub = connection.register_hub(HUB_NAME) #receive new message from the hub boongalooGroupsActivityHub.client.on('groupWasLeftByUser', groupWasLeftByUserHandler) #process errors connection.error += signalrErrorHandler #start a connection connection.qs = {'userId': '5b8e69b6-fc13-494d-9228-4215de85254f'} print("Connection was started") with connection: connection.wait(13)
def sendNewMailRequestInSeparateThread(): with Session() as session: upload_result = uploadImage() #create a connection connection = Connection(HUB_HOST_URL, session) #get PeepneeHub hub peepneeHub = connection.register_hub(HUB_NAME) peepneeHub.client.on('mailRequestAccepted', mailRequestAccepted) peepneeHub.client.on('mailRequestDeclined', mailRequestDeclined) peepneeHub.client.on('repeatMailRequest', repeatMailRequest) peepneeHub.client.on('updateDefaultOwnerSettings', updateDefaultOwnerSettings) #process errors connection.error += print_error #start a connection log("Connection was started", True) with connection: peepneeHub.server.invoke('newMailRequest', upload_result['link'], "OCR PARSED TEXT") connection.wait(16) log("Connection to SignalR hub was closed!", True)
#get chat hub bot = connection.register_hub('BotControl') #start a connection connection.start() #create new chat message handler def print_received_message(data): print('received: ', data) #receive new chat messages from the hub bot.client.on('controllerAt', print_received_message) #create error handler def print_error(error): print('error: ', error) #process errors connection.error += print_error #connection.start() #start connection, optionally can be connection.start() with connection: #post new message #bot.server.invoke('sendLocation', 'RaspPi') #wait a second before exit connection.wait(60)
class SignalR(object): def __init__(self, header=None, on_open=None, on_message=None, on_error=None, on_close=None, ): self.header = header if header is not None else [] self.on_open = on_open self.on_message = on_message self.on_error = on_error self.on_close = on_close self.keep_running = False self.conn = None self.corehub = None self.cps = [] def r(self, **kwargs): msg = kwargs if 'R' in msg and type(msg['R']) is not bool: if 'MarketName' in msg['R'] and msg['R']['MarketName'] is None: msg['R']['MarketName'] = self.cps[0] # MarketName is None Problem self.cps.pop(0) # message FIFO >? del msg['R']['Fills'] self.received(kwargs) def received(self, data): self._callback(self.on_message, data) def subscribe(self, channel, cp='BTC-USDT'): self.cps.append(cp) if channel == 'ticker': self.corehub.server.invoke('SubscribeToSummaryDeltas') elif channel == 'trader': self.corehub.server.invoke('SubscribeToExchangeDeltas', cp) self.corehub.server.invoke('queryExchangeState', cp) def close(self): self.keep_running = False if self.conn: self.conn.close self._callback(self.on_close) def run_forever(self, ping_interval=0, ping_timeout=None, ): if ping_timeout and ping_interval and ping_interval <= ping_timeout: raise logging.warning("Ensure ping_interval > ping_timeout") if self.conn: raise logging.warning("connection is already opened") thread = None self.keep_running = True try: with cfscrape.create_scraper() as connection: self.conn = Connection(None, connection) self.conn.received += self.r # self.conn.url = 'https://socket-stage.bittrex.com/signalr' self.corehub = self.conn.register_hub('coreHub') logging.info(MSG_TRY_TO_CONNECT.format('Bittrex',self.conn.url)) self.conn.start() logging.info(MSG_CONNECT_SUCCESS.format('Bittrex',self.conn.url)) self._callback(self.on_open) self.corehub.client.on('updateSummaryState', self.received) self.corehub.client.on('updateExchangeState', self.received) while self.conn.started: if not self.keep_running: break self.conn.wait(1) #Data will receive when connection is waiting except (Exception, KeyboardInterrupt, SystemExit) as e: self._callback(self.on_error, e) finally: if thread and thread.isAlive(): thread.join() self.keep_running = False self._callback(self.on_close) self.conn = None self.corehub = None def _callback(self, callback, *args): if callback: try: callback(self, *args) except Exception as e: logging.error("error from callback {}: {}".format(callback, e))
#create error handler def print_error(error): print('error: ', error) #receive new chat messages from the hub chat.client.on('newMessageReceived', print_received_message) #change chat topic chat.client.on('topicChanged', print_topic) #process errors connection.error += print_error #start connection, optionally can be connection.start() with connection: #post new message chat.server.invoke('send', 'Python is here') #change chat topic chat.server.invoke('setTopic', 'Welcome python!') #invoke server method that throws error chat.server.invoke('requestError') #post another message chat.server.invoke('send', 'Bye-bye!') #wait a second before exit connection.wait(1)
class EmotivConnection(object): """ Read data from file or hid. Only CSV for now. """ def __init__(self): self.hub_url = 'http://localhost:51560/signalr' self.hub_name = 'EmokitHub' self.connection = None self.hub = None self.hub_event = 'OnProducerChanged' self.stop_connection = False self.connection_thread = Thread(target=self.run) self.running = False self.stop_received = False; self.reader_init = False self.lock = Lock() def start(self): """ Starts the connection thread. """ self.stopped = False self.connection_thread.start() def stop(self): """ Stops the reader thread. """ self.lock.acquire() self._stop_signal = True self.lock.release() def run(self, source=None): with Session() as session: #create a connection self.connection = Connection(self.hub_url, session) #connect to the hub self.hub = self.connection.register_hub(self.hub_name) # start the connection self.connection.start() def OnProducerChanged(data): if self.stop_received is False: print('received: ', data) """ Starts emotiv, called upon initialization. """ if data == "start": self.running = True elif data == "stop": self.running = False self.stop_received = True print("Emotiv Stopped") #receive new chat messages from the hub self.hub.client.on(self.hub_event, OnProducerChanged) #create error handler def print_signalr_error(error): print('error: ', error) #process errors self.connection.error += print_signalr_error #hold the connection (annoying way to do it) self.lock.acquire() while not self.stop_connection: self.lock.release() self.connection.wait() if(self.reader_init): self.hub.server.invoke("Init"); self.reader_init = False self.lock.acquire() def __exit__(self, exc_type, exc_value, traceback): self.stop() if self.connection_thread: self.connection_thread.close()
#create error handler def print_error(error): print('error: ', error) #receive new chat messages from the hub chat.client.on('newMessageReceived', print_received_message) #change chat topic chat.client.on('topicChanged', print_topic) #process errors connection.error += print_error #start connection, optionally can be connection.start() with connection: #post new message # chat.server.invoke('send', 'Python is here') # #change chat topic chat.server.invoke('setTopic', 'Welcome python!') # #invoke server method that throws error # chat.server.invoke('requestError') #post another message chat.server.invoke('send', 'Bye-bye!') #wait a second before exit connection.wait(1)
print('Hmm! Mail was declined.') def repeatMailRequest(): print('What? Repeat mail request.') def updateDefaultOwnerSettings(openAfterDefaultTime, secondsToDefaultBehaviour): print( "Kewl? Update settings to openAfterDefaultTime: {0} and secondsToDefaultBehaviour: {1}" .format(openAfterDefaultTime, secondsToDefaultBehaviour)) def print_error(error): print('error: ', error) peepneeHub.client.on('mailRequestAccepted', mailRequestAccepted) peepneeHub.client.on('mailRequestDeclined', mailRequestDeclined) peepneeHub.client.on('repeatMailRequest', repeatMailRequest) peepneeHub.client.on('updateDefaultOwnerSettings', updateDefaultOwnerSettings) #process errors connection.error += print_error #start a connection print("Connection was started") with connection: peepneeHub.server.invoke('mailRequestAccepted') peepneeHub.server.invoke('updateDefaultOwnerSettings', 0, 13) peepneeHub.server.invoke('newMailRequest', 'some_url', 'some_text') connection.wait(13)
def signal_r_setup(): with Session() as session: # create a connection #connection = Connection("https://atbot01.azurewebsites.net/signalr", session) connection = Connection("https://dube.azurewebsites.net/signalr", session) #connection = Connection("http://localhost:6658/signalr", session) # get control hub bot = connection.register_hub('BotControl') hub = connection.register_hub('WebRtcHub') # start a connection connection.start() t = Timer(.1, RHANDLER.stop) hub.server.invoke('registerBot', 'PyBot') print('connected to SignalR hub... connection id: ' + connection.token) # create new control message handler def handle_bot_control_request(data): print('received: ', data) try: command = data['Command'] #RHANDLER.get_sensors() if command == "turn": RHANDLER.turn(data) elif command == "rise": RHANDLER.rise(data) else: #RHANDLER.go(data) RHANDLER.go_direct(data) t.cancel() t = Timer(0.50, RHANDLER.stop) t.start() except: pass def send_telemetry(): cnt = 0 while True: cnt = cnt + 1 j = RHANDLER.get_sensors() bot.server.invoke('sendBotTelemetry', j) time.sleep(5) # receive new chat messages from the hub bot.client.on('controllerAt', handle_bot_control_request) thread = Thread(target=send_telemetry, args=()) thread.daemon = True thread.start() # create error handler def print_error(error): print('error: ', error) # process errors connection.error += print_error # wait before exit connection.wait(None)
def signalRTest(): # monkey.patch_all() # from requests.packages.urllib3.util.ssl_ import create_urllib3_context # create_urllib3_context() with Session() as session: # create a connection # connection = Connection("http://tvbetapi.net/mainfeed", session) # connection = Connection("http://192.168.212.172:11009/mainfeed", session) # connection = Connection("http://192.168.212.172:9005/mainfeed", session) # connection = Connection("http://localhost:11009/mainfeed", session) # connection = Connection("http://localhost:30258/mainfeed", session) # connection = Connection("http://localhost:30258/feedhub", session) # connection = Connection("http://localhost:14507/hubs", session) # connection = Connection("http://localhost:44312/hubs", session) # connection = Connection("http://192.168.212.172:11011/hubs", session) connection = Connection("http://192.168.212.172:11993/hubs", session) # connection = Connection("http://192.168.212.172:9005/feedhub", session) # get chat hub # feedHub = connection.register_hub('mainfeed') feedHub = connection.register_hub('FeedHub') # start a connection connection.start() # create new chat message handler def print_received_message(data): t = json.dumps(data) temp = json.loads(t) print(temp) # if temp['NI'] != 1: # print(temp) # if temp['NI'] == 8: # print('LastHands: ', temp['D']['LH']) # print('Hands: ', temp['D']['H']) # print('------') # create error handler def print_error(error): print('error: ', error) # receive new chat messages from the hub # feedHub.client.on('addMessage', print_received_message) # feedHub.client.on('addMessage', print_received_message) feedHub.client.on('TimingSubscribe', print_received_message) feedHub.client.on('VideoGamesSubscribe', print_received_message) feedHub.client.on('GamesInfoSubscribe', print_received_message) feedHub.client.on('GamesSubscribe', print_received_message) feedHub.client.on('GamesLastResultsSubscribe', print_received_message) feedHub.client.on('GamesStatisticsSubscribe', print_received_message) feedHub.client.on('GamesEventsSubscribe', print_received_message) feedHub.client.on('PromterGameSubscribe', print_received_message) # # change chat topic # chat.client.on('topicChanged', print_topic) # process errors connection.error += print_error money = 10 # start connection, optionally can be connection.start() with connection: # post new message # feedHub.server.invoke('send', '{"M":14,"GT":5}') # SubscribeOnGame # feedHub.server.invoke('send', '{"M":2,"GT":4,"C":"EUR","CID":46,"CG":5,"L":"en"}') # feedHub.server.invoke('send', '{"M":3,"GT":3,"C":"EUR","CI":127,"CG":3,"L":"en"}') # SubOnGame # feedHub.server.invoke('send', '{"M":16,"GID":90018722430,"CID":35,"L":"en"}') # feedHub.server.invoke('send', '{"M":17,"CI":192,"GID":30001947193,"GT":3,"L":"ru"}') # feedHub.server.invoke('send', '{"M":20,"GID":50007287757,"GT":5}') # SubscribeOnGameStatistic feedHub.server.invoke('SubscribeOnTiming', [2]) # feedHub.server.invoke('SubscribeOnVideoGames', [2], 2026) # feedHub.server.invoke('SubscribeOnGamesInfo', 2, 3) # feedHub.server.invoke('SubscribeOnPromterGame', 5) # feedHub.server.invoke('SubscribeOnGamesLastResults', 2, 3) # feedHub.server.invoke('SubscribeOnGamesStatistics', 6) # feedHub.server.invoke('SubscribeOnGames', [{"i": 6703045, "t": 5}], 46) # feedHub.server.invoke('SubscribeOnCashDeskGames', [{"i": 90000037378, "t": 2}], 127) # feedHub.server.invoke('SubscribeOnCashDeskGamesEvents', [{"i": 131197, "t": 7, "e": [{"t": 123, "p": ["175.5"]}, {"t": 2169, "p": ["-1", "0"]}]}], 127, 0) # SubscribeOnPromterGame # feedHub.server.invoke('send', '{"M":21,"GT":2,"CI":121,"CE":15,"EM":2,"EI":[{"ET":21,"P":[1]},{"ET":4043,"P":[1,2,3,4,5,6]},{"ET":23,"P":[18.5]},{"ET":30,"P":[]}]}') # feedHub.server.invoke('send', '{"M": 21,"GT": 2,"CI":121,"CE":30,"EM":1,"EI":[{"ET":21,"P":["1"]}]}') # feedHub.server.invoke('send', '{"M":8,"GT":3}') # feedHub.server.invoke('send', '{"M":9,"CID":46}') # feedHub.server.invoke('send', '{"GTS":[2],"C":"EUR","L":"en","PM":0.05,"M":19}') # feedHub.server.invoke('send', '{"M":4,"GT":2,"CG":2}') # change chat topic # chat.server.invoke('setTopic', 'Welcome python!') # invoke server method that throws error # chat.server.invoke('requestError') # chat.server.invoke('send', 'Bye-bye!') # wait a second before exit connection.wait(None)