Посилання на повідомлення#
Вступ#
MessageLink дозволяє двом роботам V5 Brains спілкуватися, надсилаючи короткі рядкові повідомлення з необов’язковими невеликими даними. Він розроблений для координації між роботами, наприклад, для запуску процедур, обміну результатами датчиків або запуску поведінки в іншого робота.
Кожне використання send додає повідомлення до черги пов’язаного V5 Brain, і черга зчитується в порядку першої надсилання (FIFO). Якщо кілька повідомлень надіслано до того, як інший V5 Brain використає receive, вони будуть збережені та повернуті по одному в порядку надсилання. Оскільки повідомлення можуть стояти в черзі, багаторазове надсилання одного й того ж статусу в кожному циклі може створити затримку; для логіки, критичної за часом, надсилайте лише тоді, коли значення змінюються.
Важливо: Обидва роботи повинні одночасно запускати проекти, що використовують MessageLink , інакше повідомлення не будуть надіслані/отримані.
This page uses link as the example MessageLink name. Replace it with your own configured name as needed.
Нижче наведено список доступних методів:
Створити посилання#
Створіть MessageLink на обох роботах V5 Brains, щоб встановити канал зв’язку між ними — або бездротовим способом за допомогою радіостанцій V5 Robot Radio, або через дротовий Smart Cable — щоб роботи могли надсилати повідомлення один одному.
MessageLink(smartport, name, linktype, wired)
Параметр |
Опис |
|---|---|
|
Розумний порт, що використовується для цього з’єднання — порт, до якого підключено радіо V5 Robot (бездротовий зв’язок) або до якого підключено розумний кабель (дротовий зв’язок). Записується як |
|
Унікальна назва, яка буде надана цьому посиланню у вигляді рядка. |
|
Роль, яку цей Мозок використовуватиме для цієї пари посилань. Кожна пара повинна містити одного Менеджера та одного Працівника:
|
|
Необов’язково. Чи є це з’єднання дротовим, чи бездротовим:
|
Код для робота 1
""" Create a wireless link in Port 1 name: VEXRoboticsLink123456789 linktype: Manager """ link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER)Код для Робота 2
""" Create a wireless link in Port 1 name: VEXRoboticsLink123456789 linktype: Worker """ link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER)
Доступні методи#
Після налаштування MessageLink та підключення Brains ви можете використовувати наведені нижче методи для надсилання, отримання та відповіді на повідомлення.
is_linked#
Метод is_linked повертає, чи сполучені V5 Brains на MessageLink один з одним.
True– Два мозку V5 спарені та спілкуються через цей канал.False– Два мізки V5 не спарені на цьому зв’язку.
Примітка: Рекомендується завжди перевіряти, чи підключені V5 Brains на початку проєкту, перш ніж запускати будь-який подальший код.
Usage:
link.is_linked()
Параметри |
Опис |
|---|---|
Цей метод не має параметрів. |
Код для робота 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)Код для Робота 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 надсилає рядок та/або ціле число та/або число з плаваючою комою до іншого підключеного V5 Brain.
Usage:
send(string, integer, float)
Параметри |
Опис |
|---|---|
|
Рядок, який потрібно надіслати іншому підключеному V5 Brain. |
|
Необов’язково. Ціле число для надсилання іншому підключеному V5 Brain. |
|
Необов’язково. Число з плаваючою комою для надсилання до іншого підключеного V5 Brain. Числа з плаваючою комою форматуються до 4 знаків після коми; якщо вказано менше знаків після коми, додаються завершальні нулі, доки не буде показано 4. |
If only string is sent, the other linked V5 Brain receives that exact string.
Якщо включено integer та/або float , приймаючий Brain отримує один закодований рядок, який об’єднує всі поля в такому порядку: .string_integer_float
Приклад: При використанні link.send(“string”, 1, 2.55) отримується як .string_1_2.5500.
Код для робота 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)Код для Робота 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)
Код для робота 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)Код для Робота 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 повертає наступне повідомлення з черги від іншого підключеного V5 Brain. Повідомлення зчитуються в порядку FIFO (спочатку найстаріші непрочитані). Якщо черга порожня, коли викликається receive , вона очікує нового повідомлення до зазначеного timeout Якщо в цьому вікні повідомлення не надходить, receive повертає None, і будь-яке повідомлення, надіслане після цього, залишається в черзі для зчитування під час наступного використання receive.
Якщо інший пов’язаний V5 Brain надіслав лише рядок string, receive повертає саме цей рядок.
Якщо інший пов’язаний V5 Brain надіслав ціле число та/або число з плаваючою комою, receive повертає один закодований рядок, який об’єднує всі поля в такому порядку: .string_integer_float
Наприклад, якщо інший пов’язаний V5 Brain використовує link.send(“string”, 1, 2.55), то використання link.receive() повертає закодований рядок, такий як .string_1_2.5500. Ви можете розділити цей закодований рядок (див. приклади нижче), щоб витягти назву повідомлення, ціле число та значення з плаваючою комою.
Якщо ви бажаєте уникнути ручного розділення/парсингу, використовуйте received для реєстрації обробника для певного імені повідомлення; обробник отримує надіслані значення як аргументи.
Usage:
receive(timeout)
Параметри |
Опис |
|---|---|
|
Необов’язково. Скільки часу в мілісекундах |
Код для робота 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)Код для Робота 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)
Код для робота 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)Код для Робота 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 реєструє функцію, яка викликається щоразу, коли V5 Brain отримує надіслане повідомлення.
Usage:
link.received(message, arg)
Параметри |
Опис |
|---|---|
|
The message name (string) to match. When a received message’s name matches this value, the |
|
Раніше визначена function, яка виконується, коли V5 Brain отримує повідомлення, що відповідає |
received викликів зворотних викликів з чотирма аргументами:
Підпис зворотного виклику:
callback(message, linkname, index, value)
Аргумент |
Опис |
|---|---|
|
Назва отриманого повідомлення (наприклад, |
|
Назва посилання, з якого було отримано повідомлення. |
|
Цілочисельне значення, що надсилається разом із повідомленням (якщо вказано). |
|
Значення з плаваючою комою, що надсилається разом із повідомленням (якщо вказано). |
Код для робота 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)Код для Робота 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)