Link da mensagem#
Introdução#
O MessageLink permite que dois V5 Brain comuniquem enviando mensagens curtas com dados opcionais. Foi concebido para a coordenação entre robôs — como iniciar rotinas, partilhar resultados de sensores ou desencadear comportamentos noutro robô.
Cada utilização de send adiciona uma mensagem à fila do V5 Brain ligado, e a fila é lida pela ordem de chegada (FIFO). Se forem enviadas várias mensagens antes de o outro V5 Brain utilizar receive, estas serão armazenadas e devolvidas uma de cada vez, pela ordem em que foram enviadas. Como as mensagens podem ser colocadas em fila, enviar repetidamente o mesmo estado a cada iteração do ciclo pode criar uma acumulação; para lógica crítica em termos de tempo, envie apenas quando os valores se alteram.
Importante: Ambos os robots devem estar a executar projetos que utilizem MessageLink em simultâneo, caso contrário não será enviada/recebida qualquer mensagem.
Esta página utiliza o link como exemplo o nome MessageLink Substitua-o pelo nome que configurou se necessário.
Segue-se uma lista dos métodos disponíveis:
Criar um link#
Crie um MessageLink em ambos os V5 Brains para estabelecer um canal de comunicação entre eles — seja sem fios com os V5 Robot Radios ou através de um Smart Cable com fios — para que os robôs possam enviar mensagens entre si.
MessageLink(smartport, name, linktype, wired)
Parâmetro |
Descrição |
|---|---|
|
A porta inteligente utilizada para esta ligação é a porta à qual o rádio do robô V5 está ligado (sem fios) ou à qual o cabo inteligente está ligado (com fios). Escreve-se como |
|
O nome único a atribuir a este link, em formato de texto. |
|
A função que este Cérebro desempenhará para este par de ligações. Cada par deve incluir um Gestor e um Trabalhador:
|
|
Opcional. Indica se a ligação é com ou sem fios:
|
Código para o Robot 1
""" Create a wireless link in Port 1 name: VEXRoboticsLink123456789 linktype: Manager """ link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER)Código para o Robot 2
""" Create a wireless link in Port 1 name: VEXRoboticsLink123456789 linktype: Worker """ link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER)
Métodos disponíveis#
Após configurar o MessageLink e ligar os Brains, pode utilizar os métodos abaixo para enviar, receber e responder a mensagens.
is_linked#
O método is_linked retorna se os V5 Brains num MessageLink estão emparelhados entre si.
True– Os dois V5 Brains estão emparelhados e a comunicar neste link.False– Os dois V5 Brains não estão emparelhados nesta ligação.
Nota: É uma boa prática verificar sempre se os módulos V5 estão ligados no início de um projeto, antes de executar qualquer outro código.
Usage:
link.is_linked()
Parâmetros |
Descrição |
|---|---|
Este método não tem parâmetros. |
Código para o Robot 1
# Tell the other robot when the screen is being pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") # Continuously send if the screen is being pressed while True: if brain.screen.pressing(): link.send("pressed") else: link.send("released") wait(50, MSEC)Código para o Robot 2
# Display if the other robot's screen is being pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) # Continuously check if Robot 1 has sent "pressed" while True: brain.screen.clear_screen() brain.screen.set_cursor(1, 1) brain.screen.print("Robot 2 - Worker") brain.screen.next_row() if link.receive() == "pressed": brain.screen.new_line() brain.screen.print("Manager is being pressed!") wait(50, MSEC)
send#
send envia uma string e/ou um número inteiro e/ou um número de ponto flutuante para o outro V5 Brain ligado.
Usage:
send(string, integer, float)
Parâmetros |
Descrição |
|---|---|
|
A sequência de caracteres a enviar para o outro V5 Brain ligado. |
|
Opcional. Um número inteiro para enviar ao outro V5 Brain ligado. |
|
Opcional. Um número de ponto flutuante para enviar ao outro V5 Brain ligado. Os números de ponto flutuante são formatados com 4 casas decimais; se forem fornecidas menos casas decimais, serão adicionados zeros à direita até que sejam apresentados 4. |
Se apenas a string string for enviada, o outro V5 Brain ligado receberá exatamente essa string.
Se forem incluídos integer e/ou float , o Brain receptor recebe uma única string codificada que combina todos os campos por esta ordem: .string_integer_float
Exemplo: Usando link.send(“string”, 1, 2.55) é recebido como .string_1_2.5500.
Código para o Robot 1
# Tell the other robot when the screen is being pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") # Continuously send if the screen is being pressed while True: if brain.screen.pressing(): link.send("pressed") else: link.send("released") wait(50, MSEC)Código para o Robot 2
# Display if the other robot's screen is being pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) # Continuously check if Robot 1 has sent "pressed" while True: brain.screen.clear_screen() brain.screen.set_cursor(1, 1) brain.screen.print("Robot 2 - Worker") brain.screen.next_row() if link.receive() == "pressed": brain.screen.new_line() brain.screen.print("Manager is being pressed!") wait(50, MSEC)
Código para o Robot 1
# Tell the other robot where the screen was pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") brain.screen.next_row() brain.screen.print("Tap to send circles") # Send the coordinates whenever the screen is pressed while True: if brain.screen.pressing(): x = brain.screen.x_position() y = brain.screen.y_position() link.send("touch", x, y) wait(10, MSEC)Código para o Robot 2
# Draw a circle where Robot 1's screen was pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 2 - Worker") while True: # Get the full encoded string circle_coordinates = link.receive(200) if circle_coordinates: # Split the encoded string by _ parts = circle_coordinates.split("_") if len(parts) == 3: # Convert the coordinates back into numbers x = float(parts[1]) y = float(parts[2]) brain.screen.set_fill_color(Color.WHITE) brain.screen.draw_circle(x, y, 20) wait(10, MSEC)
receive#
receive returns the next queued message from the other linked V5 Brain. Messages are read in FIFO order (oldest unread first). If the queue is empty when receive is called, it waits up to the specified timeout for a new message. If no message arrives in that window, receive returns None, and any message sent afterward remains in the queue to be read the next time receive is used.
Se o outro V5 Brain ligado enviar apenas uma string string, receive e devolverá exactamente essa string.
Se o outro V5 Brain ligado enviar um número inteiro e/ou de ponto flutuante, receive e devolve uma única string codificada que combina todos os campos por esta ordem: .string_integer_float
Por exemplo, se o outro V5 Brain ligado utilizar link.send(“string”, 1, 2.55), então a utilização de link.receive() devolve uma string codificada como .string_1_2.5500. Pode dividir esta string codificada (ver exemplos abaixo) para extrair o nome da mensagem, valores inteiros e de ponto flutuante.
Se preferir evitar a divisão/análise manual, utilize received para registar um manipulador para um nome de mensagem específico; o manipulador recebe os valores enviados como argumentos.
Usage:
receive(timeout)
Parâmetros |
Descrição |
|---|---|
|
Opcional. Tempo em milissegundos |
Código para o Robot 1
# Tell the other robot when the screen is being pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") # Continuously send if the screen is being pressed while True: if brain.screen.pressing(): link.send("pressed") else: link.send("released") wait(50, MSEC)Código para o Robot 2
# Display if the other robot's screen is being pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) # Continuously check if Robot 1 has sent "pressed" while True: brain.screen.clear_screen() brain.screen.set_cursor(1, 1) brain.screen.print("Robot 2 - Worker") brain.screen.next_row() if link.receive() == "pressed": brain.screen.new_line() brain.screen.print("Manager is being pressed!") wait(50, MSEC)
Código para o Robot 1
# Send a math problem for the other Brain to solve # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") """ Change whether to "add" or "subtract", then what numbers to use in the operation. """ link.send("add", 7, 2.5)Código para o Robot 2
# Solve the math problem that the other Brain sends # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 2 - Worker") brain.screen.next_row() math_problem = link.receive() if math_problem: # Split the encoded string by _ parts = math_problem.split("_") if len(parts) == 3: # Remove the . from the beginning of the string operator = "".join([c for c in parts[0] if c.isalpha()]) # Separate out the numbers for the operation a = int(parts[1]) b = float(parts[2]) # Use what operator was sent if operator == "add": result = a + b elif operator == "subtract": result = a - b # If neither add or subtract is sent, do nothing else: pass brain.screen.print("Result = ", result)
received#
received regista uma função a ser chamada sempre que o V5 Brain receber uma mensagem enviada.
Usage:
link.received(message, arg)
Parâmetros |
Descrição |
|---|---|
|
O nome da mensagem (string) a corresponder. Quando o nome de uma mensagem recebida corresponde a este valor, é chamada a função de retorno de chamada |
|
Uma função previamente definida que é executada quando o V5 Brain recebe uma mensagem correspondente à mensagem |
received chamada de retorno com quatro argumentos:
Subscrição de callback:
callback(message, linkname, index, value)
Discussão |
Descrição |
|---|---|
|
O nome da mensagem recebida (por exemplo, |
|
O nome do link a partir do qual a mensagem foi recebida. |
|
O valor inteiro enviado com a mensagem (se fornecido). |
|
O valor float enviado com a mensagem (se fornecido). |
Código para o Robot 1
# Send a math problem for the other Brain to solve # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") """ Change whether to "add" or "subtract", then what numbers to use in the operation. """ link.send("add", 7, 2.5)Código para o Robot 2
# Solve the math problem that the other Brain sends # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 2 - Worker") brain.screen.next_row() # add if "add" is received def add_cmd(message, linkname, a, b): result = a + b brain.screen.print("Result = ", result) # subtract if ""subtract" is received def subtract_cmd(message, linkname, a, b): result = a - b brain.screen.print("Result = ", result) # Create event handlers for "add" and "subtract" link.received("add", add_cmd) link.received("subtract", subtract_cmd)