Lien vers le message#
Introduction#
MessageLink permet à deux EXP Brains de communiquer en envoyant de courts messages contenant éventuellement de petites données. Il est conçu pour la coordination entre robots, notamment pour lancer des routines, partager des résultats de capteurs ou déclencher des comportements sur un autre robot.
Chaque utilisation de send ajoute un message à la file d’attente du cerveau EXP lié, et cette file est lue selon le principe du premier entré, premier sorti (FIFO). Si plusieurs messages sont envoyés avant que l’autre cerveau EXP n’utilise receive, ils seront stockés et renvoyés un par un, dans l’ordre de leur envoi. Étant donné que les messages peuvent être mis en file d’attente, l’envoi répété du même statut à chaque boucle peut créer un engorgement ; pour une logique critique en termes de temps, n’envoyez des messages que lorsque les valeurs changent.
Important : Les deux robots doivent exécuter simultanément des projets utilisant MessageLink , sinon aucun message ne sera envoyé/reçu.
This page uses link as the example MessageLink name. Replace it with your own configured name as needed.
Vous trouverez ci-dessous une liste des méthodes disponibles :
Créer un lien#
Créez un MessageLink sur les deux EXP Brains pour établir un canal de communication entre eux, soit sans fil avec des radios robotiques V5, soit par l’intermédiaire d’un câble intelligent câblé, afin que les robots puissent s’envoyer des messages.
MessageLink(smartport, name, linktype, wired)
Paramètre |
Description |
|---|---|
|
Le port intelligent utilisé pour cette liaison est celui auquel la radio du robot V5 est connectée (sans fil) ou celui auquel le câble intelligent est branché (avec fil). Il est indiqué sous la forme |
|
The unique name to give this link as a string. |
|
Rôle attribué à cette paire de liens par le Cerveau. Chaque paire doit inclure un Gestionnaire et un Travailleur :
|
|
Facultatif. Indiquez si la connexion est filaire ou sans fil :
|
Code pour le robot 1
""" Create a wireless link in Port 1 name: VEXRoboticsLink123456789 linktype: Manager """ link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER)Code pour Robot 2
""" Create a wireless link in Port 1 name: VEXRoboticsLink123456789 linktype: Worker """ link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER)
Méthodes disponibles#
Une fois votre MessageLink configuré et les Brains connectés, vous pouvez utiliser les méthodes ci-dessous pour envoyer, recevoir et répondre aux messages.
is_linked#
La méthode is_linked renvoie si les EXP Brains d’un MessageLink sont appariés entre eux.
True– Les deux cerveaux EXP sont appariés et communiquent via ce lien.False– Les deux cerveaux EXP ne sont pas appariés sur ce lien.
Remarque : Il est recommandé de toujours vérifier que les EXP Brains sont bien liés au début d’un projet avant d’exécuter tout autre code.
Usage:
link.is_linked()
Paramètres |
Description |
|---|---|
Cette méthode ne comporte aucun paramètre. |
Code pour le 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)Code pour 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 envoie une chaîne de caractères et/ou un entier et/ou un nombre flottant à l’autre EXP Brain lié.
Usage:
send(string, integer, float)
Paramètres |
Description |
|---|---|
|
La chaîne de caractères à envoyer à l’autre EXP Brain lié. |
|
Facultatif. Un entier à envoyer à l’autre EXP Brain lié. |
|
Facultatif. Nombre décimal à envoyer à l’autre EXP Brain lié. Les nombres décimaux sont formatés avec 4 décimales ; si moins de décimales sont fournies, des zéros sont ajoutés à la fin jusqu’à ce que 4 décimales soient affichées. |
Si seule la chaîne string est envoyée, l’autre EXP Brain lié reçoit exactement cette chaîne.
Si les champs integer et/ou float sont inclus, le système Brain reçoit une seule chaîne encodée qui combine tous les champs dans cet ordre : .string_integer_float
Exemple : En utilisant link.send(“string”, 1, 2.55) est reçu comme .string_1_2.5500.
Code pour le 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)Code pour 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)
Code pour le 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)Code pour 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 EXP 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.
Si l’autre EXP Brain lié a envoyé uniquement une chaîne string, receive renvoie cette chaîne exacte.
Si l’autre EXP Brain lié a envoyé un entier et/ou un nombre à virgule flottante, receive renvoie une seule chaîne encodée qui combine tous les champs dans cet ordre : .string_integer_float
Par exemple, si l’autre EXP Brain lié utilise link.send(“string”, 1, 2.55), alors link.receive() renvoie une chaîne encodée telle que .string_1_2.5500. Vous pouvez diviser cette chaîne encodée (voir les exemples ci-dessous) pour extraire le nom du message, l’entier et les valeurs flottantes.
Si vous préférez éviter le fractionnement/l’analyse manuel, utilisez received pour enregistrer un gestionnaire pour un nom de message spécifique ; le gestionnaire reçoit les valeurs envoyées comme arguments.
Usage:
receive(timeout)
Paramètres |
Description |
|---|---|
|
Optionnel. Durée (en millisecondes |
Code pour le 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)Code pour 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)
Code pour le 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)Code pour 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 enregistre une fonction à appeler chaque fois que le cerveau EXP reçoit un message envoyé.
Usage:
link.received(message, arg)
Paramètres |
Description |
|---|---|
|
Nom du message (chaîne de caractères) à rechercher. Lorsqu’un message reçu trouve un nom correspondant à cette valeur, la fonction de rappel |
|
Une fonction précédemment définie qui s’exécute lorsque le cerveau EXP reçoit un message correspondant au message |
received rappel est appelé avec quatre arguments :
Signature de rappel :
callback(message, linkname, index, value)
Argument |
Description |
|---|---|
|
Le nom du message reçu (par exemple, |
|
Nom du lien à partir duquel le message a été reçu. |
|
La valeur entière envoyée avec le message (si elle est fournie). |
|
La valeur flottante envoyée avec le message (si elle est fournie). |
Code pour le 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)Code pour 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)