コード例 #1
0
    def test_no_reconnect(self):
        connection = HubConnectionBuilder()\
            .with_url(self.server_url, options={"verify_ssl": False})\
            .configure_logging(logging.ERROR)\
            .build()

        _lock = threading.Lock()

        _lock.acquire(timeout=10)

        connection.on_open(lambda: _lock.release())

        connection.on("ReceiveMessage", lambda _: _lock.release())

        connection.start()

        self.assertTrue(_lock.acquire(timeout=10))  # Released on ReOpen
        
        connection.send("DisconnectMe", [])

        self.assertTrue(_lock.acquire(timeout=10))

        time.sleep(10)

        self.assertRaises(
            HubConnectionError,
            lambda: connection.send("DisconnectMe", []))

        connection.stop()
        del _lock
コード例 #2
0
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")
コード例 #3
0
    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
コード例 #4
0
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)
コード例 #5
0
ファイル: StarterBot.py プロジェクト: juan-db/2021-Galaxio
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()
コード例 #6
0
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)
コード例 #7
0
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)
コード例 #8
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()
コード例 #9
0
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)
コード例 #10
0
    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()
コード例 #11
0
                              "*****@*****.**")
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()
コード例 #12
0
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)
コード例 #13
0
class NotificationReceiver:
    """
    This object is used to receive notifications.
    This should only be generated once per client as to not duplicate notifications.
    """
    def __init__(self, cso):
        self.cso = cso
        self.requests = cso.requests
        self.evtloop = cso.evtloop
        self.negotiate_request = None
        self.wss_url = None
        self.connection = None

    async def get_unread_notifications(self):
        unread_req = await self.requests.get(
            url=
            "https://notifications.roblox.com/v2/stream-notifications/unread-count"
        )
        return UnreadNotifications(unread_req.json())

    async def initialize(self):
        self.negotiate_request = await self.requests.get(
            url="https://realtime.roblox.com/notifications/negotiate"
            "?clientProtocol=1.5"
            "&connectionData=%5B%7B%22name%22%3A%22usernotificationhub%22%7D%5D",
            cookies=self.requests.session.cookies)
        self.wss_url = f"wss://realtime.roblox.com/notifications?transport=websockets" \
                       f"&connectionToken={quote(self.negotiate_request.json()['ConnectionToken'])}" \
                       f"&clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22usernotificationhub%22%7D%5D"
        self.connection = HubConnectionBuilder()
        self.connection.with_url(
            self.wss_url,
            options={
                "headers": {
                    "Cookie":
                    f".ROBLOSECURITY={self.requests.session.cookies['.ROBLOSECURITY']};"
                },
                "skip_negotiation": False
            })

        def on_message(_self, raw_notification):
            """
            Internal callback when a message is received.
            """
            try:
                notification_json = json.loads(raw_notification)
            except json.decoder.JSONDecodeError:
                return
            if len(notification_json) > 0:
                notification = Notification(notification_json)
                self.evtloop.run_until_complete(
                    self.on_notification(notification))
            else:
                return

        self.connection.with_automatic_reconnect({
            "type": "raw",
            "keep_alive_interval": 10,
            "reconnect_interval": 5,
            "max_attempts": 5
        }).build()

        self.connection.hub.on_message = on_message

        self.connection.start()

    def close(self):
        """
        Closes the connection and stops receiving notifications.
        """
        self.connection.stop()
コード例 #14
0
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])
コード例 #15
0
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()
sys.exit(0)
コード例 #16
0
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()
コード例 #17
0
ファイル: easee_manager.py プロジェクト: skela/home
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}")