Compare commits

..

19 Commits

Author SHA1 Message Date
Andrew Johnson
3aadf562fd Add Apache License 2.0
Added the Apache License 2.0 to the project.
2025-11-23 14:20:29 +01:00
Andrew Johnson
f6035231c0 Move the client out of the simulator 2025-11-22 09:44:34 +01:00
Andrew Johnson
d100f7e820 Add space 2025-11-15 14:02:10 +01:00
Andrew Johnson
944b225a81 Remove collider none 2025-11-15 12:28:47 +01:00
Andrew Johnson
f22a171c80 Add conda as a reference 2025-11-15 12:08:52 +01:00
Andrew Johnson
e5b36e4e96 Add extra trusted domain 2025-11-15 12:05:02 +01:00
Andrew Johnson
bfa9653bc8 Add more docs on venv 2025-11-15 11:45:29 +01:00
Andrew Johnson
63367bab8c Lock in python package versions 2025-11-15 11:11:19 +01:00
Andrew Johnson
3f6049c355 Clean code 2025-11-09 13:38:42 +01:00
Andrew Johnson
6503a5c5f4 Merge commit 'edebc795d9df8936dd9311b06bdb06de0fe5d9cb' 2025-11-09 13:31:30 +01:00
Andrew Johnson
edebc795d9 Update examples/5_take_a_picture.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-09 13:31:08 +01:00
Andrew Johnson
a10c1b5bc5 Merge remote-tracking branch 'origin/copilot/sub-pr-2' into andrew/add-dynamic-dev-container-config 2025-11-09 13:30:50 +01:00
copilot-swe-agent[bot]
3e10e3e621 Fix cross-platform errno compatibility
Co-authored-by: anjrew <26453863+anjrew@users.noreply.github.com>
2025-11-09 12:30:13 +00:00
copilot-swe-agent[bot]
3f387756ab Initial plan 2025-11-09 12:27:42 +00:00
Andrew Johnson
fb44f33bea Update to socket based solution 2025-11-09 13:22:41 +01:00
Andrew Johnson
73454a03c8 Remove files on disk 2025-11-09 13:10:05 +01:00
Andrew Johnson
3cac34355f Add sim recording files 2025-11-09 13:00:41 +01:00
Andrew Johnson
a513489835 Add socket cleanup 2025-11-09 12:52:49 +01:00
Andrew Johnson
55b42d9ece Clean up docs 2025-11-09 12:29:34 +01:00
24 changed files with 434 additions and 63 deletions

1
.gitignore vendored
View File

@@ -87,3 +87,4 @@ cython_debug/
.devcontainer/devcontainer.json .devcontainer/devcontainer.json
output/ output/
artifacts/

11
.vscode/launch.json vendored
View File

@@ -4,6 +4,17 @@
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{
"name": "Run Tello Simulator",
"type": "debugpy",
"request": "launch",
"program": "${workspaceFolder}/tello_sim/run_sim.py",
"console": "integratedTerminal",
"justMyCode": true,
"env": {
"PYTHONPATH": "${workspaceFolder}"
}
},
{ {
"name": "Python Debugger: Current File", "name": "Python Debugger: Current File",
"type": "debugpy", "type": "debugpy",

201
LICENSE Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -37,7 +37,7 @@ If you prefer to set up the environment manually:
1. Create the virtual environment by running: 1. Create the virtual environment by running:
```bash ```bash
python3 -m venv venv python3.12 -m venv venv
``` ```
2. Activate the virtual environment by running: 2. Activate the virtual environment by running:
@@ -49,7 +49,7 @@ If you prefer to set up the environment manually:
3. Install the required packages by running: 3. Install the required packages by running:
```bash ```bash
pip install -r requirements.txt pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org -r requirements.txt
``` ```
4. Export the python path by running: 4. Export the python path by running:
@@ -58,7 +58,6 @@ If you prefer to set up the environment manually:
export PYTHONPATH=$PWD export PYTHONPATH=$PWD
``` ```
## Running the simulation ## Running the simulation
To run the simulation, run the following command: To run the simulation, run the following command:
@@ -69,4 +68,22 @@ python tello_sim/run_sim.py
You can try running some of the [examples](./examples) to see how the simulation works. The examples are located in the `examples` folder. You can try running some of the [examples](./examples) to see how the simulation works. The examples are located in the `examples` folder.
Or use the [client](./tello_sim/tello_sim_client.py) class to interact with the simulation server. The client class is located in the `tello_sim` folder. Or use the [client](./tello_sim_client.py) class to interact with the simulation server. The client class is located in the `tello_sim` folder.
## Troubleshooting
- For a specific python version on macOS, consider using [pyenv](https://github.com/pyenv/pyenv?tab=readme-ov-file#b-set-up-your-shell-environment-for-pyenv) to manage multiple python versions.
- Another alternative for macOS users is to use [Homebrew](https://brew.sh/) to install the desired python version:
```bash
brew install python@3.12
```
- Conda users can create an environment with the desired python version:
```bash
conda create -n tello-sim python=3.12
conda activate tello-sim
pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org -r requirements.txt
export PYTHONPATH=$PWD
```

View File

@@ -1,4 +1,4 @@
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
import time import time

View File

@@ -1,8 +1,8 @@
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
import time import time
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
# Create a Tello instance # Create a Tello instance
tello = TelloSimClient() tello = TelloSimClient()

View File

@@ -1,4 +1,4 @@
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
import time import time

View File

@@ -1,5 +1,5 @@
from typing import Callable from typing import Callable
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
import time import time

View File

@@ -1,4 +1,4 @@
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
import time import time

View File

@@ -1,4 +1,4 @@
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
print(TelloSimClient) print(TelloSimClient)

View File

@@ -1,7 +1,7 @@
import time import time
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
# Create a Tello instance # Create a Tello instance

View File

@@ -1,7 +1,7 @@
import time import time
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
# Create a Tello instance # Create a Tello instance
tello = TelloSimClient() tello = TelloSimClient()

View File

@@ -1,4 +1,4 @@
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
import cv2 import cv2
# Create a Tello instance # Create a Tello instance

View File

@@ -2,7 +2,7 @@ import os
import cv2 import cv2
import time import time
import numpy as np import numpy as np
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
# Initialize and connect # Initialize and connect
tello = TelloSimClient() tello = TelloSimClient()
@@ -20,12 +20,16 @@ tello.streamoff()
# Prepare directory to save # Prepare directory to save
script_dir = os.path.dirname(__file__) script_dir = os.path.dirname(__file__)
artifact_folder_path = os.path.join(script_dir, "../../artifacts/images") artifact_folder_path = os.path.join(os.path.dirname(script_dir), "artifacts", "images")
os.makedirs(artifact_folder_path, exist_ok=True) os.makedirs(artifact_folder_path, exist_ok=True)
print("[Example] Saving captured picture to:", artifact_folder_path)
# Save the frame # Save the frame
save_path = os.path.join(artifact_folder_path, "picture.png") save_path = os.path.join(artifact_folder_path, "picture.png")
cv2.imwrite(save_path, np.array(frame_read.frame)) cv2.imwrite(save_path, np.array(frame_read.frame))
# Land # Land
tello.land() tello.land()

View File

@@ -2,7 +2,7 @@ import os
from threading import Thread from threading import Thread
import time import time
from typing import cast from typing import cast
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
import cv2 import cv2

View File

@@ -1,4 +1,4 @@
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
import time import time

View File

@@ -1,4 +1,4 @@
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
import time import time

View File

@@ -1,6 +1,6 @@
# Not verified working on normal Tello! # Not verified working on normal Tello!
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
import time import time

View File

@@ -1,5 +1,5 @@
"Here try to create a script that navigates the drone through a course." "Here try to create a script that navigates the drone through a course."
from tello_sim.tello_sim_client import TelloSimClient from tello_sim_client import TelloSimClient
import time import time

View File

@@ -1,4 +1,4 @@
ursina ursina==7.0.0
PyOpenGL PyOpenGL==3.1.9
numpy numpy==2.2.3
opencv-python opencv-python==4.11.0.86

View File

@@ -1,7 +1,7 @@
import os import os
import socket import socket
from ursina import * import errno
from cv2.typing import MatLike from ursina import * # type: ignore
from time import time from time import time
import cv2 import cv2
from ursina_adapter import UrsinaAdapter from ursina_adapter import UrsinaAdapter
@@ -17,10 +17,34 @@ class CommandServer:
self.stream_active = False self.stream_active = False
self.last_altitude = 0 self.last_altitude = 0
self._recording_folder = "output/recordings" self._recording_folder = "output/recordings"
self.server_socket = None
if not os.path.exists(self._recording_folder): if not os.path.exists(self._recording_folder):
os.makedirs(self._recording_folder) os.makedirs(self._recording_folder)
def check_port_available(self, port: int = 9999) -> bool:
"""
Check if the specified port is available.
Returns True if available, False if in use.
"""
try:
test_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
test_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
test_socket.bind(('localhost', port))
test_socket.close()
return True
except OSError:
return False
def cleanup(self):
"""Clean up resources and close the server socket."""
if self.server_socket:
try:
self.server_socket.close()
print("[Command Listener] Server socket closed.")
except Exception as e:
print(f"[Command Listener] Error closing socket: {e}")
def streamon(self): def streamon(self):
"""Start capturing screenshots and enable FPV video preview.""" """Start capturing screenshots and enable FPV video preview."""
if not self.stream_active: if not self.stream_active:
@@ -60,16 +84,35 @@ class CommandServer:
""" """
Listens for commands to send to the Simulator Listens for commands to send to the Simulator
""" """
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 9999)) # Port number for communication self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.listen(5)
print("[Command Listener] Listening on port 9999...")
while True: try:
conn, _ = server.accept() self.server_socket.bind(('localhost', 9999)) # Port number for communication
data = conn.recv(1024).decode() self.server_socket.listen(5)
if data: print("[Command Listener] Listening on port 9999...")
print(f"[Command Listener] Received command: {data}") except OSError as e:
if e.errno == errno.EADDRINUSE: # Address already in use
print("\n" + "="*70)
print("ERROR: Port 9999 is already in use!")
print("="*70)
print("\nAnother instance of the simulator may be running.")
print("\nTo fix this, run one of these commands in your terminal:")
print(" macOS/Linux: lsof -ti:9999 | xargs kill -9")
print(" Windows: netstat -ano | findstr :9999")
print(" taskkill /PID <PID> /F")
print("\nOr simply restart your computer.")
print("="*70 + "\n")
raise
else:
raise
try:
while True:
conn, _ = self.server_socket.accept()
data = conn.recv(1024).decode()
if data:
print(f"[Command Listener] Received command: {data}")
if data == "connect": if data == "connect":
self._ursina_adapter.connect() self._ursina_adapter.connect()
@@ -202,13 +245,25 @@ class CommandServer:
conn.send(state.encode()) conn.send(state.encode())
elif data == "get_latest_frame": elif data == "get_latest_frame":
# Save the frame to disk first # Send frame data directly over TCP instead of using filesystem
frame_path = os.path.join(self._recording_folder, "latest_frame.png")
if self._ursina_adapter.latest_frame is not None: if self._ursina_adapter.latest_frame is not None:
cv2.imwrite(frame_path, self._ursina_adapter.latest_frame) # Encode frame as PNG in memory
conn.send(frame_path.encode()) success, buffer = cv2.imencode('.png', self._ursina_adapter.latest_frame)
if success:
# Send frame size first (4 bytes)
frame_data = buffer.tobytes()
frame_size = len(frame_data)
conn.send(frame_size.to_bytes(4, byteorder='big'))
# Then send the actual frame data
conn.send(frame_data)
print(f"[Frame Transfer] Sent {frame_size} bytes over TCP")
else:
# Send 0 size to indicate no frame
conn.send((0).to_bytes(4, byteorder='big'))
else: else:
conn.send(b"N/A") # Send 0 size to indicate no frame available
conn.send((0).to_bytes(4, byteorder='big'))
elif data == "capture_frame": elif data == "capture_frame":
self._ursina_adapter.capture_frame() self._ursina_adapter.capture_frame()
elif data.startswith("set_speed"): elif data.startswith("set_speed"):
@@ -221,4 +276,11 @@ class CommandServer:
elif data == "end": elif data == "end":
self.end() self.end()
conn.close() conn.close()
except KeyboardInterrupt:
print("\n[Command Listener] Shutting down...")
self.cleanup()
except Exception as e:
print(f"[Command Listener] Error: {e}")
self.cleanup()
raise

View File

@@ -1,21 +1,63 @@
from command_server import CommandServer from command_server import CommandServer
from ursina_adapter import UrsinaAdapter from ursina_adapter import UrsinaAdapter
import threading import threading
import atexit
import signal
import sys
class TelloDroneSim: class TelloDroneSim:
def __init__(self): def __init__(self):
self._ursina_adapter = UrsinaAdapter() self._ursina_adapter = UrsinaAdapter()
self._server = CommandServer(self._ursina_adapter) self._server = CommandServer(self._ursina_adapter)
# Register cleanup handlers
atexit.register(self.cleanup)
signal.signal(signal.SIGINT, self._signal_handler)
signal.signal(signal.SIGTERM, self._signal_handler)
def _signal_handler(self, signum, frame):
"""Handle termination signals gracefully."""
print("\n[Tello Sim] Received shutdown signal, cleaning up...")
self.cleanup()
sys.exit(0)
def cleanup(self):
"""Clean up resources."""
if hasattr(self, '_server'):
self._server.cleanup()
@property @property
def state(self): def state(self):
return self._ursina_adapter return self._ursina_adapter
def start(self): def start(self):
# Check if port is available before starting
if not self._server.check_port_available(9999):
print("\n" + "="*70)
print("ERROR: Cannot start simulator - Port 9999 is already in use!")
print("="*70)
print("\nAnother instance of the simulator may be running.")
print("\nTo fix this, run one of these commands in your terminal:")
print(" macOS/Linux: lsof -ti:9999 | xargs kill -9")
print(" Windows: netstat -ano | findstr :9999")
print(" taskkill /PID <PID> /F")
print("\nOr simply restart your computer.")
print("="*70 + "\n")
sys.exit(1)
server_thread = threading.Thread(target=self._server.listen) server_thread = threading.Thread(target=self._server.listen)
server_thread.daemon = True server_thread.daemon = True
server_thread.start() server_thread.start()
self._ursina_adapter.run()
try:
self._ursina_adapter.run()
except KeyboardInterrupt:
print("\n[Tello Sim] Interrupted, cleaning up...")
self.cleanup()
except Exception as e:
print(f"[Tello Sim] Error: {e}")
self.cleanup()
raise
def update(self) -> None: def update(self) -> None:
self._ursina_adapter.tick() self._ursina_adapter.tick()

View File

@@ -163,7 +163,6 @@ class UrsinaAdapter():
scale=(15, 15, 12), scale=(15, 15, 12),
position=(-123, 0.0, 260), position=(-123, 0.0, 260),
rotation=(0, 0, 0), rotation=(0, 0, 0),
collider='none',
cast_shadow=True cast_shadow=True
) )
@@ -181,7 +180,6 @@ class UrsinaAdapter():
scale=(4, 6.5, 5), scale=(4, 6.5, 5),
position=(-55, 2.5, 260), position=(-55, 2.5, 260),
rotation=(0, -90, 0), rotation=(0, -90, 0),
collider='none',
cast_shadow=True cast_shadow=True
) )
@@ -191,7 +189,6 @@ class UrsinaAdapter():
scale=(4, 6.5, 5), scale=(4, 6.5, 5),
position=(25, 2.5, 95), position=(25, 2.5, 95),
rotation=(0, 90, 0), rotation=(0, 90, 0),
collider='none',
cast_shadow=True cast_shadow=True
) )
@@ -200,7 +197,6 @@ class UrsinaAdapter():
scale=(4, 6.5, 5), scale=(4, 6.5, 5),
position=(-55, 2.5, -70), position=(-55, 2.5, -70),
rotation=(0, -90, 0), rotation=(0, -90, 0),
collider='none',
cast_shadow=True cast_shadow=True
) )
@@ -222,7 +218,6 @@ class UrsinaAdapter():
scale=(63, 45, 45), scale=(63, 45, 45),
position=(-199, 3.0, 380), position=(-199, 3.0, 380),
rotation=(0, 0, 0), rotation=(0, 0, 0),
collider='None',
cast_shadow=True cast_shadow=True
) )
@@ -791,6 +786,7 @@ class UrsinaAdapter():
def _motion_complete_callback(self): def _motion_complete_callback(self):
self.is_moving = False self.is_moving = False
self._execute_next_command() self._execute_next_command()
def land(self) -> None: def land(self) -> None:
if self.is_moving: if self.is_moving:
print("Tello Simulator: Movement in progress. Deferring landing...") print("Tello Simulator: Movement in progress. Deferring landing...")
@@ -828,7 +824,7 @@ class UrsinaAdapter():
def capture_frame(self): def capture_frame(self):
"""Capture and save the latest FPV frame from update()""" """Capture the latest FPV frame. Optionally save to disk if save_frames_to_disk is True."""
if not self.stream_active: if not self.stream_active:
print("[Capture] Stream not active. Cannot capture frame.") print("[Capture] Stream not active. Cannot capture frame.")
return return
@@ -837,11 +833,9 @@ class UrsinaAdapter():
print("[Capture] No latest frame available.") print("[Capture] No latest frame available.")
return return
frame_path = os.path.join(self.recording_folder, f"frame_{self.frame_count}.png") # Always increment frame count for tracking
cv2.imwrite(frame_path, self.latest_frame)
self.saved_frames.append(frame_path)
self.frame_count += 1 self.frame_count += 1
print(f"[Capture] Screenshot {self.frame_count} saved: {frame_path}") print(f"[Capture] Frame {self.frame_count} captured (memory only)")
def set_speed(self, x: int): def set_speed(self, x: int):
"""Set drone speed by adjusting acceleration force. """Set drone speed by adjusting acceleration force.
@@ -899,7 +893,7 @@ class UrsinaAdapter():
if self.bezier_mode: if self.bezier_mode:
t_now = time() t_now = time()
elapsed = t_now - self.bezier_start_time elapsed = t_now - self.bezier_start_time # type: ignore
t = min(1.0, elapsed / self.bezier_duration) t = min(1.0, elapsed / self.bezier_duration)
# Bézier point # Bézier point
@@ -926,8 +920,6 @@ class UrsinaAdapter():
if self.stream_active: if self.stream_active:
self.capture_frame() self.capture_frame()
if not moving: if not moving:
self.pitch_angle = 0 # Reset pitch when not moving self.pitch_angle = 0 # Reset pitch when not moving

View File

@@ -69,12 +69,53 @@ class TelloSimClient:
print(f"[Error] Unable to connect to the simulation at {self.host}:{self.port}") print(f"[Error] Unable to connect to the simulation at {self.host}:{self.port}")
def get_frame_read(self) -> BackgroundFrameRead: def get_frame_read(self) -> BackgroundFrameRead:
frame_path = self._request_data('get_latest_frame') """Get the latest frame directly from the simulator over TCP."""
if frame_path != "N/A" and os.path.exists(frame_path): try:
image = cv2.imread(frame_path) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
if image is not None: s.connect((self.host, self.port))
return BackgroundFrameRead(frame=cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) s.send(b'get_latest_frame')
return BackgroundFrameRead(frame=np.zeros([360, 640, 3], dtype=np.uint8))
# Receive frame size (4 bytes)
size_data = s.recv(4)
if len(size_data) != 4:
print("[Error] Failed to receive frame size")
return BackgroundFrameRead(frame=np.zeros([360, 640, 3], dtype=np.uint8))
frame_size = int.from_bytes(size_data, byteorder='big')
# If size is 0, no frame available
if frame_size == 0:
print("[Debug] No frame available from simulator")
return BackgroundFrameRead(frame=np.zeros([360, 640, 3], dtype=np.uint8))
# Receive the frame data
frame_data = b''
bytes_received = 0
while bytes_received < frame_size:
chunk = s.recv(min(4096, frame_size - bytes_received))
if not chunk:
break
frame_data += chunk
bytes_received += len(chunk)
# Decode the frame from PNG bytes
if len(frame_data) == frame_size:
nparr = np.frombuffer(frame_data, np.uint8)
image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
if image is not None:
# Return frame in BGR format (OpenCV's native format)
# Users should convert to RGB if needed for display
return BackgroundFrameRead(frame=image)
print("[Error] Failed to decode frame data")
return BackgroundFrameRead(frame=np.zeros([360, 640, 3], dtype=np.uint8))
except ConnectionRefusedError:
print(f"[Error] Unable to connect to the simulation at {self.host}:{self.port}")
return BackgroundFrameRead(frame=np.zeros([360, 640, 3], dtype=np.uint8))
except Exception as e:
print(f"[Error] Failed to get frame: {e}")
return BackgroundFrameRead(frame=np.zeros([360, 640, 3], dtype=np.uint8))
def _request_data(self, command): def _request_data(self, command):
try: try: