├── docs
├── pilot_atts.png
├── osd_settings.png
├── 3DPrint
│ └── wirex-1.webp
└── general_settings.png
├── .github
└── workflows
│ └── rhfest.yaml
├── custom_plugins
└── vrxc_elrs
│ ├── manifest.json
│ ├── connections.py
│ ├── msp.py
│ ├── __init__.py
│ └── elrs_backpack.py
├── .gitignore
├── README.md
└── LICENSE
/docs/pilot_atts.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/i-am-grub/vrxc_elrs/HEAD/docs/pilot_atts.png
--------------------------------------------------------------------------------
/docs/osd_settings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/i-am-grub/vrxc_elrs/HEAD/docs/osd_settings.png
--------------------------------------------------------------------------------
/docs/3DPrint/wirex-1.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/i-am-grub/vrxc_elrs/HEAD/docs/3DPrint/wirex-1.webp
--------------------------------------------------------------------------------
/docs/general_settings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/i-am-grub/vrxc_elrs/HEAD/docs/general_settings.png
--------------------------------------------------------------------------------
/.github/workflows/rhfest.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | name: RHFest
3 |
4 | on:
5 | push:
6 | branches:
7 | - master
8 | pull_request:
9 |
10 | jobs:
11 | validation:
12 | name: Validation
13 | runs-on: ubuntu-latest
14 | steps:
15 | - name: Check out code from GitHub
16 | uses: actions/checkout@v4.2.2
17 |
18 | - name: Run RHFest validation
19 | uses: docker://ghcr.io/rotorhazard/rhfest-action:v2
--------------------------------------------------------------------------------
/custom_plugins/vrxc_elrs/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "domain": "vrxc_elrs",
3 | "name": "VRxC ELRS",
4 | "author": "Bryce \"GRUBBY\" Gruber",
5 | "author_uri": "https://github.com/i-am-grub",
6 | "description": "The ExpressLRS Backpack integrated into RotorHazard",
7 | "documentation_uri": "https://github.com/i-am-grub/VRxC_ELRS",
8 | "required_rhapi_version": "1.2",
9 | "version": "1.4.3",
10 | "category": ["OSD & VRx Control"]
11 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/#use-with-ide
110 | .pdm.toml
111 |
112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113 | __pypackages__/
114 |
115 | # Celery stuff
116 | celerybeat-schedule
117 | celerybeat.pid
118 |
119 | # SageMath parsed files
120 | *.sage.py
121 |
122 | # Environments
123 | .env
124 | .venv
125 | env/
126 | venv/
127 | ENV/
128 | env.bak/
129 | venv.bak/
130 |
131 | # Spyder project settings
132 | .spyderproject
133 | .spyproject
134 |
135 | # Rope project settings
136 | .ropeproject
137 |
138 | # mkdocs documentation
139 | /site
140 |
141 | # mypy
142 | .mypy_cache/
143 | .dmypy.json
144 | dmypy.json
145 |
146 | # Pyre type checker
147 | .pyre/
148 |
149 | # pytype static type analyzer
150 | .pytype/
151 |
152 | # Cython debug symbols
153 | cython_debug/
154 |
155 | # PyCharm
156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158 | # and can be added to the global gitignore or merged into this file. For a more nuclear
159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160 | #.idea/
161 |
--------------------------------------------------------------------------------
/custom_plugins/vrxc_elrs/connections.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from dataclasses import dataclass
3 | from enum import Enum
4 | from typing import Protocol, Union
5 |
6 | import gevent
7 | import gevent.queue
8 | import gevent.socket as socket
9 | import serial
10 | import serial.tools.list_ports
11 | from gevent.queue import Queue
12 |
13 | from .msp import MSPPacket, MSPPacketType, MSPTypes
14 |
15 | SOCKET_PORT = 8080
16 | AVOIDED_PORTS = {"/dev/ttyAMA0", "/dev/ttyAMA10", "COM1"}
17 |
18 | logger = logging.getLogger(__name__)
19 |
20 |
21 | class BackpackConnection(Protocol):
22 | """
23 | Protocol for backpack connections
24 | """
25 |
26 | connected: bool
27 |
28 | def __init__(self, send_queue: Queue, recieve_queue: Queue): ...
29 |
30 | def connect(self, **kwargs) -> bool: ...
31 |
32 | def disconnect(self): ...
33 |
34 |
35 | @dataclass
36 | class ConnectionType:
37 | """
38 | Dataclass for custom connection enum
39 | """
40 |
41 | type_: type["BackpackConnection"]
42 | id_: int
43 |
44 |
45 | class SerialConnection:
46 | """
47 | Backpack over serial connection
48 | """
49 |
50 | _send_greenlet: Union[gevent.Greenlet, None] = None
51 | _recieve_greenlet: Union[gevent.Greenlet, None] = None
52 | _parsing_greenlet: Union[gevent.Greenlet, None] = None
53 |
54 | def __init__(self, send_queue: Queue, recieve_queue: Queue):
55 | self._connected = False
56 | self._send_queue = send_queue
57 | self._recieve_queue = recieve_queue
58 | self._connection: Union[serial.Serial, None] = None
59 | self._parsing_queue = gevent.queue.Queue()
60 |
61 | @property
62 | def connected(self) -> bool:
63 | return self._connected
64 |
65 | def connect(self) -> bool:
66 | packet = MSPPacket()
67 | packet.set_function(MSPTypes.MSP_ELRS_GET_BACKPACK_VERSION)
68 |
69 | logger.info("Attempting to find backpack")
70 |
71 | avaliable_port = {port.device for port in serial.tools.list_ports.comports()}
72 |
73 | for port in avaliable_port - AVOIDED_PORTS:
74 |
75 | try:
76 | connection = serial.Serial(
77 | port=port,
78 | baudrate=460800,
79 | bytesize=8,
80 | parity="N",
81 | stopbits=1,
82 | timeout=5,
83 | xonxoff=0,
84 | rtscts=0,
85 | write_timeout=5,
86 | )
87 | except:
88 | logger.warning(
89 | "Failed to open serial device. Attempting to connect to new device..."
90 | )
91 | continue
92 |
93 | # Some devkits need extra time to establish the connection
94 | gevent.sleep(2)
95 |
96 | # Clear out any previous data in the serial buffer
97 | connection.read_all()
98 |
99 | try:
100 | connection.write(packet.get_packet())
101 | except:
102 | logger.error(
103 | "Failed to write to open serial device. Attempting to connect to new device..."
104 | )
105 | connection.close()
106 | continue
107 |
108 | gevent.sleep(0.2)
109 |
110 | data = connection.read_all()
111 | for packet in MSPPacket.packets_from_bytes(data):
112 | if (
113 | packet.type_ == MSPPacketType.RESPONSE
114 | and packet.function == MSPTypes.MSP_ELRS_GET_BACKPACK_VERSION
115 | ):
116 | self._connection = connection
117 | self._connected = True
118 | break
119 |
120 | if self._connected:
121 | break
122 |
123 | else:
124 | return False
125 |
126 | self._parsing_greenlet = gevent.spawn(self._parser)
127 | self._send_greenlet = gevent.spawn(self._send)
128 | self._recieve_greenlet = gevent.spawn(self._recieve)
129 | return True
130 |
131 | def _send(self) -> None:
132 | """
133 | Sends data from the queue over the socket
134 | """
135 | assert self._connection is not None
136 |
137 | try:
138 | while self._connected:
139 | packet: MSPPacket = self._send_queue.get()
140 | self._connection.write(packet.get_packet())
141 |
142 | finally:
143 | self._connected = False
144 | self._send_greenlet = None
145 | self.disconnect()
146 |
147 | def _parser(self) -> None:
148 | """
149 | Parses incoming data
150 | """
151 | for packet in MSPPacket.packets_from_bytes_queue(self._parsing_queue):
152 | self._recieve_queue.put(packet)
153 |
154 | def _recieve(self) -> None:
155 | """
156 | Recieves data from the socket and adds it to the queue
157 | """
158 | assert self._connection is not None
159 |
160 | try:
161 | while self._connected:
162 | data = self._connection.read_all()
163 | self._parsing_queue.put(data)
164 | gevent.sleep(0.2)
165 |
166 | finally:
167 | self._connected = False
168 | self._recieve_greenlet = None
169 | self.disconnect()
170 |
171 | def disconnect(self):
172 | """
173 | _summary_
174 | """
175 | self._connected = False
176 |
177 | if self._parsing_greenlet is not None:
178 | self._parsing_greenlet.kill()
179 |
180 | if self._send_greenlet is not None:
181 | self._send_greenlet.kill()
182 |
183 | if self._recieve_greenlet is not None:
184 | self._recieve_greenlet.kill()
185 |
186 | self._connection.close()
187 |
188 |
189 | class SocketConnection:
190 | """
191 | Backpack over socket connection
192 | """
193 |
194 | _send_greenlet: Union[gevent.Greenlet, None] = None
195 | _recieve_greenlet: Union[gevent.Greenlet, None] = None
196 |
197 | def __init__(self, send_queue: Queue, recieve_queue: Queue):
198 | self._connected = False
199 | self._send_queue = send_queue
200 | self._recieve_queue = recieve_queue
201 | self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
202 |
203 | @property
204 | def connected(self) -> bool:
205 | return self._connected
206 |
207 | def connect(self, ip_addr: str) -> bool:
208 | """
209 | Establishes the socket connection
210 |
211 | :param ip_addr: The IP address to connect to
212 | """
213 | self._socket.settimeout(5)
214 | packet = MSPPacket()
215 | packet.set_function(MSPTypes.MSP_ELRS_GET_BACKPACK_VERSION)
216 |
217 | try:
218 | self._socket.connect((ip_addr, SOCKET_PORT))
219 | self._socket.sendall(packet.get_packet())
220 | data = self._socket.recv(128)
221 | for packet in MSPPacket.packets_from_bytes(data):
222 | if (
223 | packet.type_ == MSPPacketType.RESPONSE
224 | and packet.function == MSPTypes.MSP_ELRS_GET_BACKPACK_VERSION
225 | ):
226 | self._connected = True
227 | break
228 | else:
229 | self._socket.close()
230 | return False
231 |
232 | except TimeoutError:
233 | self._socket.close()
234 | return False
235 |
236 | self._socket.settimeout(None)
237 |
238 | self._send_greenlet = gevent.spawn(self._send)
239 | self._recieve_greenlet = gevent.spawn(self._recieve)
240 |
241 | return True
242 |
243 | def _send(self) -> None:
244 | """
245 | Sends data from the queue over the socket
246 | """
247 | try:
248 | while self._connected:
249 | packet: MSPPacket = self._send_queue.get()
250 |
251 | timeout = gevent.Timeout(1)
252 | timeout.start()
253 | try:
254 | self._socket.sendall(packet.get_packet())
255 | finally:
256 | timeout.close()
257 | except gevent._socketcommon.cancel_wait_ex:
258 | ...
259 |
260 | finally:
261 | self._connected = False
262 | self._send_greenlet = None
263 | self.disconnect()
264 |
265 | def _recieve(self) -> None:
266 | """
267 | Recieves data from the socket and adds it to the queue
268 | """
269 | try:
270 | while self._connected:
271 | data = self._socket.recv(128)
272 | for packet in MSPPacket.packets_from_bytes(data):
273 | self._recieve_queue.put(packet)
274 | except gevent._socketcommon.cancel_wait_ex:
275 | ...
276 |
277 | finally:
278 | self._connected = False
279 | self._recieve_greenlet = None
280 | self.disconnect()
281 |
282 | def disconnect(self):
283 | """
284 | Disconnects the socket
285 | """
286 | self._connected = False
287 |
288 | if self._send_greenlet is not None:
289 | self._send_greenlet.kill()
290 |
291 | if self._recieve_greenlet is not None:
292 | self._recieve_greenlet.kill()
293 |
294 | self._socket.close()
295 |
296 |
297 | class ConnectionTypeEnum(ConnectionType, Enum):
298 | """
299 | Enum for different connection selections
300 | """
301 |
302 | USB = SerialConnection, 1
303 | ONBOARD = SerialConnection, 2
304 | SOCKET = SocketConnection, 3
305 |
--------------------------------------------------------------------------------
/custom_plugins/vrxc_elrs/msp.py:
--------------------------------------------------------------------------------
1 | """
2 | ExpressLRS Backpack bridge
3 | """
4 |
5 | import sys
6 | from collections.abc import Generator, Sequence
7 | from enum import Enum, IntEnum, auto
8 | from typing import Union
9 |
10 | from gevent.queue import Queue
11 |
12 | if sys.version_info >= (3, 11):
13 | from typing import Self
14 | else:
15 | from typing_extensions import Self
16 |
17 | MSP_HEADER_LENGTH = 8
18 |
19 |
20 | class MSPState(Enum):
21 | IDLE = auto()
22 | HEADER_START = auto()
23 | HEADER_X = auto()
24 | HEADER_V2_NATIVE = auto()
25 | PAYLOAD_V2_NATIVE = auto()
26 | CHECKSUM_V2_NATIVE = auto()
27 | COMMAND_RECEIVED = auto()
28 |
29 |
30 | class MSPPacketType(IntEnum):
31 | UNKNOWN = ord("!")
32 | COMMAND = ord("<")
33 | RESPONSE = ord(">")
34 |
35 |
36 | class MSPTypes(IntEnum):
37 | """
38 | ExpressLRS Backpack MSP types
39 | """
40 |
41 | MSP_ELRS_FUNC = 0x4578 # ['E','x']
42 |
43 | MSP_SET_RX_CONFIG = 45
44 | MSP_VTX_CONFIG = 88 # out message Get vtx settings - betaflight
45 | MSP_SET_VTX_CONFIG = 89 # in message Set vtx settings - betaflight
46 | MSP_EEPROM_WRITE = 250 # in message no param
47 |
48 | # ELRS specific opcodes
49 | MSP_ELRS_RF_MODE = 0x06
50 | MSP_ELRS_TX_PWR = 0x07
51 | MSP_ELRS_TLM_RATE = 0x08
52 | MSP_ELRS_BIND = 0x09
53 | MSP_ELRS_MODEL_ID = 0x0A
54 | MSP_ELRS_REQU_VTX_PKT = 0x0B
55 | MSP_ELRS_SET_TX_BACKPACK_WIFI_MODE = 0x0C
56 | MSP_ELRS_SET_VRX_BACKPACK_WIFI_MODE = 0x0D
57 | MSP_ELRS_SET_RX_WIFI_MODE = 0x0E
58 | MSP_ELRS_SET_RX_LOAN_MODE = 0x0F
59 | MSP_ELRS_GET_BACKPACK_VERSION = 0x10
60 | MSP_ELRS_BACKPACK_CRSF_TLM = 0x11
61 | MSP_ELRS_SET_SEND_UID = 0x00B5
62 | MSP_ELRS_SET_OSD = 0x00B6
63 |
64 | # CRSF encapsulated msp defines
65 | ENCAPSULATED_MSP_PAYLOAD_SIZE = 4
66 | ENCAPSULATED_MSP_FRAME_LEN = 8
67 |
68 | # ELRS backpack protocol opcodes
69 | # See: https:#docs.google.com/document/d/1u3c7OTiO4sFL2snI-hIo-uRSLfgBK4h16UrbA08Pd6U/edit#heading=h.1xw7en7jmvsj
70 |
71 | # outgoing, packets originating from the backpack or forwarded from the TX backpack to the VRx
72 | MSP_ELRS_BACKPACK_GET_CHANNEL_INDEX = 0x0300
73 | MSP_ELRS_BACKPACK_SET_CHANNEL_INDEX = 0x0301
74 | MSP_ELRS_BACKPACK_GET_FREQUENCY = 0x0302
75 | MSP_ELRS_BACKPACK_SET_FREQUENCY = 0x0303
76 | MSP_ELRS_BACKPACK_GET_RECORDING_STATE = 0x0304
77 | MSP_ELRS_BACKPACK_SET_RECORDING_STATE = 0x0305
78 | MSP_ELRS_BACKPACK_GET_VRX_MODE = 0x0306
79 | MSP_ELRS_BACKPACK_SET_VRX_MODE = 0x0307
80 | MSP_ELRS_BACKPACK_GET_RSSI = 0x0308
81 | MSP_ELRS_BACKPACK_GET_BATTERY_VOLTAGE = 0x0309
82 | MSP_ELRS_BACKPACK_GET_FIRMWARE = 0x030A
83 | MSP_ELRS_BACKPACK_SET_BUZZER = 0x030B
84 | MSP_ELRS_BACKPACK_SET_OSD_ELEMENT = 0x030C
85 | MSP_ELRS_BACKPACK_SET_HEAD_TRACKING = (
86 | 0x030D # enable/disable head-tracking forwarding packets to the TX
87 | )
88 | MSP_ELRS_BACKPACK_SET_RTC = 0x030E
89 |
90 | # incoming, packets originating from the VRx
91 | MSP_ELRS_BACKPACK_SET_MODE = 0x0380 # enable wifi/binding mode
92 | MSP_ELRS_BACKPACK_GET_VERSION = 0x0381 # get the bacpack firmware version
93 | MSP_ELRS_BACKPACK_GET_STATUS = 0x0382 # get the status of the backpack
94 | MSP_ELRS_BACKPACK_SET_PTR = 0x0383 # forwarded back to TX backpack
95 |
96 |
97 | class MSPPacket:
98 | """
99 | Class for managing msp data
100 | """
101 |
102 | def __init__(self) -> None:
103 | self._type: MSPPacketType = MSPPacketType.COMMAND
104 | self._function: Union[MSPTypes, None] = None
105 | self._payload: bytes | bytearray = bytearray()
106 | self._flags: int = 0
107 |
108 | @classmethod
109 | def packets_from_bytes_queue(cls, queue: Queue) -> Generator[Self, None, None]:
110 | """
111 | Parses packets from a provided queue
112 |
113 | :param queue: The queue to generate packets from
114 | :yield: The packet
115 | """
116 |
117 | def _gen() -> Generator[bytes, None, None]:
118 | while not queue.is_shutdown:
119 | yield queue.get()
120 |
121 | for bytes_ in _gen():
122 | yield from cls.packets_from_bytes(bytes_)
123 |
124 | @classmethod
125 | def packets_from_bytes(cls, data: bytes) -> Generator[Self, None, None]:
126 | """
127 | Parses packets from a provided queue
128 |
129 | :param queue: The queue to generate packets from
130 | :yield: The packet
131 | """
132 |
133 | yield from cls._generate_packets((i for i in data))
134 |
135 | @classmethod
136 | def _generate_packets(
137 | cls, data: Generator[int, None, None]
138 | ) -> Generator[Self, None, None]:
139 | """
140 | Generates packets from an incoming generator
141 |
142 | :param data: The data generator
143 | :yield: The generated packet
144 | """
145 | state: MSPState = MSPState.IDLE
146 | type_ = MSPPacketType.UNKNOWN
147 | flags = 0
148 | function_: MSPTypes | None = None
149 | buffer = bytearray()
150 | length = 0
151 | crc = 0
152 |
153 | for c in data:
154 |
155 | if state == MSPState.IDLE:
156 | if c == ord("$"):
157 | buffer = bytearray()
158 | buffer.append(c)
159 | state = MSPState.HEADER_START
160 |
161 | elif state == MSPState.HEADER_START:
162 | if c == ord("X"):
163 | buffer.append(c)
164 | state = MSPState.HEADER_X
165 | else:
166 | state = MSPState.IDLE
167 |
168 | elif state == MSPState.HEADER_X:
169 | state = MSPState.HEADER_V2_NATIVE
170 | crc = 0
171 |
172 | if c in (
173 | MSPPacketType.COMMAND,
174 | MSPPacketType.RESPONSE,
175 | ):
176 | buffer.append(c)
177 | type_ = MSPPacketType(c)
178 | else:
179 | type_ = MSPPacketType.UNKNOWN
180 | state = MSPState.IDLE
181 |
182 | elif state == MSPState.HEADER_V2_NATIVE:
183 | buffer.append(c)
184 | crc = cls._crc8_dvb_s2(crc, c)
185 |
186 | if len(buffer) == MSP_HEADER_LENGTH:
187 | flags = buffer[3]
188 | function_ = MSPTypes(cls._bytes_to_int(buffer[4:6]))
189 | length = cls._bytes_to_int(buffer[6:8])
190 |
191 | if length == 0:
192 | state = MSPState.CHECKSUM_V2_NATIVE
193 | else:
194 | state = MSPState.PAYLOAD_V2_NATIVE
195 |
196 | elif state == MSPState.PAYLOAD_V2_NATIVE:
197 | buffer.append(c)
198 | crc = cls._crc8_dvb_s2(crc, c)
199 |
200 | if len(buffer) - MSP_HEADER_LENGTH == length:
201 | state = MSPState.CHECKSUM_V2_NATIVE
202 |
203 | elif state == MSPState.CHECKSUM_V2_NATIVE:
204 | if c == crc:
205 | assert function_ is not None
206 | packet = cls()
207 | packet.set_type(type_)
208 | packet.set_flags(flags)
209 | packet.set_function(function_)
210 |
211 | if len(buffer) - MSP_HEADER_LENGTH > 0:
212 | packet.set_payload(buffer[8:])
213 |
214 | yield packet
215 |
216 | state = MSPState.IDLE
217 |
218 | else:
219 | state = MSPState.IDLE
220 |
221 | @property
222 | def function(self) -> Union[MSPTypes, None]:
223 | """
224 | Getter for the packet's function
225 | """
226 | return self._function
227 |
228 | @property
229 | def type_(self) -> MSPPacketType:
230 | """
231 | Getter for the packet's type
232 | """
233 | return self._type
234 |
235 | @property
236 | def payload(self) -> bytes:
237 | """
238 | Getter for the packet's type
239 | """
240 | return self._payload
241 |
242 | @staticmethod
243 | def _int_to_bytes(a: int) -> bytes:
244 | return a.to_bytes(2, "little")
245 |
246 | @staticmethod
247 | def _bytes_to_int(a: bytes | bytearray) -> int:
248 | return int.from_bytes(a, "little")
249 |
250 | def set_function(self, function: MSPTypes) -> None:
251 | """
252 | Sets the function for the packet
253 |
254 | :param function: The enum to set the function to
255 | """
256 | self._function = function
257 |
258 | def set_payload(self, payload: Sequence[int] | bytes) -> None:
259 | """
260 | Sets the payload for the packet
261 |
262 | :param payload: The payload of the packet
263 | """
264 | self._payload = bytes(payload)
265 |
266 | def set_flags(self, flags: int) -> None:
267 | """
268 | Sets the payload for the packet
269 |
270 | :param payload: The payload of the packet
271 | """
272 | self._flags = flags
273 |
274 | def set_type(self, type_: MSPPacketType) -> None:
275 | """
276 | Sets the payload for the packet
277 |
278 | :param payload: The payload of the packet
279 | """
280 | self._type = type_
281 |
282 | def iterate_payload(self) -> Generator[int, None, None]:
283 | """
284 | Yields the data in the packet
285 |
286 | :yield: Payload values
287 | """
288 | assert self._payload is not None
289 | yield from self._payload
290 |
291 | def get_payload_size(self) -> int:
292 | """
293 | Gets the size of the payload
294 |
295 | :return: _description_
296 | """
297 | return len(self._payload)
298 |
299 | def _payload_size(self) -> bytes:
300 | return self._int_to_bytes(self.get_payload_size())
301 |
302 | @staticmethod
303 | def _crc8_dvb_s2(crc: int, a: int) -> int:
304 | crc = crc ^ a
305 | for _ in range(8):
306 | if crc & 0x80:
307 | crc = (crc << 1) ^ 0xD5
308 | else:
309 | crc = crc << 1
310 | return crc & 0xFF
311 |
312 | @classmethod
313 | def _calculate_checksum(cls, body: Sequence[int]) -> int:
314 | crc = 0
315 | for x in body:
316 | crc = cls._crc8_dvb_s2(crc, x)
317 | return crc
318 |
319 | def _create_body(self) -> bytearray:
320 | assert self._function is not None
321 | assert self._payload is not None
322 |
323 | body = bytearray()
324 | body.append(self._flags)
325 | body += self._int_to_bytes(self._function)
326 | body += self._payload_size()
327 | body += self._payload
328 |
329 | return body
330 |
331 | def get_packet(self) -> bytearray:
332 | """
333 | Get the constrcuted packet
334 |
335 | :return: The constructed packet
336 | """
337 | assert self._type is not MSPPacketType.UNKNOWN
338 |
339 | msp = bytearray()
340 | msp.append(ord("$"))
341 | msp.append(ord("X"))
342 | msp.append(self._type)
343 |
344 | body = self._create_body()
345 | checksum = self._calculate_checksum(body)
346 |
347 | msp += bytes(body)
348 | msp.append(checksum)
349 |
350 | return msp
351 |
--------------------------------------------------------------------------------
/custom_plugins/vrxc_elrs/__init__.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | import RHAPI
4 | from eventmanager import Evt
5 | from RHUI import UIField, UIFieldSelectOption, UIFieldType
6 |
7 | from .connections import ConnectionTypeEnum
8 | from .elrs_backpack import ELRSBackpack
9 |
10 | logger = logging.getLogger(__name__)
11 |
12 |
13 | def initialize(rhapi: RHAPI.RHAPI):
14 |
15 | controller = ELRSBackpack("elrs", "ELRS", rhapi)
16 |
17 | rhapi.events.on(Evt.VRX_INITIALIZE, controller.register_handlers)
18 | rhapi.events.on(Evt.PILOT_ALTER, controller.pilot_alter)
19 | rhapi.events.on(
20 | Evt.STARTUP, controller.start_recieve_loop, name="start_recieve_loop"
21 | )
22 | rhapi.events.on(Evt.STARTUP, controller.start_connection, name="start_connection")
23 |
24 | #
25 | # Setup UI
26 | #
27 |
28 | elrs_bindphrase = UIField(
29 | name="comm_elrs", label="ELRS BP Bind Phrase", field_type=UIFieldType.TEXT
30 | )
31 | rhapi.fields.register_pilot_attribute(elrs_bindphrase)
32 |
33 | active = UIField("elrs_active", "Enable ELRS OSD", field_type=UIFieldType.CHECKBOX)
34 | rhapi.fields.register_pilot_attribute(active)
35 |
36 | rhapi.ui.register_panel(
37 | "elrs_settings", "ELRS Backpack General Settings", "settings", order=0
38 | )
39 |
40 | rhapi.ui.register_panel(
41 | "elrs_vrxc", "ELRS Backpack OSD Settings", "settings", order=0
42 | )
43 |
44 | #
45 | # Check Boxes
46 | #
47 |
48 | _race_start = UIField(
49 | "_race_start",
50 | "Start Race from Transmitter",
51 | desc="Allows the race director to remotely start races",
52 | field_type=UIFieldType.CHECKBOX,
53 | )
54 | rhapi.fields.register_option(_race_start, "elrs_settings")
55 |
56 | _race_stop = UIField(
57 | "_race_stop",
58 | "Stop Race from Transmitter",
59 | desc="Allows the race director to remotely stop races",
60 | field_type=UIFieldType.CHECKBOX,
61 | )
62 | rhapi.fields.register_option(_race_stop, "elrs_settings")
63 |
64 | _autosave_on_stop = UIField(
65 | "_autosave_on_stop",
66 | "Autosave on stop",
67 | desc="Automatically save the race when stopping from the transmitter",
68 | field_type=UIFieldType.CHECKBOX,
69 | value="0",
70 | )
71 | rhapi.fields.register_option(_autosave_on_stop, "elrs_settings")
72 |
73 | _socket_ip = UIField(
74 | "_socket_ip",
75 | "ELRS Netpack Address",
76 | desc="Hostanme or IP Address of the ELRS Netpack",
77 | value="elrs-netpack.local",
78 | field_type=UIFieldType.TEXT,
79 | )
80 | rhapi.fields.register_option(_socket_ip, "elrs_settings")
81 |
82 | conn_opts = [UIFieldSelectOption(value=None, label="")]
83 | for type_ in ConnectionTypeEnum:
84 | race_selection = UIFieldSelectOption(value=type_.id_, label=type_.name)
85 | conn_opts.append(race_selection)
86 |
87 | _conn_opt = UIField(
88 | "_conn_opt",
89 | "Backback Connection Type",
90 | desc="Select the type of connection to use for the backpack",
91 | field_type=UIFieldType.SELECT,
92 | options=conn_opts,
93 | )
94 | rhapi.fields.register_option(_conn_opt, "elrs_settings")
95 |
96 | _heat_name = UIField(
97 | "_heat_name",
98 | "Show Heat Name",
99 | desc="Show the heat's name on start",
100 | field_type=UIFieldType.CHECKBOX,
101 | )
102 | rhapi.fields.register_option(_heat_name, "elrs_vrxc")
103 |
104 | _round_num = UIField(
105 | "_round_num",
106 | "Show Round Number",
107 | desc="Show round number on start",
108 | field_type=UIFieldType.CHECKBOX,
109 | )
110 | rhapi.fields.register_option(_round_num, "elrs_vrxc")
111 |
112 | _class_name = UIField(
113 | "_class_name",
114 | "Show Class Name",
115 | desc="Show the class's name on start",
116 | field_type=UIFieldType.CHECKBOX,
117 | )
118 | rhapi.fields.register_option(_class_name, "elrs_vrxc")
119 |
120 | _event_name = UIField(
121 | "_event_name",
122 | "Show Event Name",
123 | desc="Show the event's name on start",
124 | field_type=UIFieldType.CHECKBOX,
125 | )
126 | rhapi.fields.register_option(_event_name, "elrs_vrxc")
127 |
128 | _position_mode = UIField(
129 | "_position_mode",
130 | "Show Current Position and Lap",
131 | desc="off - only shows current lap",
132 | field_type=UIFieldType.CHECKBOX,
133 | )
134 | rhapi.fields.register_option(_position_mode, "elrs_vrxc")
135 |
136 | _gap_mode = UIField(
137 | "_gap_mode",
138 | "Show Gap Time",
139 | desc="off - shows lap time",
140 | field_type=UIFieldType.CHECKBOX,
141 | )
142 | rhapi.fields.register_option(_gap_mode, "elrs_vrxc")
143 |
144 | _results_mode = UIField(
145 | "_results_mode",
146 | "Show Post-Race Results",
147 | desc="Show pilot's results upon race completion",
148 | field_type=UIFieldType.CHECKBOX,
149 | )
150 | rhapi.fields.register_option(_results_mode, "elrs_vrxc")
151 |
152 | #
153 | # Text Fields
154 | #
155 |
156 | _racestage_message = UIField(
157 | "_racestage_message",
158 | "Race Stage Message",
159 | desc="lowercase letters are symbols",
160 | field_type=UIFieldType.TEXT,
161 | value="w ARM NOW x",
162 | )
163 | rhapi.fields.register_option(_racestage_message, "elrs_vrxc")
164 |
165 | _racestart_message = UIField(
166 | "_racestart_message",
167 | "Race Start Message",
168 | desc="lowercase letters are symbols",
169 | field_type=UIFieldType.TEXT,
170 | value="w GO! x",
171 | )
172 | rhapi.fields.register_option(_racestart_message, "elrs_vrxc")
173 |
174 | _pilotdone_message = UIField(
175 | "_pilotdone_message",
176 | "Pilot Done Message",
177 | desc="lowercase letters are symbols",
178 | field_type=UIFieldType.TEXT,
179 | value="w FINISHED! x",
180 | )
181 | rhapi.fields.register_option(_pilotdone_message, "elrs_vrxc")
182 |
183 | _racefinish_message = UIField(
184 | "_racefinish_message",
185 | "Race Finish Message",
186 | desc="lowercase letters are symbols",
187 | field_type=UIFieldType.TEXT,
188 | value="w FINISH LAP! x",
189 | )
190 | rhapi.fields.register_option(_racefinish_message, "elrs_vrxc")
191 |
192 | _racestop_message = UIField(
193 | "_racestop_message",
194 | "Race Stop Message",
195 | desc="lowercase letters are symbols",
196 | field_type=UIFieldType.TEXT,
197 | value="w LAND NOW! x",
198 | )
199 | rhapi.fields.register_option(_racestop_message, "elrs_vrxc")
200 |
201 | _leader_message = UIField(
202 | "_leader_message",
203 | "Race Leader Message",
204 | desc="lowercase letters are symbols",
205 | field_type=UIFieldType.TEXT,
206 | value="RACE LEADER",
207 | )
208 | rhapi.fields.register_option(_leader_message, "elrs_vrxc")
209 |
210 | #
211 | # Basic Integers
212 | #
213 |
214 | _racestart_uptime = UIField(
215 | "_racestart_uptime",
216 | "Start Message Uptime",
217 | desc="decaseconds",
218 | field_type=UIFieldType.BASIC_INT,
219 | value=5,
220 | )
221 | rhapi.fields.register_option(_racestart_uptime, "elrs_vrxc")
222 |
223 | _finish_uptime = UIField(
224 | "_finish_uptime",
225 | "Finish Message Uptime",
226 | desc="decaseconds",
227 | field_type=UIFieldType.BASIC_INT,
228 | value=20,
229 | )
230 | rhapi.fields.register_option(_finish_uptime, "elrs_vrxc")
231 |
232 | _results_uptime = UIField(
233 | "_results_uptime",
234 | "Lap Result Uptime",
235 | desc="decaseconds",
236 | field_type=UIFieldType.BASIC_INT,
237 | value=40,
238 | )
239 | rhapi.fields.register_option(_results_uptime, "elrs_vrxc")
240 |
241 | _announcement_uptime = UIField(
242 | "_announcement_uptime",
243 | "Announcement Uptime",
244 | desc="decaseconds",
245 | field_type=UIFieldType.BASIC_INT,
246 | value=50,
247 | )
248 | rhapi.fields.register_option(_announcement_uptime, "elrs_vrxc")
249 |
250 | _heatname_row = UIField(
251 | "_heatname_row",
252 | "Heat Name Row",
253 | desc="Use rows between 0-17",
254 | field_type=UIFieldType.BASIC_INT,
255 | value=2,
256 | )
257 | rhapi.fields.register_option(_heatname_row, "elrs_vrxc")
258 |
259 | _classname_row = UIField(
260 | "_classname_row",
261 | "Class Name Row",
262 | desc="Use rows between 0-17",
263 | field_type=UIFieldType.BASIC_INT,
264 | value=1,
265 | )
266 | rhapi.fields.register_option(_classname_row, "elrs_vrxc")
267 |
268 | _eventname_row = UIField(
269 | "_eventname_row",
270 | "Event Name Row",
271 | desc="Use rows between 0-17",
272 | field_type=UIFieldType.BASIC_INT,
273 | value=0,
274 | )
275 | rhapi.fields.register_option(_eventname_row, "elrs_vrxc")
276 |
277 | _announcement_row = UIField(
278 | "_announcement_row",
279 | "Announcement Row",
280 | desc="Use rows between 0-17",
281 | field_type=UIFieldType.BASIC_INT,
282 | value=3,
283 | )
284 | rhapi.fields.register_option(_announcement_row, "elrs_vrxc")
285 |
286 | _status_row = UIField(
287 | "_status_row",
288 | "Race Status Row",
289 | desc="Use rows between 0-17",
290 | field_type=UIFieldType.BASIC_INT,
291 | value=5,
292 | )
293 | rhapi.fields.register_option(_status_row, "elrs_vrxc")
294 |
295 | _currentlap_row = UIField(
296 | "_currentlap_row",
297 | "Current Lap/Position Row",
298 | desc="Use rows between 0-17",
299 | field_type=UIFieldType.BASIC_INT,
300 | value=0,
301 | )
302 | rhapi.fields.register_option(_currentlap_row, "elrs_vrxc")
303 |
304 | _lapresults_row = UIField(
305 | "_lapresults_row",
306 | "Lap/Gap Results Row",
307 | desc="Use rows between 0-17",
308 | field_type=UIFieldType.BASIC_INT,
309 | value=15,
310 | )
311 | rhapi.fields.register_option(_lapresults_row, "elrs_vrxc")
312 |
313 | _results_row = UIField(
314 | "_results_row",
315 | "Results Rows",
316 | desc="Use rows between 0-16. Uses two rows.",
317 | field_type=UIFieldType.BASIC_INT,
318 | value=13,
319 | )
320 | rhapi.fields.register_option(_results_row, "elrs_vrxc")
321 |
322 | #
323 | # Quick Buttons
324 | #
325 |
326 | rhapi.ui.register_quickbutton(
327 | "elrs_settings",
328 | "bp_connect",
329 | "Backpack Connect",
330 | controller.start_connection,
331 | )
332 | rhapi.ui.register_quickbutton(
333 | "elrs_settings",
334 | "bp_disconnect",
335 | "Backpack Disconnect",
336 | controller.disconnect,
337 | )
338 | rhapi.ui.register_quickbutton(
339 | "elrs_settings", "enable_bind", "Start Backpack Bind", controller.activate_bind
340 | )
341 |
342 | rhapi.ui.register_quickbutton(
343 | "elrs_settings",
344 | "test_osd",
345 | "Test Bound Backpack's OSD",
346 | controller.test_bind_osd,
347 | )
348 | rhapi.ui.register_quickbutton(
349 | "elrs_settings", "enable_wifi", "Start Backpack WiFi", controller.activate_wifi
350 | )
351 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # RotorHazard VRx Control for the ExpressLRS Backpack
2 |
3 | This is a plugin being developed for the RotorHazard timing system with the following features:
4 | - [X] Send OSD messages to pilots using compatible equipment (such as the [HDZero goggles](https://www.youtube.com/watch?v=VXwaUoA16jc))
5 | - [X] Allows for the race manager to [start the race from their transmitter](https://github.com/i-am-grub/VRxC_ELRS?tab=readme-ov-file#control-the-race-from-the-race-directors-transmitter)
6 | - [ ] Pilot's `ready` status from their transmitter
7 |
8 | See [here](https://github.com/i-am-grub/VRxC_ELRS/issues/5) for the plugin's current roadmap
9 |
10 | ## How does it work?
11 |
12 | This plugin is built to control to an external device or chip running the ExpressLRS Timer backpack over a serial port. This allows the
13 | timing system to communicate with other devices with an ELRS backpack built into them giving the timer the ability to receive state messages
14 | from a pilot's transmitter, or send messages to display OSD information directly to a pilot's goggles.
15 |
16 | ## I'm a pilot. What do I need to setup?
17 |
18 | Currently, the only device supported for receiving OSD race messages from the ELRS backpack is the HDZero goggles. They come with
19 | an internal ESP32 chip installed for the ExpressLRS backpack. Update the goggles's video receiver backpack to the latest version by either using the
20 | [ExpressLRS Configurator](https://github.com/ExpressLRS/ExpressLRS-Configurator/releases) or the
21 | [ExpressLRS Web Flasher](https://expresslrs.github.io/web-flasher/). Follow [this guide](https://www.expresslrs.org/hardware/backpack/hdzero-goggles/) for
22 | the first time installation process. If assistance is needed with the installation or upgrading the goggle firmware,
23 | ask for help in the `help-and-support` channels of the [ExpressLRS Discord](https://discord.gg/expresslrs).
24 |
25 | > [!IMPORTANT]
26 | > REMEMBER YOUR BACKPACK BIND PHRASE: The timer's backpack will use it to send OSD messages from the timer to your HDZero goggles.
27 | > You will likely need to provide the bind phrase to the race director if you want OSD information at your race.
28 |
29 | > [!NOTE]
30 | > The backpack bind phrase can either be the same or different than the bind phrase used for the ExpressLRS radio protocol.
31 | > Setting the same bind phrase will not cause the backpack to interfere with the radio protocol.
32 |
33 | ## Setup Directions for Race Directors
34 |
35 | ### Installing the Timer Backpack
36 |
37 | The list below is of some of the known compatible devices for the RotorHazard Timer Backpack. It is recommended to use a chip that is capable of connecting an external WIFI antenna to
38 | help improve the range of the timer's backpack.
39 |
40 | | ELRS Device | Compatible Hardware |
41 | | --------------------- | --------------------------------------------------------------------------------------------------------------------- |
42 | | EP82 Module (DIY) | [ESP8266 NodeMCU](https://a.co/d/9vgX3Tx) |
43 | | EP32 Module (DIY) | [ESP32-DevKitC](https://a.co/d/62OGBgG) |
44 | | EP32C3 Module (DIY) | [ESP32-C3-DevKitM-1U](https://www.digikey.com/en/products/detail/espressif-systems/ESP32-C3-DEVKITM-1U/15198974) |
45 | | EP32S3 Module (DIY) | [ESP32-S3-DevKitC-1U](https://www.digikey.com/en/products/detail/espressif-systems/ESP32-S3-DEVKITC-1U-N8R8/16162636) |
46 | | NuclearHazard | [NuclearHazard Board](https://www.etsy.com/listing/1428199972/nuclearhazard-core-kit-case-and-rx-sold) v7 or newer |
47 | | [ELRS-Netpack](https://github.com/i-am-grub/elrs-netpack) (DIY) | [Waveshare ESP32-S3 Ethernet](https://www.waveshare.com/esp32-s3-eth.htm) |
48 |
49 | > [!TIP]
50 | > While other specific development boards with similar chipsets may be supported by the targets in the table, it is not guaranteed that they work.
51 | > For example, the Seeed Studio XIAO ESP32C3/S3 board do not work with the targets listed above, but when using the
52 | > [ExpressLRS Toolchain](https://www.expresslrs.org/software/toolchain-install/) for building the backpack firmware,
53 | > the platformio settings can be changed to build compatible firmware for XIAO boards.
54 |
55 | > [!NOTE]
56 | > While a normal ExpressLRS reciever can be flashed with backpack firmware and be used for the timer backpack, this is not recommended.
57 | > The primary reason behind this is that the ELRS backpack is based on ESPNow which uses the WIFI hardware of the ESP32/ESP82.
58 | > Recievers typically have a small ceramic antenna installed seperately for connecting to the web UI over WIFI; this antenna is
59 | > different than the the one(s) reserved for the radio protocol. The ceramic antennta would likely be less performant over an ESP32
60 | > devkit with an external WIFI antenna connected.
61 |
62 | #### Flashing ESP32/ESP82 Devkits
63 |
64 | To build and flash the firmware, use the [ExpressLRS Configurator](https://github.com/ExpressLRS/ExpressLRS-Configurator/releases) or the [ExpressLRS Web Flasher](https://expresslrs.github.io/web-flasher/)
65 | 1. Connect the device to the computer over USB.
66 |
67 | > If Windows doesn't recognize the device connected over USB, a driver install or update may be required.
68 | > Espressif designed boards typically either use the [CP210x](https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers) or
69 | > [FTDI](https://ftdichip.com/drivers/vcp-drivers/) USB to serial converter chips
70 |
71 | 2. Select the backpack firmware mode
72 | - If using the configurator, select `Backpack` on the left side menu.
73 | - If using the Web Flasher, select `Race Timer` under the Backpack Firmware section
74 | 3. Select the 1.5.0 (or a newer) release
75 | 4. Select the RotorHazard device category
76 | 5. Select the target for the device
77 | 6. Select the UART flashing method
78 | 7. Enter the backpack bind phrase (for race control from the director's transmitter)
79 | 8. Select the COM port for the device
80 | 9. Build and flash the firmware
81 |
82 | #### Flashing NuclearHazard Hardware
83 |
84 | To build the firmware, use the [ExpressLRS Configurator](https://github.com/ExpressLRS/ExpressLRS-Configurator/release) or the [ExpressLRS Web Flasher](https://expresslrs.github.io/web-flasher/)
85 |
86 | 1. Select the backpack firmware section
87 | - If using the configurator, select `Backpack` on the left side menu.
88 | - If using the Web Flasher, select `Race Timer` under the Backpack Firmware section
89 | 2. Select the 1.5.0 release (or a newer version)
90 | 3. Select the RotorHazard device category
91 | 4. Select NuclearHazard as the device
92 | 5. Select the method
93 | - If using the configurator, select `WIFI`.
94 | - If using the Web Flasher, select `Local Download`
95 | 6. Enter the backpack bind phrase (for race control from the director's transmitter)
96 | 7. Build the firmware
97 | 8. Follow [this guide](https://nuclearquads.com/instructions/vrxc) to flash the on board ESP32. Instead of downloading the backpack bin files, use the files built with the configurator.
98 |
99 | #### Flashing ELRS Netpack
100 |
101 | 1. Download the [netpack-installer](https://github.com/i-am-grub/netpack-installer) plugin from the community plugins
102 | list
103 | 2. Connect the required ESP32 devkit to your timer
104 | 3. In the `ELRS Netpack Firmware` panel (found on the `Settings` page), select the serial port of the connected device
105 | and press the `Flash Netpack Firmware` button.
106 |
107 | ### Installing the RotorHazard Plugin
108 |
109 | 1. Verify RotorHazard v4.1.0+ is installed on the timer
110 | 2. Follow the instructions in the [latest release](https://github.com/i-am-grub/VRxC_ELRS/releases) of the plugin to complete the installation process.
111 |
112 | ### Control the Race from the Race Director's Transmitter
113 |
114 | There is a feature to control the race from the race director's transmitter by tracking the position of the `DVR Rec` switch setup within the transmitter's backpack. It currently works
115 | by binding the race timer's backpack to the race director's backpack bind phrase similar to the process used with the transmitter and VRx backpacks.
116 |
117 | Currently only starting and stopping the race are supported. Setting up this feature will not prevent other users from receiving OSD messages.
118 |
119 | > [!IMPORTANT]
120 | > This feature requires the Race Director to have the ELRS Backpack setup on their transmitter. Please ensure this is setup before completing the following instructions.
121 |
122 | 1. Setup the `DVR Rec` switch in the ELRS backpack
123 | 1. Open the ExpressLRS Lua script (v3 is recommended) on the transmitter
124 | 2. Open up the Backpack settings
125 | 3. Set the AUX channel for `DVR Rec`
126 |
127 | > [!NOTE]
128 | > This will not stop the ability to start recording DVR through this switch. It is just a state that the race timer's backpack listens for.
129 |
130 | 2. Bind the Race Timer backpack to the Transmitter. This step can be skipped if flashing the timer's backpack with firmware that contains the race director's backpack bind phrase.
131 | 1. Start the RotorHazard server with the ESP32 connected.
132 | 2. Navigate to the `ELRS Backpack General Settings` panel.
133 | 3. Click the `Start Backpack Bind` button.
134 | 4. Within the ExpressLRS Lua script on the transmitter, click `Bind`
135 |
136 | To test to see if the backpack was bound successfully, navigate to the `Race` page within RotorHazard, and use the `DVR Rec` switch to start the race.
137 | [Start Race from Transmitter](https://github.com/i-am-grub/VRxC_ELRS?tab=readme-ov-file#start-race-from-transmitter--checkbox)
138 | or [Stop Race from Transmitter](https://github.com/i-am-grub/VRxC_ELRS?tab=readme-ov-file#stop-race-from-transmitter--checkbox)
139 | will need to be enabled under `ELRS Backpack General Settings`
140 |
141 | > [!TIP]
142 | > Anytime the backpack needs to be bound to a new transmitter, it will be easiest to reflash the ESP32 with the firmware in the latest release, and then rebind.
143 |
144 | # Extra Hardware Notes
145 |
146 | ## 3D Printed Case
147 |
148 | Some users have like to use the following 3D printable case available on [Printables](https://www.printables.com/model/762529-esp32-wroom-32u-casing) for
149 | an externally connected `ESP32-DevKitC-1U` board.
150 |
151 | 
152 |
153 | ## WIFI Signal Booster
154 |
155 | The quality and reliability of the ExpressLRS backpack is significantly dependent on the HDZero goggle's ability to receive the backpack messages from the timer. Since the
156 | antenna for the goggle's backpack is inside and there may be additional RF interference on the 2.4 GHz with pilot's radio protocols, a WIFI signal booster may help increase
157 | the reliability of the backpack.
158 |
159 | My personal setup:
160 | - [ESP32-DevKitC](https://a.co/d/62OGBgG)
161 | - [U.FL to RP-SMA Cables](https://a.co/d/7n99T9o)
162 | - [800mW Pen Bi-Directional Booster Module](https://www.data-alliance.net/800mw-bi-directional-booster-module-w-rp-sma-female-connectors/)
163 | - [USB Power Cable for powering the booster from the RaspberryPi](https://a.co/d/9iAPV57)
164 | - A high gain 2.4 GHz WIFI antenna with RP-SMA connection
165 |
166 | > [!NOTE]
167 | > An ESP32 typically has a maximum power setting less than 100 milliwatts without a signal booster
168 |
169 | ## USB Extension Cable
170 |
171 | [Some groups](https://youtu.be/FZvmfyvRiPE?si=LXu0zXUpDj9NsnUN&t=201) have had good luck with moving the ESP32 closer to the pilots by using a long USB cable or a USB extension cable.
172 |
173 | > [!NOTE]
174 | > The RotorHazard development team is looking into setting up the ability to peform a serial-over-https connection. This will allow groups to connect the timer backpack directly to
175 | > the race director's computer instead of the timer.
176 |
177 | # Settings
178 |
179 | ## Pilot Settings
180 |
181 | 
182 |
183 | ### ELRS BP Bindphrase : TEXT
184 |
185 | The pilot's individual bind phrase for their backpack. If a bind phrase is not set, the pilot's callsign will be used as a fallback bind phrase instead.
186 |
187 | ### Enable ELRS OSD : CHECKBOX
188 |
189 | Turns the pilot's ELRS OSD on/off
190 |
191 | ## ELRS Backpack General Settings
192 |
193 | 
194 |
195 | ### Start Race from Transmitter : CHECKBOX
196 |
197 | Allows the race director to start the race from their transmitter. Please navigate [here](https://github.com/i-am-grub/VRxC_ELRS#control-the-race-from-the-race-directors-transmitter) for binding the backpack.
198 |
199 | ### Stop Race from Transmitter : CHECKBOX
200 |
201 | Allows the race director to stop the race from their transmitter. Please navigate [here](https://github.com/i-am-grub/VRxC_ELRS#control-the-race-from-the-race-directors-transmitter) for binding the backpack.
202 |
203 | ### Autosave on stop : CHECKBOX
204 |
205 | Automatically save the race when stopping from the transmitter
206 |
207 | ### Backpack Rescan : BUTTON
208 |
209 | Triggers the timer to scan the serial devices for a backpack device. Only works if the timer is not already connected to a backpack device
210 |
211 | ### Start Backpack Bind : BUTTON
212 |
213 | Puts the timer's backpack into a binding mode for pairing with the race director's transmitter.
214 |
215 | > [!TIP]
216 | > After successfully completing this process, the timer's backpack will inherit the race director's bind phrase from the transmitter.
217 |
218 | ### Test Bound Backpack's OSD : BUTTON
219 |
220 | Will display OSD messages on HDZero goggles with a matching bind phrase. Used for testing if the timer's backpack successfully inherited the transmitter's bind phrase.
221 |
222 | ### Start Backpack WIFI : BUTTON
223 |
224 | Starts the backpack's WIFI mode. Used for over-the-air firmware updates.
225 |
226 | > [!TIP]
227 | > To connect to the backpack's web user interface, verify the backpack is setup to connect to the same network as the device used to access the web user interface,
228 | > or connect the device to the wireless network the backpack created. Open `http://elrs_timer.local` in the device's browser to connect to the web user interface.
229 |
230 | ## ELRS Backpack OSD Settings
231 |
232 | 
233 |
234 | > [!NOTE]
235 | > It is a goal of this project to eventually move all the OSD settings in this section to be pilot configurable through the ExpressLRS VRx backpack's web user interface.
236 | > The current implementation is noted to be a work around until enough progress has been completed on the VRx backpack for individual pilot configuration.
237 |
238 | ### Show Heat Name : CHECKBOX
239 |
240 | Shows the race's heat name to pilots when active
241 |
242 | ### Show Round Number : CHECKBOX
243 |
244 | Shows the race's round number to pilots when active. Also requires `Show Heat Name` to be active.
245 |
246 | ### Show Class Name : CHECKBOX
247 |
248 | Shows the race's class name to pilots when active
249 |
250 | ### Show Event Name : CHECKBOX
251 |
252 | Shows the race's event name to pilots when active
253 |
254 | ### Show Current Position and Lap : CHECKBOX
255 |
256 | - TOGGLED ON: Shows current position and current lap when multiple pilots are in a race
257 | - TOGGLED OFF: Only shows current lap
258 |
259 | ### Show Gap Time : CHECKBOX
260 |
261 | - TOGGLED ON: Shows the gap time to next pilot if using a compatible win condition for the race
262 | - TOGGLED OFF: Shows lap result time
263 |
264 | ### Show Post-Race Results : CHECKBOX
265 |
266 | The pilot will be shown results when they finish the race. It is recommended to have pilots turn off `Post Flight Results` in Betaflight so the results won't be overridden when the pilot lands.
267 |
268 | ### Race Stage Message : TEXT
269 |
270 | The message shown to pilots when the timer is staging the race
271 |
272 | ### Race Start Message : TEXT
273 |
274 | The message shown to pilots when the race first starts
275 |
276 | ### Pilot Done Message : TEXT
277 |
278 | The message shown to pilots when the pilot finishes
279 |
280 | ### Race Finish Message : TEXT
281 |
282 | The message shown to pilots when the time runs out
283 |
284 | ### Race Stop Message : TEXT
285 |
286 | The message shown to pilots when the race is stopped
287 |
288 | ### Race Leader Message : TEXT
289 |
290 | The message shown to pilots when `Show Gap Time` is enabled and the pilot is leading the race
291 |
292 | ### Start Message Uptime : INT
293 |
294 | The length of time `Race Start Message` is shown to pilots
295 |
296 | ### Finish Message Uptime : INT
297 |
298 | The length of time `Pilot Done Message` and `Race Finish Message` is shown to pilots
299 |
300 | ### Lap Result Uptime : INT
301 |
302 | Length of time the pilot's lap or gap time is shown after completing a lap.
303 |
304 | ### Announcement Uptime : INT
305 |
306 | Length of time to show announcements to pilots. (e.g. When a race is scheduled)
307 |
308 | ### Heat Name Row : INT
309 |
310 | Row to show the heat name on when the race is staging.
311 |
312 | ### Class Name Row : INT
313 |
314 | Row to show the class name on when the race is staging.
315 |
316 | ### Event Name Row : INT
317 |
318 | Row to show the event name on when the race is staging.
319 |
320 | ### Announcement Row : INT
321 |
322 | Row to show announcements such as when a race is scheduled. This row is also used by `Show Race Name on Stage`
323 |
324 | ### Race Status Row : INT
325 |
326 | Row to show race status messages.
327 |
328 | ### Current Lap/Position Row : INT
329 |
330 | Row to show current lap and position
331 |
332 | ### Lap/Gap Results Row : INT
333 |
334 | Row to show lap or gap time
335 |
336 | ### Results Rows : INT
337 |
338 | The row to start showing a pilot's post race statistics on. It will also use the follow row in conjunction with the entered one.
339 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/custom_plugins/vrxc_elrs/elrs_backpack.py:
--------------------------------------------------------------------------------
1 | import hashlib
2 | import logging
3 |
4 | import gevent
5 | import gevent.lock
6 | import gevent.socket as socket
7 | import util.RH_GPIO as RH_GPIO
8 | from gevent.queue import Queue
9 | from RHRace import RaceStatus, WinCondition
10 | from VRxControl import VRxController
11 |
12 | from .connections import BackpackConnection, ConnectionTypeEnum
13 | from .msp import MSPPacket, MSPPacketType, MSPTypes
14 |
15 | logger = logging.getLogger(__name__)
16 |
17 |
18 | class CancelError(BaseException): ...
19 |
20 |
21 | class ELRSBackpack(VRxController):
22 | _connection: BackpackConnection | None = None
23 |
24 | def __init__(self, name, label, rhapi):
25 | super().__init__(name, label)
26 | self._rhapi = rhapi
27 | self._send_queue = Queue()
28 | self._recieve_queue = Queue(maxsize=100)
29 | self._queue_lock = gevent.lock.RLock()
30 |
31 | @property
32 | def _backpack_connected(self) -> bool:
33 | if self._connection is None:
34 | return False
35 |
36 | return self._connection.connected
37 |
38 | def register_handlers(self, args) -> None:
39 | """
40 | Registers handlers in the RotorHazard system
41 | """
42 | args["register_fn"](self)
43 |
44 | def start_race(self):
45 | """
46 | Start the race
47 | """
48 | if self._rhapi.db.option("_race_start") == "1":
49 | start_race_args = {"start_time_s": 10}
50 | if self._rhapi.race.status == RaceStatus.READY:
51 | self._rhapi.race.stage(start_race_args)
52 |
53 | def stop_race(self):
54 | """
55 | Stop the race
56 | """
57 | if self._rhapi.db.option("_race_stop") == "1":
58 | status = self._rhapi.race.status
59 | if status in (RaceStatus.STAGING, RaceStatus.RACING):
60 | if self._rhapi.db.option("_autosave_on_stop") == "1":
61 | self._rhapi.race.save()
62 | else:
63 | self._rhapi.race.stop()
64 |
65 | #
66 | # Connection handling
67 | #
68 |
69 | def start_recieve_loop(self, *_):
70 | """
71 | Start the msp packet processing loop
72 | """
73 | gevent.spawn(self.recieve_loop)
74 | logger.info("Backpack recieve greenlet started.")
75 |
76 | def start_connection(self, *_) -> None:
77 | """
78 | Starts the connection loop
79 | """
80 | if self._backpack_connected:
81 | message = "Backpack already connected"
82 | self._rhapi.ui.message_notify(self._rhapi.language.__(message))
83 | return
84 |
85 | id_ = self._rhapi.db.option("_conn_opt", None, as_int=True)
86 | for con in ConnectionTypeEnum:
87 | if id_ == con.id_:
88 | break
89 | else:
90 | message = "Connection type not provided"
91 | self._rhapi.ui.message_notify(self._rhapi.language.__(message))
92 | return
93 |
94 | if con == ConnectionTypeEnum.USB:
95 | self._establish_connection(con.type_)
96 |
97 | elif con == ConnectionTypeEnum.ONBOARD:
98 | if RH_GPIO.is_real_hw_GPIO():
99 | logger.info("Turning on GPIO pins for NuclearHazard boards")
100 | RH_GPIO.setmode(RH_GPIO.BCM)
101 | RH_GPIO.setup(16, RH_GPIO.OUT, initial=RH_GPIO.HIGH)
102 | gevent.sleep(0.5)
103 | RH_GPIO.setup(11, RH_GPIO.OUT, initial=RH_GPIO.HIGH)
104 | gevent.sleep(0.5)
105 | RH_GPIO.output(11, RH_GPIO.LOW)
106 | gevent.sleep()
107 | RH_GPIO.output(11, RH_GPIO.HIGH)
108 |
109 | self._establish_connection(con.type_)
110 |
111 | else:
112 | message = "Instance not running on Raspberry Pi"
113 | self._rhapi.ui.message_notify(self._rhapi.language.__(message))
114 |
115 | elif con == ConnectionTypeEnum.SOCKET:
116 | addr = self._rhapi.db.option("_socket_ip", None)
117 | if addr is not None:
118 | try:
119 | ip_addr = socket.gethostbyname(addr)
120 | except socket.gaierror:
121 | message = "Failed to connect to device's socket"
122 | self._rhapi.ui.message_notify(self._rhapi.language.__(message))
123 | else:
124 | self._establish_connection(con.type_, ip_addr=ip_addr)
125 | else:
126 | message = "IP Address for socket not provided"
127 | self._rhapi.ui.message_notify(self._rhapi.language.__(message))
128 |
129 | def _establish_connection(
130 | self, connection_type: type[BackpackConnection], **kwargs
131 | ):
132 | """
133 | Setup the backpack connection
134 |
135 | :param connection_type: The type of connection to use
136 | """
137 | # Clear data in send queue
138 | while not self._send_queue.empty():
139 | self._send_queue.get()
140 |
141 | self._connection = connection_type(self._send_queue, self._recieve_queue)
142 | if not self._connection.connect(**kwargs):
143 | message = "Attempt to establish backpack connection failed"
144 | self._rhapi.ui.message_notify(self._rhapi.language.__(message))
145 | return
146 |
147 | message = "Backpack sucessfully connected"
148 | self._rhapi.ui.message_notify(self._rhapi.language.__(message))
149 |
150 | self.version_request()
151 |
152 | def recieve_loop(self) -> None:
153 | """
154 | Handles recieving data from the backpack
155 | """
156 | try:
157 | while True:
158 | packet: MSPPacket = self._recieve_queue.get()
159 |
160 | function_ = packet.function
161 |
162 | if packet.type_ == MSPPacketType.RESPONSE:
163 | if function_ == MSPTypes.MSP_ELRS_GET_BACKPACK_VERSION:
164 | version = bytes(i for i in packet.payload if i != 0).decode(
165 | "utf-8"
166 | )
167 | message = f"Backpack device firmware version: {version}"
168 | logger.info(message)
169 | self._rhapi.ui.message_notify(self._rhapi.language.__(message))
170 |
171 | if packet.type_ == MSPPacketType.COMMAND:
172 | if function_ == MSPTypes.MSP_ELRS_BACKPACK_SET_RECORDING_STATE:
173 | itr = packet.iterate_payload()
174 | if (val := next(itr)) == 0x00:
175 | self.stop_race()
176 | elif val == 0x01:
177 | self.start_race()
178 |
179 | except KeyboardInterrupt:
180 | logger.error("Stopping blackpack connector greenlet")
181 |
182 | def disconnect(self, *_) -> None:
183 | """
184 | Disconnect the connection loop
185 | """
186 | if not self._backpack_connected:
187 | message = "Backpack not connected"
188 | self._rhapi.ui.message_notify(self._rhapi.language.__(message))
189 | return
190 |
191 | assert self._connection is not None
192 | self._connection.disconnect()
193 |
194 | message = "Backpack disconnected"
195 | self._rhapi.ui.message_notify(self._rhapi.language.__(message))
196 |
197 | #
198 | # Packet creation
199 | #
200 |
201 | def hash_phrase(self, bindphrase: str) -> bytes:
202 | """
203 | Hashes a string into a UID
204 |
205 | :param bindphrase: The string to hash
206 | :return: The hashed phrase
207 | """
208 |
209 | hash_ = bytearray(
210 | x
211 | for x in hashlib.md5(
212 | (f'-DMY_BINDING_PHRASE="{bindphrase}"').encode()
213 | ).digest()[0:6]
214 | )
215 | if (hash_[0] % 2) == 1:
216 | hash_[0] -= 0x01
217 |
218 | return hash_
219 |
220 | def get_pilot_uid(self, pilot_id: int) -> bytes:
221 | """
222 | Get the uid for a pilot. If a bindphrase is not
223 | saved as an attribute, the pilot callsign is used
224 | to generate the uid.
225 |
226 | :param pilot_id: The pilot id
227 | :return: The pilot uid
228 | """
229 | assert pilot_id > 0, "Can not generate backpack uid for invalid pilot"
230 | bindphrase = self._rhapi.db.pilot_attribute_value(pilot_id, "comm_elrs")
231 | if bindphrase:
232 | uid = self.hash_phrase(bindphrase)
233 | else:
234 | pilot = self._rhapi.db.pilot_by_id(pilot_id)
235 | assert pilot is not None, "Pilot not in database"
236 | uid = self.hash_phrase(pilot.callsign)
237 |
238 | return uid
239 |
240 | def center_osd(self, len_: int) -> int:
241 | """
242 | Provides the column value needed to
243 | center a string of the provided length
244 | on the HDZero Goggles screen
245 |
246 | :param len_: The length of the string
247 | :return:
248 | """
249 | offset = len_ // 2
250 | col = 50 // 2 - offset
251 | return max(col, 0)
252 |
253 | def send_msp(self, msp: MSPPacket) -> None:
254 | """
255 | Sends a MSP packet to the backpack connection
256 | if it is active
257 |
258 | :param msp: _description_
259 | """
260 | if self._backpack_connected:
261 | self._send_queue.put(msp)
262 |
263 | def set_send_uid(self, address: bytes) -> None:
264 | """
265 | Sends the packet to set the address for the
266 | recipient of future packets
267 |
268 | :param address: Address to set
269 | """
270 | packet = MSPPacket()
271 | packet.set_function(MSPTypes.MSP_ELRS_SET_SEND_UID)
272 | payload = bytearray()
273 | payload.append(0x01)
274 | payload += address
275 | packet.set_payload(payload)
276 | self.send_msp(packet)
277 |
278 | def reset_send_uid(self) -> None:
279 | """
280 | Sends the packet to reset the packet recipient
281 | to the system default
282 | """
283 | packet = MSPPacket()
284 | packet.set_function(MSPTypes.MSP_ELRS_SET_SEND_UID)
285 | payload = bytearray()
286 | payload.append(0x00)
287 | packet.set_payload(payload)
288 | self.send_msp(packet)
289 |
290 | def send_clear_osd(self) -> None:
291 | """
292 | Sends the packet to clear the goggle's osd
293 | """
294 | packet = MSPPacket()
295 | packet.set_function(MSPTypes.MSP_ELRS_SET_OSD)
296 | payload = bytearray()
297 | payload.append(0x02)
298 | packet.set_payload(payload)
299 | self.send_msp(packet)
300 |
301 | def send_osd_text(self, row: int, col: int, text: str) -> None:
302 | """
303 | Sends a packet that provides text data to the
304 | recipient. This does not display the text to the
305 | recipient until `send_display_osd` is called
306 |
307 | :param row: The row to display the text on
308 | :param col: The column to place the start of the
309 | :param message: _description_
310 | """
311 | payload = bytearray((0x03, row, col, 0))
312 | for index, char in enumerate(text):
313 | if index >= 50:
314 | break
315 |
316 | payload.append(ord(char))
317 |
318 | packet = MSPPacket()
319 | packet.set_function(MSPTypes.MSP_ELRS_SET_OSD)
320 | packet.set_payload(payload)
321 | self.send_msp(packet)
322 |
323 | def send_display_osd(self) -> None:
324 | """
325 | Sends a packet that informs the recipient
326 | to display any provided text
327 | """
328 | packet = MSPPacket()
329 | packet.set_function(MSPTypes.MSP_ELRS_SET_OSD)
330 | payload = bytearray((0x04,))
331 | packet.set_payload(payload)
332 | self.send_msp(packet)
333 |
334 | def send_clear_osd_row(self, row: int) -> None:
335 | """
336 | Sends a packet that clears the text data
337 | in a specific row. This does not remove
338 | the text until `send_display_osd` is called.
339 |
340 | :param row: The row to remove text from
341 | """
342 | payload = bytearray((0x03, row, 0, 0))
343 | for _ in range(50):
344 | payload.append(0)
345 |
346 | packet = MSPPacket()
347 | packet.set_function(MSPTypes.MSP_ELRS_SET_OSD)
348 | packet.set_payload(payload)
349 | self.send_msp(packet)
350 |
351 | def version_request(self):
352 | """
353 | Sends the packet requesting the version of the
354 | backpack hardware
355 | """
356 | packet = MSPPacket()
357 | packet.set_function(MSPTypes.MSP_ELRS_GET_BACKPACK_VERSION)
358 | self.send_msp(packet)
359 |
360 | def activate_bind(self, *_) -> None:
361 | """
362 | Sends a packet to put the connected device in
363 | bind mode
364 | """
365 | message = "Activating backpack's bind mode..."
366 | self._rhapi.ui.message_notify(self._rhapi.language.__(message))
367 |
368 | packet = MSPPacket()
369 | packet.set_function(MSPTypes.MSP_ELRS_BACKPACK_SET_MODE)
370 | payload = bytearray((ord("B"),))
371 | packet.set_payload(payload)
372 | self.send_msp(packet)
373 |
374 | def activate_wifi(self, *_) -> None:
375 | """
376 | Sends a packet to put the connected device in
377 | bind mode
378 | """
379 | message = "Turning on backpack's wifi..."
380 | self._rhapi.ui.message_notify(self._rhapi.language.__(message))
381 |
382 | packet = MSPPacket()
383 | packet.set_function(MSPTypes.MSP_ELRS_BACKPACK_SET_MODE)
384 | payload = bytearray((ord("W"),))
385 | packet.set_payload(payload)
386 | self.send_msp(packet)
387 |
388 | #
389 | # Field Tests
390 | #
391 |
392 | def test_bind_osd(self, *_):
393 | """
394 | A test for checking the connection of the pilot
395 | bound to the timer backpack
396 | """
397 |
398 | def test():
399 | self._queue_lock.acquire()
400 | text = "ROTORHAZARD"
401 | for row in range(18):
402 | self.send_clear_osd()
403 | start_col = self.center_osd(len(text))
404 | self.send_osd_text(row, start_col, text)
405 | self.send_display_osd()
406 |
407 | gevent.sleep(0.5)
408 |
409 | self.send_clear_osd_row(row)
410 | self.send_display_osd()
411 |
412 | gevent.sleep(1)
413 | self.send_clear_osd()
414 | self.send_display_osd()
415 | self._queue_lock.release()
416 |
417 | gevent.spawn(test)
418 |
419 | #
420 | # VRxC Event Triggers
421 | #
422 |
423 | def pilot_alter(self, args: dict) -> None:
424 | """
425 | Logs the uid change of the pilot
426 |
427 | :param args: _description_
428 | """
429 | pilot_id = args["pilot_id"]
430 | uid = self.get_pilot_uid(pilot_id)
431 | uid_formated = ".".join([str(int.from_bytes((byte,))) for byte in uid])
432 | logger.info("Pilot %s's UID set to %s", pilot_id, uid_formated)
433 |
434 | def onRaceStage(self, args) -> None:
435 | """
436 | _summary_
437 |
438 | :param args: _description_
439 | """
440 | if not self._backpack_connected:
441 | return
442 |
443 | use_heat_name = self._rhapi.db.option("_heat_name") == "1"
444 | use_round_num = self._rhapi.db.option("_round_num") == "1"
445 | use_class_name = self._rhapi.db.option("_class_name") == "1"
446 | use_event_name = self._rhapi.db.option("_event_name") == "1"
447 |
448 | # Pull heat name and rounds
449 | heat_data = self._rhapi.db.heat_by_id(args["heat_id"])
450 | if heat_data:
451 | class_id = heat_data.class_id
452 | heat_name = heat_data.display_name
453 | round_num = self._rhapi.db.heat_max_round(args["heat_id"]) + 1
454 | else:
455 | class_id = None
456 | heat_name = None
457 | round_num = None
458 |
459 | # Check class name
460 | if class_id:
461 | raceclass = self._rhapi.db.raceclass_by_id(class_id)
462 | class_name = raceclass.display_name
463 | else:
464 | raceclass = None
465 | class_name = None
466 |
467 | # Generate heat message
468 | heat_name_row = self._rhapi.db.option("_heatname_row")
469 | if all([use_heat_name, use_round_num, heat_name, round_num]):
470 | round_trans = self._rhapi.__("Round")
471 | heat_message = (
472 | f"x {heat_name.upper()} | {round_trans.upper()} {round_num} w"
473 | )
474 | heat_start_col = self.center_osd(len(heat_message))
475 | heat_message_parms = (heat_name_row, heat_start_col, heat_message)
476 | elif use_heat_name and heat_name:
477 | heat_message = f"x {heat_name.upper()} w"
478 | heat_start_col = self.center_osd(len(heat_message))
479 | heat_message_parms = (heat_name_row, heat_start_col, heat_message)
480 | else:
481 | heat_message_parms = None
482 |
483 | # Generate class message
484 | class_name_row = self._rhapi.db.option("_classname_row")
485 | if use_class_name and class_name:
486 | class_message = f"x {class_name.upper()} w"
487 | class_start_col = self.center_osd(len(class_message))
488 | class_message_parms = (class_name_row, class_start_col, class_message)
489 |
490 | # Generate event message
491 | event_name_row = self._rhapi.db.option("_eventname_row")
492 | event_name = self._rhapi.db.option("eventName")
493 | if use_event_name and event_name:
494 | event_name = self._rhapi.db.option("eventName")
495 | event_message = heat_message = f"x {event_name.upper()} w"
496 | event_start_col = self.center_osd(len(heat_message))
497 | event_message_parms = (event_name_row, event_start_col, event_message)
498 |
499 | start_col = self.center_osd(len(self._rhapi.db.option("_racestage_message")))
500 | stage_mesage = (
501 | self._rhapi.db.option("_status_row"),
502 | start_col,
503 | self._rhapi.db.option("_racestage_message"),
504 | )
505 |
506 | # Send stage message to all pilots
507 | def arm(pilot_id):
508 | uid = self.get_pilot_uid(pilot_id)
509 | with self._queue_lock:
510 | self.set_send_uid(uid)
511 | self.send_clear_osd()
512 |
513 | # Send messages to backpack
514 | self.send_osd_text(*stage_mesage)
515 | if use_heat_name and heat_name:
516 | assert heat_message_parms is not None
517 | self.send_osd_text(*heat_message_parms)
518 | if use_class_name and class_name:
519 | self.send_osd_text(*class_message_parms)
520 | if use_event_name and event_name:
521 | self.send_osd_text(*event_message_parms)
522 |
523 | self.send_display_osd()
524 | self.reset_send_uid()
525 |
526 | seat_pilots = self._rhapi.race.pilots
527 | for seat in seat_pilots:
528 | if (
529 | seat_pilots[seat]
530 | and self._rhapi.db.pilot_attribute_value(
531 | seat_pilots[seat], "elrs_active"
532 | )
533 | == "1"
534 | ):
535 | gevent.spawn(arm, seat_pilots[seat])
536 |
537 | def onRaceStart(self, *_) -> None:
538 | if not self._backpack_connected:
539 | return
540 |
541 | def start(pilot_id):
542 | uid = self.get_pilot_uid(pilot_id)
543 | start_col = self.center_osd(
544 | len(self._rhapi.db.option("_racestart_message"))
545 | )
546 |
547 | self._queue_lock.acquire()
548 | self.set_send_uid(uid)
549 |
550 | self.send_clear_osd()
551 |
552 | self.send_osd_text(
553 | self._rhapi.db.option("_status_row"),
554 | start_col,
555 | self._rhapi.db.option("_racestart_message"),
556 | )
557 | self.send_display_osd()
558 | self.reset_send_uid()
559 | self._queue_lock.release()
560 |
561 | gevent.sleep(self._rhapi.db.option("_racestart_uptime") * 1e-1)
562 |
563 | self._queue_lock.acquire()
564 | self.set_send_uid(uid)
565 | self.send_clear_osd_row(self._rhapi.db.option("_status_row"))
566 | self.send_display_osd()
567 | self.reset_send_uid()
568 | self._queue_lock.release()
569 |
570 | seat_pilots = self._rhapi.race.pilots
571 | for seat in seat_pilots:
572 | if (
573 | seat_pilots[seat]
574 | and self._rhapi.db.pilot_attribute_value(
575 | seat_pilots[seat], "elrs_active"
576 | )
577 | == "1"
578 | ):
579 | gevent.spawn(start, seat_pilots[seat])
580 |
581 | def onRaceFinish(self, *_) -> None:
582 | if not self._backpack_connected:
583 | return
584 |
585 | def finish(pilot_id):
586 | uid = self.get_pilot_uid(pilot_id)
587 | start_col = self.center_osd(
588 | len(self._rhapi.db.option("_racefinish_message"))
589 | )
590 |
591 | self._queue_lock.acquire()
592 | self.set_send_uid(uid)
593 | self.send_clear_osd_row(self._rhapi.db.option("_status_row"))
594 | self.send_osd_text(
595 | self._rhapi.db.option("_status_row"),
596 | start_col,
597 | self._rhapi.db.option("_racefinish_message"),
598 | )
599 | self.send_display_osd()
600 | self.reset_send_uid()
601 | self._queue_lock.release()
602 |
603 | gevent.sleep(self._rhapi.db.option("_finish_uptime") * 1e-1)
604 |
605 | self._queue_lock.acquire()
606 | self.set_send_uid(uid)
607 | self.send_clear_osd_row(self._rhapi.db.option("_status_row"))
608 | self.send_display_osd()
609 | self.reset_send_uid()
610 | self._queue_lock.release()
611 |
612 | seat_pilots = self._rhapi.race.pilots
613 | seats_finished = self._rhapi.race.seats_finished
614 |
615 | for seat in seat_pilots:
616 | if (
617 | seat_pilots[seat]
618 | and self._rhapi.db.pilot_attribute_value(
619 | seat_pilots[seat], "elrs_active"
620 | )
621 | == "1"
622 | ):
623 | if not seats_finished[seat]:
624 | gevent.spawn(finish, seat_pilots[seat])
625 |
626 | def onRaceStop(self, *_) -> None:
627 | if not self._backpack_connected:
628 | return
629 |
630 | def land(pilot_id):
631 | uid = self.get_pilot_uid(pilot_id)
632 | start_col = self.center_osd(len(self._rhapi.db.option("_racestop_message")))
633 |
634 | self._queue_lock.acquire()
635 | self.set_send_uid(uid)
636 | self.send_osd_text(
637 | self._rhapi.db.option("_status_row"),
638 | start_col,
639 | self._rhapi.db.option("_racestop_message"),
640 | )
641 | self.send_display_osd()
642 | self.reset_send_uid()
643 | self._queue_lock.release()
644 |
645 | seat_pilots = self._rhapi.race.pilots
646 | seats_finished = self._rhapi.race.seats_finished
647 |
648 | for seat in seat_pilots:
649 | if (
650 | seat_pilots[seat]
651 | and self._rhapi.db.pilot_attribute_value(
652 | seat_pilots[seat], "elrs_active"
653 | )
654 | == "1"
655 | ):
656 | if not seats_finished[seat]:
657 | gevent.spawn(land, seat_pilots[seat])
658 |
659 | def onRaceLapRecorded(self, args: dict) -> None:
660 | if not self._backpack_connected:
661 | return
662 |
663 | def update_pos(result):
664 | pilot_id = result["pilot_id"]
665 |
666 | if self._rhapi.db.option("_position_mode") != "1":
667 | message = f"LAP: {result['laps'] + 1}"
668 | else:
669 | message = f"POSN: {str(result['position']).upper()} | LAP: {result['laps'] + 1}"
670 | start_col = self.center_osd(len(message))
671 |
672 | uid = self.get_pilot_uid(pilot_id)
673 | self._queue_lock.acquire()
674 | self.set_send_uid(uid)
675 | self.send_clear_osd_row(self._rhapi.db.option("_currentlap_row"))
676 |
677 | self.send_osd_text(
678 | self._rhapi.db.option("_currentlap_row"), start_col, message
679 | )
680 | self.send_display_osd()
681 | self.reset_send_uid()
682 | self._queue_lock.release()
683 |
684 | def lap_results(result, gap_info):
685 | pilot_id = result["pilot_id"]
686 |
687 | message = ""
688 | if self._rhapi.db.option("_gap_mode") != "1":
689 | if gap_info.race.win_condition == WinCondition.FASTEST_CONSECUTIVE:
690 | formatted_time1 = self._rhapi.utils.format_split_time_to_str(
691 | gap_info.current.last_lap_time, "{m}:{s}.{d}"
692 | )
693 | formatted_time2 = self._rhapi.utils.format_split_time_to_str(
694 | gap_info.current.consecutives, "{m}:{s}.{d}"
695 | )
696 | message = f"x {formatted_time1} | {gap_info.current.consecutives_base}/{formatted_time2} w"
697 | elif (
698 | gap_info.race.win_condition == WinCondition.FASTEST_LAP
699 | and gap_info.current.is_best
700 | ):
701 | formatted_time = self._rhapi.utils.format_split_time_to_str(
702 | gap_info.current.last_lap_time, "{m}:{s}.{d}"
703 | )
704 | message = f"x BEST LAP | {formatted_time} w"
705 | else:
706 | formatted_time1 = self._rhapi.utils.format_split_time_to_str(
707 | gap_info.current.last_lap_time, "{m}:{s}.{d}"
708 | )
709 | formatted_time2 = self._rhapi.utils.format_split_time_to_str(
710 | gap_info.current.total_time_laps, "{m}:{s}.{d}"
711 | )
712 | message = f"x {formatted_time1} | {formatted_time2} w"
713 |
714 | elif gap_info.race.win_condition == WinCondition.FASTEST_CONSECUTIVE:
715 | formatted_time1 = self._rhapi.utils.format_split_time_to_str(
716 | gap_info.current.last_lap_time, "{m}:{s}.{d}"
717 | )
718 | formatted_time2 = self._rhapi.utils.format_split_time_to_str(
719 | gap_info.current.consecutives, "{m}:{s}.{d}"
720 | )
721 | message = f"x {formatted_time1} | {gap_info.current.consecutives_base}/{formatted_time2} w"
722 |
723 | elif gap_info.race.win_condition == WinCondition.FASTEST_LAP:
724 | if gap_info.next_rank.diff_time:
725 | formatted_time = self._rhapi.utils.format_split_time_to_str(
726 | gap_info.next_rank.diff_time, "{m}:{s}.{d}"
727 | )
728 | formatted_callsign = str.upper(gap_info.next_rank.callsign)
729 | message = f"x {formatted_callsign} | +{formatted_time} w"
730 |
731 | elif gap_info.current.is_best_lap and gap_info.current.lap_number:
732 | formatted_time = self._rhapi.utils.format_split_time_to_str(
733 | gap_info.current.last_lap_time, "{m}:{s}.{d}"
734 | )
735 | message = f"x {self._rhapi.db.option('_leader_message')} | {formatted_time} w"
736 |
737 | elif gap_info.current.lap_number:
738 | formatted_time = self._rhapi.utils.format_split_time_to_str(
739 | gap_info.first_rank.diff_time, "{m}:{s}.{d}"
740 | )
741 | formatted_callsign = str.upper(gap_info.first_rank.callsign)
742 | message = f"x {formatted_callsign} | +{formatted_time} w"
743 |
744 | else:
745 | if gap_info.next_rank.diff_time:
746 | formatted_time = self._rhapi.utils.format_split_time_to_str(
747 | gap_info.next_rank.diff_time, "{m}:{s}.{d}"
748 | )
749 | formatted_callsign = str.upper(gap_info.next_rank.callsign)
750 | message = f"x {formatted_callsign} | +{formatted_time} w"
751 |
752 | elif gap_info.current.lap_number:
753 | formatted_time = self._rhapi.utils.format_split_time_to_str(
754 | gap_info.current.last_lap_time, "{m}:{s}.{d}"
755 | )
756 | message = f"x {self._rhapi.db.option('_leader_message')} | {formatted_time} w"
757 |
758 | start_col = self.center_osd(len(message))
759 |
760 | uid = self.get_pilot_uid(pilot_id)
761 | self._queue_lock.acquire()
762 | self.set_send_uid(uid)
763 | self.send_osd_text(
764 | self._rhapi.db.option("_lapresults_row"), start_col, message
765 | )
766 | self.send_display_osd()
767 | self.reset_send_uid()
768 | self._queue_lock.release()
769 |
770 | gevent.sleep(self._rhapi.db.option("_results_uptime") * 1e-1)
771 |
772 | self._queue_lock.acquire()
773 | self.set_send_uid(uid)
774 | self.send_clear_osd_row(self._rhapi.db.option("_lapresults_row"))
775 | self.send_display_osd()
776 | self.reset_send_uid()
777 | self._queue_lock.release()
778 |
779 | seats_finished = self._rhapi.race.seats_finished
780 | pilots_completion = {}
781 | for slot, pilot_id in self._rhapi.race.pilots.items():
782 | if pilot_id:
783 | pilots_completion[pilot_id] = seats_finished[slot]
784 |
785 | results = args["results"]["by_race_time"]
786 | for result in results:
787 | if (
788 | self._rhapi.db.pilot_attribute_value(result["pilot_id"], "elrs_active")
789 | == "1"
790 | ):
791 | if not pilots_completion[result["pilot_id"]]:
792 | gevent.spawn(update_pos, result)
793 |
794 | if result["pilot_id"] == args["pilot_id"] and (result["laps"] > 0):
795 | gevent.spawn(lap_results, result, args["gap_info"])
796 |
797 | def onLapDelete(self, *_) -> None:
798 | """
799 | Update a pilot's OSD when a they have finished
800 | """
801 | if not self._backpack_connected:
802 | return
803 |
804 | def delete(pilot_id):
805 | uid = self.get_pilot_uid(pilot_id)
806 | self._queue_lock.acquire()
807 | self.set_send_uid(uid)
808 | self.send_clear_osd()
809 | self.send_display_osd()
810 | self.reset_send_uid()
811 | self._queue_lock.release()
812 |
813 | if self._rhapi.db.option("_results_mode") == "1":
814 | seat_pilots = self._rhapi.race.pilots
815 | for seat in seat_pilots:
816 | if (
817 | seat_pilots[seat]
818 | and self._rhapi.db.pilot_attribute_value(
819 | seat_pilots[seat], "elrs_active"
820 | )
821 | == "1"
822 | ):
823 | gevent.spawn(delete, seat_pilots[seat])
824 |
825 | def onRacePilotDone(self, args: dict) -> None:
826 | """
827 | Update a pilot's OSD when a they have finished
828 | """
829 | if not self._backpack_connected:
830 | return
831 |
832 | def done(result, win_condition):
833 | pilot_id = result["pilot_id"]
834 | start_col = self.center_osd(
835 | len(self._rhapi.db.option("_pilotdone_message"))
836 | )
837 | results_row1 = self._rhapi.db.option("_results_row")
838 | results_row2 = results_row1 + 1
839 |
840 | uid = self.get_pilot_uid(pilot_id)
841 | self._queue_lock.acquire()
842 | self.set_send_uid(uid)
843 | self.send_clear_osd_row(self._rhapi.db.option("_currentlap_row"))
844 | self.send_clear_osd_row(self._rhapi.db.option("_status_row"))
845 | self.send_osd_text(
846 | self._rhapi.db.option("_status_row"),
847 | start_col,
848 | self._rhapi.db.option("_pilotdone_message"),
849 | )
850 |
851 | if self._rhapi.db.option("_results_mode") == "1":
852 | placement_message = f"PLACEMENT: {result['position']}"
853 | place_col = self.center_osd(len(placement_message))
854 | self.send_osd_text(results_row1, place_col, placement_message)
855 |
856 | if win_condition == WinCondition.FASTEST_CONSECUTIVE:
857 | win_message = f"FASTEST {result['consecutives_base']} CONSEC: {result['consecutives']}"
858 | elif win_condition == WinCondition.FASTEST_LAP:
859 | win_message = f"FASTEST LAP: {result['fastest_lap']}"
860 | elif win_condition == WinCondition.FIRST_TO_LAP_X:
861 | win_message = f"TOTAL TIME: {result['total_time']}"
862 | else:
863 | win_message = f"LAPS COMPLETED: {result['laps']}"
864 |
865 | win_col = self.center_osd(len(win_message))
866 | self.send_osd_text(results_row2, win_col, win_message)
867 |
868 | self.send_display_osd()
869 | self.reset_send_uid()
870 | self._queue_lock.release()
871 |
872 | gevent.sleep(self._rhapi.db.option("_finish_uptime") * 1e-1)
873 |
874 | self._queue_lock.acquire()
875 | self.set_send_uid(uid)
876 | self.send_clear_osd_row(self._rhapi.db.option("_status_row"))
877 | self.send_display_osd()
878 | self.reset_send_uid()
879 | self._queue_lock.release()
880 |
881 | results = args["results"]
882 | leaderboard = results[results["meta"]["primary_leaderboard"]]
883 | for result in leaderboard:
884 | if (
885 | self._rhapi.db.pilot_attribute_value(args["pilot_id"], "elrs_active")
886 | == "1"
887 | ) and (result["pilot_id"] == args["pilot_id"]):
888 | gevent.spawn(done, result, results["meta"]["win_condition"])
889 | break
890 |
891 | def onLapsClear(self, *_) -> None:
892 | """
893 | Removes data from pilot's OSD when laps are removed from the system
894 | """
895 | if not self._backpack_connected:
896 | return
897 |
898 | def clear(pilot_id):
899 | uid = self.get_pilot_uid(pilot_id)
900 | self._queue_lock.acquire()
901 | self.set_send_uid(uid)
902 | self.send_clear_osd()
903 | self.send_display_osd()
904 | self.reset_send_uid()
905 | self._queue_lock.release()
906 |
907 | seat_pilots = self._rhapi.race.pilots
908 | for seat in seat_pilots:
909 | if (
910 | seat_pilots[seat]
911 | and self._rhapi.db.pilot_attribute_value(
912 | seat_pilots[seat], "elrs_active"
913 | )
914 | == "1"
915 | ):
916 | gevent.spawn(clear, seat_pilots[seat])
917 |
918 | def onSendMessage(self, args: dict | None = None) -> None:
919 | """
920 | Sends custom text to pilots of the active heat
921 | """
922 | if not self._backpack_connected:
923 | return
924 |
925 | if args is None:
926 | return
927 |
928 | def notify(pilot):
929 | uid = self.get_pilot_uid(pilot)
930 | start_col = self.center_osd(len(args["message"]))
931 | self._queue_lock.acquire()
932 | self.set_send_uid(uid)
933 | self.send_osd_text(
934 | self._rhapi.db.option("_announcement_row"),
935 | start_col,
936 | f"x {str.upper(args['message'])} w",
937 | )
938 | self.send_display_osd()
939 | self.reset_send_uid()
940 | self._queue_lock.release()
941 |
942 | gevent.sleep(self._rhapi.db.option("_announcement_uptime") * 1e-1)
943 |
944 | self._queue_lock.acquire()
945 | self.set_send_uid(uid)
946 | self.send_clear_osd_row(self._rhapi.db.option("_announcement_row"))
947 | self.send_display_osd()
948 | self.reset_send_uid()
949 | self._queue_lock.release()
950 |
951 | seat_pilots = self._rhapi.race.pilots
952 | for seat in seat_pilots:
953 | if (
954 | seat_pilots[seat]
955 | and self._rhapi.db.pilot_attribute_value(
956 | seat_pilots[seat], "elrs_active"
957 | )
958 | == "1"
959 | ):
960 | gevent.spawn(notify, seat_pilots[seat])
961 |
--------------------------------------------------------------------------------