コード例 #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()

        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", []))
コード例 #2
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()
コード例 #3
0
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)
コード例 #4
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)
コード例 #5
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)
コード例 #6
0
ファイル: module.py プロジェクト: anagon-ai/anagon-ai
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))
コード例 #7
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)
コード例 #8
0
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()
コード例 #9
0
    .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)
コード例 #10
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])
コード例 #11
0
    global end
    end = True
    if error:
        print("error {0}".format(x))
    else:
        print("complete! ")
    global hub_connection

hub_connection = HubConnectionBuilder()\
    .with_url(server_url, options={"verify_ssl": False}) \
    .configure_logging(logging.DEBUG, socket_trace=True).build()

hub_connection.start()

hub_connection.stream("Counter", [10, 500]).subscribe({
    "next":
    lambda x: print("next callback: ", x),
    "complete":
    lambda x: bye(False, x),
    "error":
    lambda x: bye(True, x)
})

hub_connection.on("ReceiveMessage", print)

while not end:
    time.sleep(1)
    hub_connection.send("SendMessage", ["mandrewcito", "andresito"])

hub_connection.stop()
コード例 #12
0
server_url = "http://desarrollo.sreasons.com:8081/msmensajeriaapps/MSMensajeria/mensajeria-hub?ClienteId=PruebaPy"

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.hub

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("enviarSMS", print)
hub_connection.start()

username = "******"
message = "{\"Grupo:\"grupo123\",Metodo:\"enviarSMS\", Argumento: {\"Mensaje\":\"pls\"} }"

hub_connection.send("Subscribe", [username, "grupo123"])
hub_connection.send("Enviar", [username, message])

hub_connection.stop()

sys.exit(0)
コード例 #13
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()
コード例 #14
0
from signalrcore.hub_connection_builder import HubConnectionBuilder


def input_with_default(input_text, default_value):
    value = input(input_text.format(default_value))
    return default_value if value is None or value.strip() == "" else value


### server_url = input_with_default('Enter your server url(default: {0}): ', "wss://meirkr.com/chat")
server_url = "ws://meirkr.com/chat"
username = input_with_default('Enter your username (default: {0}): ', "python")

hub_connection = HubConnectionBuilder().with_url(
    server_url).with_automatic_reconnect({
        "type": "raw",
        "keep_alive_interval": 10,
        "reconnect_interval": 5,
        "max_attempts": 5
    }).build()
hub_connection.on("sendToAll", print)
hub_connection.start()
message = None
# Do login

while message != "exit()":
    message = input(">> ")
    if message is not None and message is not "exit()":
        hub_connection.send("sendToAll", [username, message])
hub_connection.stop()
コード例 #15
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()
コード例 #16
0
time.sleep(10)


def bye(error, x):
    if error:
        print("error {0}".format(x))
    else:
        print("complete! ")
    global hub_connection
    hub_connection.stop()
    sys.exit(0)


iteration = 0
subject = Subject()


def interval_handle():
    global iteration
    iteration += 1
    subject.next(str(iteration))
    if iteration == 10:
        subject.complete()


hub_connection.send("UploadStream", subject)

while iteration != 10:
    interval_handle()
    time.sleep(0.5)
コード例 #17
0
        "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()":
        hub_connection.send("ChatMessage", [message])

hub_connection.stop()

sys.exit(0)
コード例 #18
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)
コード例 #19
0
        "keep_alive_interval": 10,
        "reconnect_interval": 5,
        "max_attempts": 5
    }).build()

print("Hub connection built.")


def print_me(data):
    print(str(data[0]) + ": " + str(data[1]))


hub_connection.on("broadcastMessage", print_me)

hub_connection.start()
print("Hub connection started.")

message = ""

while message != "exit()":
    message = raw_input('')
    user = "******"
    try:
        hub_connection.send("Send", [user, message])
    except:
        print("Something went wrong.")

hub_connection.stop()
print("Connection stopped")

sys.exit(0)
コード例 #20
0
hub_connection.on("receive", print_me)

hub_connection.start()
print("Hub connection started.")

message = ""

while message != "exit()":
    message = input('>> ')

    name = "Item Name"
    description = "Item Description"
    serialNumber = "ABC123"
    itemCount = 5
    boxCount = 10
    placement = "Makati"
    expirationDate = "2020-02-25"
    manufacturingDate = "2020-02-25"

    try:
        hub_connection.send("Send", [
            name, description, serialNumber, itemCount, boxCount, placement,
            expirationDate, manufacturingDate
        ])
    except:
        print("Something went wrong.")

hub_connection.stop()
print("Connection stopped")

sys.exit(0)
コード例 #21
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)
コード例 #22
0
import logging
import time
import psutil
from signalrcore.hub_connection_builder import HubConnectionBuilder

server_url = "https://localhost:5001/chatHub"


hub_connection = HubConnectionBuilder()\
    .with_url(server_url, options={"verify_ssl": False}) \
    .configure_logging(logging.DEBUG, socket_trace=True).build()

hub_connection.start()

message = ""
max = 10
i = 0
while i < 100:
    time.sleep(3)
    hub_connection.send("SendMessage", [
        "andresito", {
            "cpu": psutil.cpu_percent(),
            "disk": psutil.disk_usage('/').percent,
            "ram": psutil.virtual_memory().percent
        }
    ])
    i += 1
コード例 #23
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}")
コード例 #24
0
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))

connection.send("DisconnectMe", [])
コード例 #25
0
hub_connection = HubConnectionBuilder()\
    .with_url(server_url, options={"verify_ssl": False}) \
    .configure_logging(logging.ERROR, socket_trace=False, handler=handler) \
    .with_automatic_reconnect({
            "type": "interval",
            "keep_alive_interval": 10,
            "intervals": [1, 3, 5, 6, 7, 87, 3]
        })\
    .with_hub_protocol(MessagePackHubProtocol())\
    .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("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],
                            lambda args: print(args, "<-------------------"))

hub_connection.stop()

sys.exit(0)