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()
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
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}")
handler = logging.StreamHandler() 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)
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)
import logging from signalrcore.hub_connection_builder import HubConnectionBuilder handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) # HubConnectionBuilder.hub = 'ESLNotificationHub' notification = HubConnectionBuilder()\ .with_url('http://os3.prestige.de:8080/?version=1&serial=1349001533&store=4', options={ "verify_ssl": False, "headers": { }})\ .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() notification.on_open(lambda: print( "connection opened and handshake received ready to send messages")) notification.on_close(lambda: print("connection closed")) notification.on_error(lambda: print("notification error")) notification.start() # notification.stop()