def test_no_reconnect(self): connection = HubConnectionBuilder()\ .with_url(self.server_url, options={"verify_ssl": False})\ .configure_logging(logging.ERROR)\ .build() _lock = threading.Lock() connection.on_open(lambda: _lock.release()) connection.on_close(lambda: _lock.release()) connection.on("ReceiveMessage", lambda _: _lock.release()) self.assertTrue(_lock.acquire(timeout=30)) # Released on open connection.start() self.assertTrue(_lock.acquire(timeout=30)) # Released on ReOpen connection.send("DisconnectMe", []) time.sleep(30) self.assertTrue(_lock.acquire(timeout=30)) self.assertRaises(ValueError, lambda: connection.send("DisconnectMe", []))
def main(game_token=''): game = None user_token = None if game_token == '': game = Game('user1', game_token) user_token, game_token = game.start() game.game_token = game_token print(game_token) else: game = Game('user2', game_token) user_token = game.accept() hub_connection = HubConnectionBuilder().with_url( "ws://localhost:5000/engine", options={ "access_token_factory": lambda: user_token }).with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }).build().build() hub_connection.start() hub_connection.on("Shot", lambda _: game.shot()) hub_connection.on("Accepted", lambda _: game.accepted()) while True: command = input() if command.lower() == 'quit': print("Goodbye!") return if command.lower().startswith('shoot'): command = command.replace('shoot', '') (x, y) = list(map(int, command.split())) game.shoot(x, y)
class ConnectionHandler(metaclass=Singleton): def __init__(self, request_processor): super(ConnectionHandler, self).__init__() self.request_processor = request_processor self.server_url = "wss://localhost:44385/computeHub" self.connection = HubConnectionBuilder()\ .with_url(self.server_url, options={ "verify_ssl": False })\ .configure_logging(logging.DEBUG)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 15, "reconnect_interval": 5, "max_attempts": 5 }).build() def start(self): self.connection.on_open(lambda: print("Connected!")) self.connection.on_close(lambda: print("Disconnected!")) self.connection.on("ReceiveMessage", print) self.connection.on( "SimpleCommand", self.request_processor.add_task) print("SignalR connecting to:", self.server_url) self.connection.start() def exit(self): self.connection.stop() print("Connection stopped")
def main(game_token=None): game = None user_token = None if game_token is None: game = Game(2, 'user1') user_token, game_token = game.start() print(game_token) else: game = Game(2, 'user2') user_token = game.accept(game_token) hub_connection = HubConnectionBuilder().with_url( "ws://localhost:5000/engine", options={ "access_token_factory": lambda: user_token }).build() hub_connection.start() hub_connection.on("Shot", lambda _: game.shot()) hub_connection.on("Accepted", lambda _: game.accepted()) while True: command = input() if command.lower() == 'quit': print("Goodbye!") return if command.lower().startswith('shoot'): command = command.replace('shoot', '') (x, y) = list(map(int, command.split())) game.shoot(x, y)
class TestSendAuthMethod(BaseTestCase): server_url = Urls.server_url_ssl_auth login_url = Urls.login_url_ssl email = "test" password = "******" received = False message = None def login(self): response = requests.post(self.login_url, json={ "username": self.email, "password": self.password }, verify=False) return response.json()["token"] def setUp(self): self.connection = HubConnectionBuilder()\ .with_url(self.server_url, options={ "verify_ssl": False, "access_token_factory": self.login, "headers": { "mycustomheader": "mycustomheadervalue" } })\ .configure_logging(logging.ERROR)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }).build() self.connection.on("ReceiveMessage", self.receive_message) self.connection.on_open(self.on_open) self.connection.on_close(self.on_close) self.connection.start() while not self.connected: time.sleep(0.1) def receive_message(self, args): self.assertEqual(args[0], self.message) self.received = True def test_send(self): self.message = "new message {0}".format(uuid.uuid4()) self.username = "******" time.sleep(1) self.received = False self.connection.send("SendMessage", [self.message]) while not self.received: time.sleep(0.1)
class SignalRCommands(threading.Thread): server_url = "wss://deepbuzz-project.azurewebsites.net/commandHub" username = "******" def __init__(self, threadID, name, counter): super().__init__() print(" SignalRCommands: __init__") self.hub_connection = HubConnectionBuilder() \ .with_url(self.server_url) \ .configure_logging(logging.DEBUG) \ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }) \ .build() threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print("Starting " + self.name) self.setup_connection(onReceivedMessage) def setup_connection(self, onReceivedCommand): print("SignalRCommands: setup_connection") self.hub_connection.on_open(lambda: print( "connection opened and handshake received ready to send messages")) self.hub_connection.on_close(lambda: print("connection closed")) self.hub_connection.on("SendCommand", onReceivedMessage) self.hub_connection.on("SendCommand", onReceivedCommand) self.hub_connection.start() message = None while message != "exit()": message = input(">> ") if message is not None and message is not "" and message is not "exit()": self.hub_connection.send("SendMessage", [self.username, message]) def close_connection(self): self.hub_connection.stop() sys.exit(0)
class SignalRConnector(BaseModule): connection: HubConnectionBuilder = None def __init__(self, hub_url): self.hub_url = hub_url def boot(self): logging.info("Connecting to websocket") self.connection = HubConnectionBuilder() \ .with_url(self.hub_url) \ .configure_logging(logging.DEBUG) \ .with_automatic_reconnect( { "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 } ) \ .build() self.connection.on_open(self.on_signalr_connected) self.connection.on_close(self.on_signalr_disconnected) self.connection.on('EventAdded', self.on_signalr_event) self.connection.start() self.subscribe(self.on_event) self.subscribe(self.handle_connected, types=SignalRConnected) def on_signalr_connected(self): self.publish(SignalRConnected('Anagon AI Bot')) def on_signalr_disconnected(self): self.publish(SignalRDisconnected('Anagon AI Bot')) def on_signalr_event(self, args): event, = args logging.info("Received SignalR event: %s" % event) if ('type', 'be.anagon.ai.signalr.connected') in event.items(): self.publish(SignalRConnected(event['client_name'])) pass def on_event(self, event: BaseEvent): logging.info("Passing event %s to SignalR server" % event) if not isinstance(event, SignalRConnected): self.connection.send('AddEvent', [event.as_dict]) def handle_connected(self, event: SignalRConnected): self.publish(TextOutput(text='%(client_name)s connected through SignalR' % event.as_dict))
class TestSendMethod(unittest.TestCase): container_id = "netcore_chat_app" connection = None server_url = "ws://localhost:81/chatHub" received = False connected = False message = None def setUp(self): self.connection = HubConnectionBuilder()\ .with_url(self.server_url)\ .configure_logging(logging.DEBUG)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }).build() self.connection.on("ReceiveMessage", self.receive_message) self.connection.on_open(self.on_open) self.connection.on_close(self.on_close) self.connection.start() while not self.connected: time.sleep(0.1) def tearDown(self): self.connection.stop() def on_open(self): self.connected = True def on_close(self): self.connected = False def receive_message(self, args): self.assertEqual(args[1], self.message) self.received = True def test_send(self): self.message = "new message {0}".format(uuid.uuid4()) self.username = "******" self.received = False self.connection.send("SendMessage", [self.username, self.message]) while not self.received: time.sleep(0.1)
def watch_remote(): hub_connection = HubConnectionBuilder() \ .with_url(config.web_socket_url, options={ 'access_token_factory': lambda: session.token.replace('bearer ', ''), 'headers': { 'Authorization': session.token } }).configure_logging(logging.ERROR).with_automatic_reconnect({ 'type': 'raw', 'keep_alive_interval': 10, 'reconnect_interval': 5, 'max_attempts': 5 }).build() hub_connection.on_open(lambda: print("++++connection opened")) hub_connection.on_close(lambda: print("++++connection closed")) hub_connection.on("organizeUpdate", print) hub_connection.on("updateNotficationBar", print) hub_connection.start()
def connect_signal_r(self, message_received_func, open_close_update_func): url = api_host + '/messagehub' hub_connection = HubConnectionBuilder() \ .with_url(url, options={ "verify_ssl": verify_ssl, "access_token_factory": self.get_or_update_access_token }) \ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 15, "max_attempts": 15 }) \ .build() hub_connection.on('ReceiveMessage', message_received_func) hub_connection.on('ReceiveUpdateOpenCloseState', open_close_update_func) hub_connection.start() return hub_connection
class LHAPIService(metaclass=Singleton): def __init__(self): self.__game_server = GameServerService() self.__hub = None def start(self): if self.__hub is not None: print("lhapi: already started") return self.__hub = HubConnectionBuilder() \ .with_url(Settings().lhapi_url + "/teamshub") \ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, }) \ .build() self.__hub.on_open(self.__on_open) self.__hub.on_close(self.__on_close) self.__hub.on("AssignTeamId", self.__on_assign_team_id) self.__hub.on("AssignGameServerUriToGameId", self.__on_assign_game_server_uri_to_game_id) self.__hub.start() def __on_open(self): print("lhapi: connection opened and handshake received") self.__hub.send("Register", [Settings().team_id, Settings().game_id]) def __on_close(self): print("lhapi: connection closed") def __on_assign_team_id(self, team_id): GameServerService().set_team_id(team_id) def __on_assign_game_server_uri_to_game_id(self, url): Settings().game_server_url = url GameServerService().start()
def run_bot(): environmentIp = os.getenv('RUNNER_IPV4', "http://localhost") environmentIp = environmentIp if environmentIp.startswith( "http://") else "http://" + environmentIp url = environmentIp + ":" + "5000" + "/runnerhub" print(url) hub_connection = HubConnectionBuilder() \ .with_url(url) \ .configure_logging(logging.INFO) \ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }).build() hub_connection.on_open(lambda: (print( "Connection opened and handshake received, ready to send messages"), set_hub_connection(True))) hub_connection.on_error( lambda data: print(f"An exception was thrown closed: {data.error}")) hub_connection.on_close( lambda: (print("Connection closed"), set_hub_connection(False))) hub_connection.on("Registered", on_register) hub_connection.on("ReceiveGameState", botService.set_game_state) hub_connection.on( "Disconnect", lambda data: (print("Disconnect Called"), (set_hub_connection(False)))) hub_connection.start() time.sleep(1) token = os.getenv("REGISTRATION_TOKEN") token = token if token is not None else uuid.uuid4() print("Registering with the runner...") bot_nickname = "Jungle_Cobra" registration_args = [str(token), bot_nickname] hub_connection.send("Register", registration_args) time.sleep(5) while hub_connected: bot = botService.bot if (bot == None): continue botService.computeNextPlayerAction(bot.object_id) actionList = [botService.playerAction] hub_connection.send("SendPlayerAction", actionList) print("Send Action to Runner") hub_connection.stop()
class GameServerService(metaclass=Singleton): def __init__(self): self.__team_id = None self.__bot = None self.__hub = None self.__hub_open = None def start(self): if self.__hub is not None: print("game server: already started") return self.__hub = HubConnectionBuilder() \ .with_url(Settings().game_server_url + "/teamshub") \ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, }) \ .build() self.__hub.on_open(self.__on_open) self.__hub.on_close(self.__on_close) self.__hub.on("RequestExecuteTurn", self.__on_request_execute_turn) self.__hub.on("ReceiveFinalMap", self.__on_receive_final_map) self.__hub.start() def __on_open(self): print("game server: connection opened and handshake received") self.__hub_open = True if self.__team_id is not None: self.__hub.send("Register", [self.__team_id]) def __on_close(self): print("game server: connection closed") def __on_request_execute_turn(self, data): if self.__bot == None: raise ValueError currentMap = data[0] dimension = data[1] maxMovement = data[2] movementLeft = data[3] lastMove = data[4] teamNumber = data[5] current_map = Map.from_strings(currentMap) host_team = teamNumber host_position = current_map.get_head_position(host_team) host_tail = current_map.get_tail_length(host_team) host_body = current_map.get_body_size(host_team) host_max_movement = maxMovement host_movement_left = movementLeft host_last_move = lastMove host = HostPlayer( host_team, host_position, host_tail, host_body, host_max_movement, host_movement_left, host_last_move, ) others = [] for other_team in Team.get_other_teams(host_team): other_position = current_map.get_head_position(other_team) other_tail = current_map.get_tail_length(other_team) other_body = current_map.get_body_size(other_team) others.append( Player( other_team, other_position, other_tail, other_body, )) game_info = GameInfo(current_map, host, others) self.__hub.send("ReturnExecuteTurn", [self.__bot.get_next_action(game_info).value]) def __on_receive_final_map(self, map): self.__hub.stop() def set_bot(self, bot): self.__bot = bot def set_team_id(self, team_id): if self.__team_id is not None: print("game server: received team ID multiple times") self.__team_id = team_id if self.__hub_open is not None: self.__hub.send("Register", [team_id])
import random from collections import deque from time import sleep, time from terminalplot import plot, get_terminal_size from signalrcore.hub_connection_builder import HubConnectionBuilder device_readings = deque(maxlen=60) count = 0 def process_device_message(msg): global device_readings, count temperature = msg[0]["temperature"] device_readings.append((count, temperature)) count += 1 h, w = get_terminal_size() x, y = zip(*device_readings) plot(x, y, h + 1, w) connection = HubConnectionBuilder() \ .with_url('http://localhost:7071/api') \ .build() connection.on('newDeviceMessage', process_device_message) connection.start() input("Receiving chat messages...")
server_url = "ws://localhost:9000/hub" username = "******" hub_connection = HubConnectionBuilder()\ .with_url(server_url)\ .configure_logging(logging.DEBUG)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }).build() hub_connection.on_open(lambda: print( "connection opened and handshake received ready to send messages")) hub_connection.on_close(lambda: print("connection closed")) hub_connection.on("messageReceived", check_user) hub_connection.start() message = None # Do login while message != "exit()": message = input(">> ") if message is not None and message is not "" and message is not "exit()": hub_connection.send("newMessage", [username, message]) hub_connection.stop() sys.exit(0)
hub_connection.start() print("Connection restarted.") print("Subscribing to stream: {}".format(streamId)) hub_connection.send("SubscribeToParameter", ["codemasters", value, "Speed"]) print("Subscribed to stream: {}".format(streamId)) speed = [] timestamps = [] def on_data(payload): for data in payload: for row in range(len(data['numericValues']['Speed'])): timestamps.append(str(datetime.datetime.fromtimestamp(data['timestamps'][row] / 1000000000))) speed.append(data['numericValues']['Speed'][row]) hub_connection.on("ParameterDataReceived", on_data) hub_connection.start() external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) # We add secondary y axe to accommodate second parameter. fig = make_subplots(specs=[[{"secondary_y": True}]]) # Add series into plot for speed. fig.add_trace( go.Scatter(x=[], y=[], name="Speed", ), secondary_y=False, ) fig.update_yaxes(range=[0,400])
hub_connection = HubConnectionBuilder()\ .with_url(server_url, options={ "access_token_factory": lambda: result['accessToken'] }).with_automatic_reconnect({ "type": "interval", "keep_alive_interval": 10, "intervals": [1, 3, 5, 6, 7, 87, 3] })\ .build() hub_connection.on_open(on_open) hub_connection.on_close(on_close) hub_connection.on("newMessage", print_message) hub_connection.start() message = None while message != "exit()": if connection_open: print(" " * offset + f"{username}:", end="") message = input() if message != None and message != "" and message != "exit()": # hub_connection.send("SendMessage", [username, message]) resp = requests.post(messages_url, json={ "sender": username, "text": message })
class TestSendAuthMethod(unittest.TestCase): container_id = "netcore_chat_app" connection = None server_url = "ws://*****:*****@GMAIL.COM" password = "******" received = False connected = False message = None def login(self): response = requests.post(self.login_url, data={ "email": self.email, "password": self.password }) return response.json()["token"] def setUp(self): self.connection = HubConnectionBuilder()\ .with_url(self.server_url, options={ "access_token_factory": self.login, "headers": { "mycustomheader": "mycustomheadervalue" } })\ .configure_logging(logging.DEBUG)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }).build() self.connection.on("ReceiveChatMessage", self.receive_message) self.connection.on_open(self.on_open) self.connection.on_close(self.on_close) self.connection.start() while not self.connected: time.sleep(0.1) def tearDown(self): self.connection.stop() def on_open(self): self.connected = True def on_close(self): self.connected = False def receive_message(self, args): self.assertEqual(args[0], "{0}: {1}".format(self.email, self.message)) self.received = True def test_send(self): self.message = "new message {0}".format(uuid.uuid4()) self.username = "******" time.sleep(1) self.received = False self.connection.send("Send", [self.message]) while not self.received: time.sleep(0.1)
"*****@*****.**") password = input_with_default('Enter your password (default: {0}): ', "Abc123.--123?") hub_connection = HubConnectionBuilder()\ .with_url(server_url, options={ "access_token_factory": lambda: signalr_core_example_login(login_url, username, password), "verify_ssl": False }).with_automatic_reconnect({ "type": "interval", "keep_alive_interval": 10, "intervals": [1, 3, 5, 6, 7, 87, 3] })\ .build() hub_connection.on_open(lambda: print( "connection opened and handshake received ready to send messages")) hub_connection.on_close(lambda: print("connection closed")) hub_connection.on("ReceiveSystemMessage", print) hub_connection.on("ReceiveChatMessage", print) hub_connection.on("ReceiveDirectMessage", print) hub_connection.start() message = None while message != "exit()": message = input(">> ") if message is not None and message != "" and message != "exit()": hub_connection.send("Send", [message]) hub_connection.stop()
def turn_machine(json_data): json_data = json.dumps(json_data) data = json.loads(json_data) dispenser = data[0]['dispenser'] count = data[0]['count'] print('Turning dispenser ' + str(dispenser) + " for " + str(count) + ' times!') for x in range(0, count): channel = pca.channel[mapping[dispenser - 1]] channel.duty_cycle = 0xFFFF time.sleep(0.5) channel.duty_cycle = 0x00 time.sleep(3) hub_connection.on_open(lambda: print( "connection opened and handshake received ready to send messages")) hub_connection.on_close(lambda: print("connection closed")) hub_connection.on('turndispenser', turn_machine) hub_connection.start() message = None while True: time.sleep(0.5) #do nothing hub_connection.stop()
"max_attempts": 5 }).build() hub_connection.on_open(lambda: print( "connection opened and handshake received ready to send messages")) hub_connection.on_close(lambda: reconnect) def reconnect(): print("connection closed") time.sleep(20) print("try reconnect") hub_connection.start() print("Connecting to hub") hub_connection.on("SendColor", writeMessage) hub_connection.start() print("Connected to hub") message = input(">> ") # #message = None #while message != "exit()": # message = input(">> ") # if message is not None and message is not "" and message is not "exit()": # hub_connection.send("SendColor", [username, message]) # #hub_connection.stop() sys.exit(0)
handler.setLevel(logging.DEBUG) hub_connection = HubConnectionBuilder()\ .with_url(server_url, options={"verify_ssl": False}) \ .configure_logging(logging.DEBUG, socket_trace=True, handler=handler) \ .with_automatic_reconnect({ "type": "interval", "keep_alive_interval": 10, "intervals": [1, 3, 5, 6, 7, 87, 3] }).build() hub_connection.on_open(lambda: print( "connection opened and handshake received ready to send messages")) hub_connection.on_close(lambda: print( "connection closed>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<")) hub_connection.on_error(lambda err: print("errrrrrrrrrrrrrrrrrrr")) hub_connection.on("ThrowExceptionCall", lambda x: print(f">>>{x}")) hub_connection.start() message = None # Do login while message != "exit()": message = input(">> ") if message is not None and message != "" and message != "exit()": hub_connection.send("ThrowException", [message]) hub_connection.stop() sys.exit(0)
sleep(1) hub = HubConnectionBuilder()\ .with_url(Server_URL)\ .configure_logging(logging.INFO)\ .with_automatic_reconnect({ "type": "interval", "keep_alive_interval": 10, "intervals": [1, 3, 5, 6, 7, 87, 3] }).build() # Handle on connect and disconnected hub.on_open(onConnectionOpened) hub.on_close(onConnectionClosed) hub.on("OnReceivedReport", onReceivedReport) try: hub.start() # Start display thread displayThread = threading.Thread(target=displayLoopThread) displayThread.start() while True: # Continue running pass except ConnectionError: onFailedToStartHub() hub.stop()
chatHubUrl = "https://iobtweb.azurewebsites.net/chatHub" hub_connection = HubConnectionBuilder()\ .with_url(chatHubUrl)\ .configure_logging(logging.DEBUG)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }).build() hub_connection.on_open(lambda: print( "connection opened and handshake received ready to send messages")) hub_connection.on_close(lambda: print("connection closed")) hub_connection.on("ChatMessage", received_message) hub_connection.start() text = None while text != "exit()": text = input(">> ") message = dict({ "user": "******", "message": text, "sourceGuid": "375ad623-6e7c-4272-8aa7-d631d22a356d", "timeStamp": "2021-04-07T11:55:46.669Z", "personId": "Llam_9" }) if text is not None and text != "" and text != "exit()":
.with_url(server_url)\ .configure_logging(logging.DEBUG)\ .build() hub_connection.on_open(lambda: print( "connection opened and handshake received ready to send messages")) hub_connection.on_close(lambda: reconnect) def reconnect(): print("connection closed") time.sleep(20) print("try reconnect") hub_connection.start() hub_connection.on("ReceiveMessage", print) hub_connection.start() message = None # Do login while message != "exit()": message = input(">> ") if message is not None and message != "" and message != "exit()": hub_connection.send("SendMessage", [username, message]) hub_connection.stop() sys.exit(0)
.with_url(server_url)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 }).build() hub_connection.on_open(lambda: print( "connection opened and handshake received ready to send messages")) hub_connection.on_close(lambda: reconnect) def reconnect(): print("connection closed") time.sleep(20) print("try reconnect") hub_connection.start() print("Connecting to hub") hub_connection.on("sendColor", colorChanger) hub_connection.start() startUp() print("Connected to hub") message = input("Press any button to quit") hub_connection.stop() print("Exiting") sys.exit(0)
class RadarrSignalrClient: def __init__(self): super(RadarrSignalrClient, self).__init__() self.apikey_radarr = None self.connection = None def start(self): self.configure() logging.info('BAZARR trying to connect to Radarr SignalR feed...') while self.connection.transport.state.value not in [0, 1, 2]: try: self.connection.start() except ConnectionError: time.sleep(5) def stop(self): logging.info('BAZARR SignalR client for Radarr is now disconnected.') self.connection.stop() def restart(self): if self.connection: if self.connection.transport.state.value in [0, 1, 2]: self.stop() if settings.general.getboolean('use_radarr'): self.start() def exception_handler(self): logging.error( "BAZARR connection to Radarr SignalR feed has failed. We'll try to reconnect." ) self.restart() @staticmethod def on_connect_handler(): logging.info( 'BAZARR SignalR client for Radarr is connected and waiting for events.' ) if not args.dev: scheduler.add_job(update_movies, kwargs={'send_event': True}, max_instances=1) def configure(self): self.apikey_radarr = settings.radarr.apikey self.connection = HubConnectionBuilder() \ .with_url(url_radarr() + "/signalr/messages?access_token={}".format(self.apikey_radarr), options={ "verify_ssl": False, "headers": headers }) \ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 5, "reconnect_interval": 180, "max_attempts": None }).build() self.connection.on_open(self.on_connect_handler) self.connection.on_reconnect(lambda: logging.error( 'BAZARR SignalR client for Radarr connection as been lost. ' 'Trying to reconnect...')) self.connection.on_close(lambda: logging.debug( 'BAZARR SignalR client for Radarr is disconnected.')) self.connection.on_error(self.exception_handler) self.connection.on("receiveMessage", dispatcher)
class Chat(MycroftSkill): def __init__(self): MycroftSkill.__init__(self) def initialize(self): chatHubUrl = "https://iobtweb.azurewebsites.net/chatHub" self.hub_connection = HubConnectionBuilder()\ .with_url(chatHubUrl)\ .configure_logging(logging.DEBUG)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 60, "reconnect_interval": 30, "max_attempts": 5 }).build() self.hub_connection.on("ChatMessage", self.handle_receive_message) self.hub_connection.start() @intent_handler(IntentBuilder("").require("ChatKeyword").require("text")) def handle_chat(self, message): text = message.data.get("text") # self.post_message(text) self.send_message(text) def send_message(self, text): message = dict({ "user": "******", "message": text, "sourceGuid": "375ad623-6e7c-4272-8aa7-d631d22a356d", "timeStamp": "2021-04-07T11:55:46.669Z", "personId": "Llam_9" }) self.hub_connection.send("ChatMessage", [message]) def post_message(self, text): message = dict({ "user": "******", "message": text, "sourceGuid": "375ad623-6e7c-4272-8aa7-d631d22a356d", "timeStamp": "2021-04-07T11:55:46.669Z", "personId": "Llam_9" }) # chatURL = "https://192.168.1.20:5000/api/ChatHub/ChatMessage" chatURL = "https://iobtweb.azurewebsites.net/api/ChatHub/ChatMessage" # chatURL = "http://localhost:5000/api/ChatHub/ChatMessage" headers = dict({ 'Content-type': 'application/json', 'Accept': 'application/json' }) response = requests.post(url=chatURL, json=message, headers=headers) result = response.json() self.speak_dialog('chat') #print(result) if (result['hasError'] == True): print(result['message']) else: payload = result['payload'] print(payload) def handle_receive_message(self, payload): self.speak_dialog("Incoming Message") self.speak_dialog(payload[0]["message"]) def stop(self): if (self.hub_connection): self.hub_connection.stop() def shutdown(self): if (self.hub_connection): self.hub_connection.stop()
class EaseeManager(object): def __init__(self, settings:EaseeSettings): self.settings = settings self.cli = EaseeCLI() self.token = None self.signals = None def start(self): try: self._start_signals() except Exception as e: _log(f"Failed to start SignalR - {sys.exc_info()[0]}") def stop(self): self.token = None try: self._stop_signals() except Exception as e: _log(f"Failed to stop SignalR - {sys.exc_info()[0]}") def _start_signals(self): url = "https://api.easee.cloud/hubs/chargers" options = {"access_token_factory": self._get_access_token,"headers":{"APP":"no.easee.apps.bridge"}} self.signals = HubConnectionBuilder().with_url(url,options).configure_logging(logging.ERROR).with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 30, "reconnect_interval": 5, "max_attempts": 5 }).build() self.signals.on_open(lambda: self.on_open()) self.signals.on_close(lambda: self.on_close()) self.signals.on_error(lambda data: print(f"An exception was thrown closed{data.error}")) self.signals.on("ProductUpdate", self.product_update) self.signals.start() def _stop_signals(self): for device in self.settings.devices: self.signals.send("Unsubscribe", [device.id]) self.signals.stop() def _get_access_token(self) -> str: if self.token is not None: return self.token.access _log("Obtaining new jwt token") self.token = self.cli.login(self.settings.username,self.settings.password) if self.token is not None: return self.token.access raise requests.exceptions.ConnectionError() def on_open(self): _log("SignalR connection opened and handshake received ready to send messages") for device in self.settings.devices: self.signals.send("SubscribeWithCurrentState", [device.id, True]) def on_close(self): _log("SignalR connection closed") def product_update(self,stuff: list): _log(f"SignalR msg received {stuff}")
class Main: def __init__(self): self._hub_connection = None self.HOST = os.environ["HVAC_HOST"] self.TOKEN = os.environ["HVAC_TOKEN"] def __del__(self): if (self._hub_connection != None): self._hub_connection.stop() def setup(self): self.setSensorHub() def start(self): self.setup() self._hub_connection.start() print("Press CTRL+C to exit.") while True: time.sleep(2) self._hub_connection.stop() sys.exit(0) def setSensorHub(self): self._hub_connection = HubConnectionBuilder()\ .with_url(f"{self.HOST}/SensorHub?token={self.TOKEN}")\ .configure_logging(logging.INFO)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 999 }).build() self._hub_connection.on("ReceiveSensorData", self.onSensorDataReceived) self._hub_connection.on_open(lambda: print("||| Connection opened.")) self._hub_connection.on_close(lambda: print("||| Connection closed.")) self._hub_connection.on_error(lambda data: print( f"||| An exception was thrown closed: {data.error}")) def onSensorDataReceived(self, data): try: print(data[0]["date"] + " --> " + data[0]["data"]) date = data[0]["date"] dp = float(data[0]["data"]) self.analyzeDatapoint(date, dp) except Exception as err: print(err) def analyzeDatapoint(self, date, data): if (data >= 80.0): self.sendActionToHvac(date, "TurnOnAc", 6) elif (data <= 20.0): self.sendActionToHvac(date, "TurnOnHeater", 6) def sendActionToHvac(self, date, action, nbTick): r = requests.get( f"{self.HOST}/api/hvac/{self.TOKEN}/{action}/{nbTick}") details = json.loads(r.text) print(details)