Compare commits
19 Commits
c56ffd185f
...
3aadf562fd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3aadf562fd | ||
|
|
f6035231c0 | ||
|
|
d100f7e820 | ||
|
|
944b225a81 | ||
|
|
f22a171c80 | ||
|
|
e5b36e4e96 | ||
|
|
bfa9653bc8 | ||
|
|
63367bab8c | ||
|
|
3f6049c355 | ||
|
|
6503a5c5f4 | ||
|
|
edebc795d9 | ||
|
|
a10c1b5bc5 | ||
|
|
3e10e3e621 | ||
|
|
3f387756ab | ||
|
|
fb44f33bea | ||
|
|
73454a03c8 | ||
|
|
3cac34355f | ||
|
|
a513489835 | ||
|
|
55b42d9ece |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -87,3 +87,4 @@ cython_debug/
|
||||
.devcontainer/devcontainer.json
|
||||
|
||||
output/
|
||||
artifacts/
|
||||
|
||||
11
.vscode/launch.json
vendored
11
.vscode/launch.json
vendored
@@ -4,6 +4,17 @@
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"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",
|
||||
"type": "debugpy",
|
||||
|
||||
201
LICENSE
Normal file
201
LICENSE
Normal 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.
|
||||
25
README.md
25
README.md
@@ -37,7 +37,7 @@ If you prefer to set up the environment manually:
|
||||
1. Create the virtual environment by running:
|
||||
|
||||
```bash
|
||||
python3 -m venv venv
|
||||
python3.12 -m venv venv
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```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:
|
||||
@@ -58,7 +58,6 @@ If you prefer to set up the environment manually:
|
||||
export PYTHONPATH=$PWD
|
||||
```
|
||||
|
||||
|
||||
## Running the simulation
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
|
||||
|
||||
import time
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
|
||||
import time
|
||||
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
|
||||
# Create a Tello instance
|
||||
tello = TelloSimClient()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
|
||||
|
||||
import time
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from typing import Callable
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
|
||||
|
||||
import time
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
|
||||
import time
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
|
||||
|
||||
print(TelloSimClient)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
|
||||
import time
|
||||
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
|
||||
|
||||
# Create a Tello instance
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
|
||||
import time
|
||||
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
|
||||
# Create a Tello instance
|
||||
tello = TelloSimClient()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
import cv2
|
||||
|
||||
# Create a Tello instance
|
||||
|
||||
@@ -2,7 +2,7 @@ import os
|
||||
import cv2
|
||||
import time
|
||||
import numpy as np
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
|
||||
# Initialize and connect
|
||||
tello = TelloSimClient()
|
||||
@@ -20,12 +20,16 @@ tello.streamoff()
|
||||
|
||||
# Prepare directory to save
|
||||
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)
|
||||
|
||||
print("[Example] Saving captured picture to:", artifact_folder_path)
|
||||
|
||||
# Save the frame
|
||||
save_path = os.path.join(artifact_folder_path, "picture.png")
|
||||
cv2.imwrite(save_path, np.array(frame_read.frame))
|
||||
|
||||
|
||||
|
||||
# Land
|
||||
tello.land()
|
||||
@@ -2,7 +2,7 @@ import os
|
||||
from threading import Thread
|
||||
import time
|
||||
from typing import cast
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
|
||||
import cv2
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
|
||||
import time
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
|
||||
import time
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Not verified working on normal Tello!
|
||||
|
||||
from tello_sim.tello_sim_client import TelloSimClient
|
||||
from tello_sim_client import TelloSimClient
|
||||
|
||||
|
||||
import time
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"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
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
ursina
|
||||
PyOpenGL
|
||||
numpy
|
||||
opencv-python
|
||||
ursina==7.0.0
|
||||
PyOpenGL==3.1.9
|
||||
numpy==2.2.3
|
||||
opencv-python==4.11.0.86
|
||||
@@ -1,7 +1,7 @@
|
||||
import os
|
||||
import socket
|
||||
from ursina import *
|
||||
from cv2.typing import MatLike
|
||||
import errno
|
||||
from ursina import * # type: ignore
|
||||
from time import time
|
||||
import cv2
|
||||
from ursina_adapter import UrsinaAdapter
|
||||
@@ -17,10 +17,34 @@ class CommandServer:
|
||||
self.stream_active = False
|
||||
self.last_altitude = 0
|
||||
self._recording_folder = "output/recordings"
|
||||
self.server_socket = None
|
||||
|
||||
if not os.path.exists(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):
|
||||
"""Start capturing screenshots and enable FPV video preview."""
|
||||
if not self.stream_active:
|
||||
@@ -60,13 +84,32 @@ class CommandServer:
|
||||
"""
|
||||
Listens for commands to send to the Simulator
|
||||
"""
|
||||
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
server.bind(('localhost', 9999)) # Port number for communication
|
||||
server.listen(5)
|
||||
print("[Command Listener] Listening on port 9999...")
|
||||
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
|
||||
try:
|
||||
self.server_socket.bind(('localhost', 9999)) # Port number for communication
|
||||
self.server_socket.listen(5)
|
||||
print("[Command Listener] Listening on port 9999...")
|
||||
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, _ = server.accept()
|
||||
conn, _ = self.server_socket.accept()
|
||||
data = conn.recv(1024).decode()
|
||||
if data:
|
||||
print(f"[Command Listener] Received command: {data}")
|
||||
@@ -202,13 +245,25 @@ class CommandServer:
|
||||
conn.send(state.encode())
|
||||
|
||||
elif data == "get_latest_frame":
|
||||
# Save the frame to disk first
|
||||
frame_path = os.path.join(self._recording_folder, "latest_frame.png")
|
||||
# Send frame data directly over TCP instead of using filesystem
|
||||
if self._ursina_adapter.latest_frame is not None:
|
||||
cv2.imwrite(frame_path, self._ursina_adapter.latest_frame)
|
||||
conn.send(frame_path.encode())
|
||||
# Encode frame as PNG in memory
|
||||
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:
|
||||
conn.send(b"N/A")
|
||||
# Send 0 size to indicate no frame
|
||||
conn.send((0).to_bytes(4, byteorder='big'))
|
||||
else:
|
||||
# Send 0 size to indicate no frame available
|
||||
conn.send((0).to_bytes(4, byteorder='big'))
|
||||
|
||||
elif data == "capture_frame":
|
||||
self._ursina_adapter.capture_frame()
|
||||
elif data.startswith("set_speed"):
|
||||
@@ -222,3 +277,10 @@ class CommandServer:
|
||||
self.end()
|
||||
|
||||
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
|
||||
|
||||
@@ -1,21 +1,63 @@
|
||||
from command_server import CommandServer
|
||||
from ursina_adapter import UrsinaAdapter
|
||||
import threading
|
||||
import atexit
|
||||
import signal
|
||||
import sys
|
||||
|
||||
class TelloDroneSim:
|
||||
def __init__(self):
|
||||
self._ursina_adapter = UrsinaAdapter()
|
||||
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
|
||||
def state(self):
|
||||
return self._ursina_adapter
|
||||
|
||||
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.daemon = True
|
||||
server_thread.start()
|
||||
|
||||
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:
|
||||
self._ursina_adapter.tick()
|
||||
@@ -163,7 +163,6 @@ class UrsinaAdapter():
|
||||
scale=(15, 15, 12),
|
||||
position=(-123, 0.0, 260),
|
||||
rotation=(0, 0, 0),
|
||||
collider='none',
|
||||
cast_shadow=True
|
||||
)
|
||||
|
||||
@@ -181,7 +180,6 @@ class UrsinaAdapter():
|
||||
scale=(4, 6.5, 5),
|
||||
position=(-55, 2.5, 260),
|
||||
rotation=(0, -90, 0),
|
||||
collider='none',
|
||||
cast_shadow=True
|
||||
)
|
||||
|
||||
@@ -191,7 +189,6 @@ class UrsinaAdapter():
|
||||
scale=(4, 6.5, 5),
|
||||
position=(25, 2.5, 95),
|
||||
rotation=(0, 90, 0),
|
||||
collider='none',
|
||||
cast_shadow=True
|
||||
)
|
||||
|
||||
@@ -200,7 +197,6 @@ class UrsinaAdapter():
|
||||
scale=(4, 6.5, 5),
|
||||
position=(-55, 2.5, -70),
|
||||
rotation=(0, -90, 0),
|
||||
collider='none',
|
||||
cast_shadow=True
|
||||
)
|
||||
|
||||
@@ -222,7 +218,6 @@ class UrsinaAdapter():
|
||||
scale=(63, 45, 45),
|
||||
position=(-199, 3.0, 380),
|
||||
rotation=(0, 0, 0),
|
||||
collider='None',
|
||||
cast_shadow=True
|
||||
)
|
||||
|
||||
@@ -791,6 +786,7 @@ class UrsinaAdapter():
|
||||
def _motion_complete_callback(self):
|
||||
self.is_moving = False
|
||||
self._execute_next_command()
|
||||
|
||||
def land(self) -> None:
|
||||
if self.is_moving:
|
||||
print("Tello Simulator: Movement in progress. Deferring landing...")
|
||||
@@ -828,7 +824,7 @@ class UrsinaAdapter():
|
||||
|
||||
|
||||
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:
|
||||
print("[Capture] Stream not active. Cannot capture frame.")
|
||||
return
|
||||
@@ -837,11 +833,9 @@ class UrsinaAdapter():
|
||||
print("[Capture] No latest frame available.")
|
||||
return
|
||||
|
||||
frame_path = os.path.join(self.recording_folder, f"frame_{self.frame_count}.png")
|
||||
cv2.imwrite(frame_path, self.latest_frame)
|
||||
self.saved_frames.append(frame_path)
|
||||
# Always increment frame count for tracking
|
||||
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):
|
||||
"""Set drone speed by adjusting acceleration force.
|
||||
@@ -899,7 +893,7 @@ class UrsinaAdapter():
|
||||
|
||||
if self.bezier_mode:
|
||||
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)
|
||||
|
||||
# Bézier point
|
||||
@@ -926,8 +920,6 @@ class UrsinaAdapter():
|
||||
if self.stream_active:
|
||||
self.capture_frame()
|
||||
|
||||
|
||||
|
||||
if not moving:
|
||||
self.pitch_angle = 0 # Reset pitch when not moving
|
||||
|
||||
|
||||
@@ -69,11 +69,52 @@ class TelloSimClient:
|
||||
print(f"[Error] Unable to connect to the simulation at {self.host}:{self.port}")
|
||||
|
||||
def get_frame_read(self) -> BackgroundFrameRead:
|
||||
frame_path = self._request_data('get_latest_frame')
|
||||
if frame_path != "N/A" and os.path.exists(frame_path):
|
||||
image = cv2.imread(frame_path)
|
||||
"""Get the latest frame directly from the simulator over TCP."""
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.connect((self.host, self.port))
|
||||
s.send(b'get_latest_frame')
|
||||
|
||||
# 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 BackgroundFrameRead(frame=cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
|
||||
# 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):
|
||||
Reference in New Issue
Block a user