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 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 test_reconnect_interval_config(self): connection = HubConnectionBuilder()\ .with_url(self.server_url, options={"verify_ssl": False})\ .configure_logging(logging.ERROR)\ .with_automatic_reconnect({ "type": "interval", "intervals": [1, 2, 4, 45, 6, 7, 8, 9, 10] })\ .build() _lock = threading.Lock() connection.on_open(lambda: _lock.release()) connection.on_close(lambda: _lock.release()) self.assertTrue(_lock.acquire(timeout=30)) connection.start() self.assertTrue(_lock.acquire(timeout=30)) connection.stop() self.assertTrue(_lock.acquire(timeout=30)) _lock.release() del _lock
class TestSendAuthErrorMethod(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) if response.status_code == 200: return response.json()["token"] raise requests.exceptions.ConnectionError() def setUp(self): pass def test_send(self): self.connection = HubConnectionBuilder()\ .with_url(self.server_url, options={ "verify_ssl": False, "access_token_factory": self.login, })\ .configure_logging(logging.ERROR)\ .build() self.connection.on_open(self.on_open) self.connection.on_close(self.on_close) self.assertRaises(requests.exceptions.ConnectionError, lambda: self.connection.start())
class TestSendMethod(unittest.TestCase): container_id = "netcore_stream_app" connection = None server_url = "ws://localhost:82/streamHub" received = False connected = False items = list(range(0, 10)) 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_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): print("opene") self.connected = True def on_close(self): self.connected = False def on_complete(self, x): self.complete = True def on_error(self, x): pass def on_next(self, x): item = self.items[0] self.items = self.items[1:] self.assertEqual(x, item) def test_stream(self): self.complete = False self.items = list(range(0, 10)) self.connection.stream("Counter", [len(self.items), 500]).subscribe({ "next": self.on_next, "complete": self.on_complete, "error": self.on_error }) while not self.complete: time.sleep(0.1)
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 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 TestSendMethod(unittest.TestCase): container_id = "netcore_stream_app" connection = None server_url = "wss://localhost:5001/chatHub" received = False connected = False items = list(range(0,10)) def setUp(self): self.connection = HubConnectionBuilder()\ .with_url(self.server_url, options={"verify_ssl":False})\ .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_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): print("opene") self.connected = True def on_close(self): self.connected = False def on_complete(self, x): self.complete = True def on_error(self, x): pass def test_stream(self): self.complete = False self.items = list(range(0,10)) subject = Subject() self.connection.send("UploadStream", subject) while(len(self.items) > 0): subject.next(str(self.items.pop())) subject.complete() self.assertTrue(len(self.items) == 0)
def create_hub_connection(context): hub_connection = HubConnectionBuilder()\ .with_url(read_secret("hub_url"), options={ "access_token_factory": login })\ .configure_logging(logging.DEBUG)\ .build() hub_connection.on_open( lambda: logging.info(f"{context} signalR connection is now open")) hub_connection.on_close( lambda: logging.info(f"{context} signalR connection is now closed")) hub_connection.on_error(lambda data: logging.warning( f"{context} an exception was thrown: '{data.error}'")) return hub_connection
def get_connection(self): hub = HubConnectionBuilder()\ .with_url(self.server_url, options={"verify_ssl":False})\ .configure_logging(logging.WARNING)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 })\ .build() hub.on_open(self.on_open) hub.on_close(self.on_close) return hub
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 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)
def test_enable_trace(self): hub = HubConnectionBuilder()\ .with_url(self.server_url, options={"verify_ssl":False})\ .configure_logging(logging.WARNING, socket_trace=True)\ .with_automatic_reconnect({ "type": "raw", "keep_alive_interval": 10, "reconnect_interval": 5, "max_attempts": 5 })\ .build() hub.on_open(self.on_open) hub.on_close(self.on_close) hub.start() self.assertTrue(websocket.isEnabledForDebug()) websocket.enableTrace(False) hub.stop()
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()
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 test_start(self): connection = HubConnectionBuilder()\ .with_url(self.server_url, options={"verify_ssl": False})\ .configure_logging(logging.ERROR)\ .build() _lock = threading.Lock() self.assertTrue(_lock.acquire(timeout=30)) connection.on_open(lambda: _lock.release()) connection.on_close(lambda: _lock.release()) result = connection.start() self.assertTrue(result) self.assertTrue(_lock.acquire(timeout=30)) # Released on open result = connection.start() self.assertFalse(result) 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])
class AbstractRiskClient(ABC): ## Game Logic ## @abstractmethod def choose_deploy(self, board: Board) -> Location: """returns the position to which the player's next army should be deployed""" pass @abstractmethod def choose_attack(self, board: Board) -> Tuple[Location, Location]: """returns the source and target of attack""" pass @abstractmethod def should_attack(self, board: Board) -> bool: """returns True if this player should attack given the current board and False otherwise""" pass ## Helper Functions for Logic ## def get_neighbors(self, territory: BoardTerritory, board: Board) -> Sequence[BoardTerritory]: """returns a list containing all territories neighboring the given territory""" def is_neighbor(other: BoardTerritory): return max(abs(territory.location.column - other.location.column), abs(territory.location.row - other.location.row)) == 1 return [t for t in board if is_neighbor(t)] def get_attacks( self, board: Board) -> Sequence[Tuple[BoardTerritory, BoardTerritory]]: """returns all possible attacks: (srouce, dest) territory pairs""" print("attacking...") return [(src, tgt) for src in self.get_mine(board) for tgt in self.get_neighbors(src, board) if src.armies > 1 and tgt.ownerName != self.name] def get_deployable(self, board: Board) -> Sequence[BoardTerritory]: """get locations that are legal for deploying an army""" return list(self.get_free(board)) + list(self.get_mine(board)) def get_free(self, board: Board) -> Sequence[BoardTerritory]: """returns a list of all unoccupied territories""" return [t for t in board if t.ownerName is None] def get_mine(self, board: Board) -> Sequence[BoardTerritory]: """returns a list of player's territories""" return [t for t in board if t.ownerName == self.name] ## Handlers ## # argument from signalr is actually a list of arguments (in this case a single list) def handle_deploy(self, dict_board: List[List[dict]]) -> None: print("handling deploy...") board: Board = board_from_dicts(*dict_board) deploy_location = self.choose_deploy(board) print(f"attempting to deploy to {deploy_location}") self.connection.send(MessageTypes.DeployRequest, [Location.Schema().dump(deploy_location)]) def handle_attack(self, dict_board: List[List[dict]]) -> None: print("handling attack...") board = board_from_dicts(*dict_board) if self.should_attack(board): attack = self.choose_attack(board) (source, target) = attack print(f"attempting to attack from {source} to {target}") self.connection.send(MessageTypes.AttackRequest, [ Location.Schema().dump(source), Location.Schema().dump(target) ]) else: print("done attacking") self.connection.send(MessageTypes.AttackComplete, []) def handle_join(self, name: List[str]) -> None: """saves the name assigned by the server""" print(f"confirmed join as {name}") [self.name] = name def handle_open(self): print( "connection opened and handshake received ready to send messages") # send our name only after connected self.connection.send(MessageTypes.Signup, [self.name]) def handle_close(self): print("Connection to server closed.") # exit main interrupt_main() def handle_status(self, status): print("Received status report.") def start(self, name, server, port): """runs the client, communicating with the server as necessary""" self.name = name self.connection = HubConnectionBuilder().with_url( f"{server}:{port}/riskhub").build() self.connection.on(MessageTypes.ReceiveMessage, print) self.connection.on(MessageTypes.SendMessage, print) self.connection.on(MessageTypes.SendStatus, self.handle_status) self.connection.on(MessageTypes.JoinConfirmation, self.handle_join) self.connection.on(MessageTypes.YourTurnToDeploy, self.handle_deploy) self.connection.on(MessageTypes.YourTurnToAttack, self.handle_attack) self.connection.on_open(self.handle_open) self.connection.on_close(self.handle_close) self.connection.start() # accept commands (mostly just waiting while the server interupts) command = "" while (command.lower() != 'exit'): print("Please enter a command ('exit' to exit): ", end="") command = input() def start_cli(self): """runs the client based on command-line arguments""" parser = argparse.ArgumentParser('RiskClient') parser.add_argument('--server', default="http://localhost") parser.add_argument('--port', type=int, default=5000) parser.add_argument('--name', default="python_person") args = parser.parse_args() try: self.start(name=args.name, server=args.server, port=args.port) except: print("Trouble with the connection. Do you have the right port?") print(f"Here is what we used: {args}")
import signalrcore from signalrcore.hub_connection_builder import HubConnectionBuilder import logging from signalrcore.hub_connection_builder import HubConnectionBuilder from dash.dependencies import Input, Output, State import plotly streamId = "" token = "{your_token}" server_url = "wss://reader-quix-{your_workspace}.platform.quix.ai/hub" hub_connection = HubConnectionBuilder()\ .with_url(server_url, options={"access_token_factory": lambda : token, })\ .build() hub_connection.on_open(print("Connection opened.")) hub_connection.on_close(lambda: on_close_handler()) def on_close_handler(): print("Connection closed.") if streamId: print("Reconnecting...") 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 = []
f"{username}:", end="") 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,
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}")
"*****@*****.**") 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()
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)
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 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)
else: lcd.clear() lcd.message = "No servers\nconnected" 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:
import logging import sys import time sys.path.append("./") from signalrcore.hub_connection_builder import HubConnectionBuilder connection = HubConnectionBuilder()\ .with_url("wss://localhost:5001/chathub", 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()) (_lock.acquire(timeout=30)) # Released on open connection.start() (_lock.acquire(timeout=30)) # Released on ReOpen connection.send("DisconnectMe", []) time.sleep(30) (_lock.acquire(timeout=30))