diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c3002d8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,216 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[codz] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +# Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +# poetry.lock +# poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +# pdm.lock +# pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +# pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# Redis +*.rdb +*.aof +*.pid + +# RabbitMQ +mnesia/ +rabbitmq/ +rabbitmq-data/ + +# ActiveMQ +activemq-data/ + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +.idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore +# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, +# you could uncomment the following to ignore the entire vscode folder +# .vscode/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ + +# Streamlit +.streamlit/secrets.toml diff --git a/README.md b/README.md index 396501f..e7cfd21 100644 --- a/README.md +++ b/README.md @@ -1,107 +1,90 @@ # PepperPlus-RI -## GitHooks +The robot interface is a high-level API for controlling the robot. It implements the API as designed: https://utrechtuniversity.youtrack.cloud/articles/N25B-A-14/RI-CB-Communication. -To activate automatic commits/branch name checks run: - -```shell -git config --local core.hooksPath .githooks -``` - -If your commit fails its either: -branch name != /description-of-branch -commit name != : description of the commit. - : N25B-Num's +This is an implementation for the Pepper robot, using the Pepper SDK and Python 2.7 as required by the SDK. - -## Getting started - -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://git.science.uu.nl/ics/sp/2025/n25b/pepperplus-ri.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://git.science.uu.nl/ics/sp/2025/n25b/pepperplus-ri/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - ## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. + +### Linux (or WSL) + +Start off by installing [Pyenv](https://github.com/pyenv/pyenv?tab=readme-ov-file#installation) and walk through the steps outlined there (be sure to also add it to PATH). Also install the [Python build requirements](https://github.com/pyenv/pyenv/wiki#suggested-build-environment). Afterwards, install Python 2.7 and activate it for your current shell: + +```bash +pyenv install 2.7 +pyenv shell 2.7 +``` + +You can check that this worked by typing + +```bash +python -V +``` + +Which should return `Python 2.7.18`. + +Next, `cd` into this repository and create (and activate) a virtual environment: + +```bash +cd / +python -m pip install virtualenv +python -m virtualenv .venv +source .venv/bin/activate +``` + +Install the required packages with + +```bash +pip install -r requirements.txt +``` + +Now we need to install the NaoQi SDK into our virtual environment, which we need to do manually. Begin by downloading the SDK: + +```bash +wget https://community-static.aldebaran.com/resources/2.5.10/Python%20SDK/pynaoqi-python2.7-2.5.7.1-linux64.tar.gz +``` + +Next, move into the `site-packages` directory and extract the file you just downloaded: + +```bash +cd .venv/lib/python2.7/site-packages/ +tar xvfz /pynaoqi-python2.7-2.5.7.1-linux64.tar.gz +rm /pynaoqi-python2.7-2.5.7.1-linux64.tar.gz +``` + +Lastly, we need to inform our virtual environment where to find our newly installed package: + +```bash +echo /.venv/lib/python2.7/site-packages/pynaoqi-python2.7-2.5.7.1-linux64/lib/python2.7/site-packages/ > pynaoqi-python2.7.pth +``` + +That's it! Verify that it works with + +```bash +python -c "import qi; print(qi)" +``` + +You should now be able to run this project. + +### macOS + +Similar to Linux, but don't bother installing `pyenv` as it won't be able to install Python 2 on Apple Silicon. Instead, install Python 2.7.18 from the [Python website](https://www.python.org/downloads/release/python-2718/). + +Create the virtual environment as described above in the Linux section. Stop at the point where it shows you how to download the NaoQi SDK. Instead, use: + +```shell +curl -OL https://community-static.aldebaran.com/resources/2.5.10/Python%20SDK/pynaoqi-python2.7-2.5.7.1-mac64.tar.gz +``` + +Then resume the steps from above. + + ## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +```shell +cd src +python -m robot_interface.main +``` diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..aee002a --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +pyzmq<16 +pyaudio<=0.2.11 diff --git a/src/robot_interface/__init__.py b/src/robot_interface/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/robot_interface/endpoints/__init__.py b/src/robot_interface/endpoints/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/robot_interface/endpoints/main_receiver.py b/src/robot_interface/endpoints/main_receiver.py new file mode 100644 index 0000000..4ad7846 --- /dev/null +++ b/src/robot_interface/endpoints/main_receiver.py @@ -0,0 +1,48 @@ +import zmq + +from robot_interface.endpoints.receiver_base import ReceiverBase + + +class MainReceiver(ReceiverBase): + def __init__(self, zmq_context, port=5555): + """ + The main receiver endpoint, responsible for handling ping and negotiation requests. + + :param zmq_context: The ZeroMQ context to use. + :type zmq_context: zmq.Context + + :param port: The port to use. + :type port: int + """ + super(MainReceiver, self).__init__("main") + self.create_socket(zmq_context, zmq.REP, port) + + @staticmethod + def _handle_ping(message): + """A simple ping endpoint. Returns the provided data.""" + return {"endpoint": "ping", "data": message.get("data")} + + @staticmethod + def _handle_negotiation(message): + """ + Handle a negotiation request. Will respond with ports that can be used to connect to the robot. + + :param message: The negotiation request message. + :type message: dict + + :return: A response dictionary with a 'ports' key containing a list of ports and their function. + :rtype: dict[str, list[dict]] + """ + # TODO: .../error on all endpoints? + return {"endpoint": "negotiation/error", "data": "The requested endpoint is not implemented."} + + def handle_message(self, message): + if "endpoint" not in message: + return {"endpoint": "error", "data": "No endpoint provided."} + + if message["endpoint"] == "ping": + return self._handle_ping(message) + elif message["endpoint"] == "negotiation": + return self._handle_negotiation(message) + + return {"endpoint": "error", "data": "The requested endpoint is not supported."} diff --git a/src/robot_interface/endpoints/receiver_base.py b/src/robot_interface/endpoints/receiver_base.py new file mode 100644 index 0000000..b3183f7 --- /dev/null +++ b/src/robot_interface/endpoints/receiver_base.py @@ -0,0 +1,21 @@ +from abc import ABCMeta, abstractmethod + +from robot_interface.endpoints.socket_base import SocketBase + + +class ReceiverBase(SocketBase, object): + """Associated with a ZeroMQ socket.""" + __metaclass__ = ABCMeta + + @abstractmethod + def handle_message(self, message): + """ + Handle a message with the receiver. + + :param message: The message to handle. + :type message: dict + + :return: A response message. + :rtype: dict + """ + return {"endpoint": "error", "data": "The requested receiver is not implemented."} diff --git a/src/robot_interface/endpoints/socket_base.py b/src/robot_interface/endpoints/socket_base.py new file mode 100644 index 0000000..a5124f6 --- /dev/null +++ b/src/robot_interface/endpoints/socket_base.py @@ -0,0 +1,38 @@ +from abc import ABCMeta + + +class SocketBase(object): + __metaclass__ = ABCMeta + + name = None + socket = None + + def __init__(self, name): + """ + :param name: The name of the endpoint. + :type name: str + """ + self.name = name + self.socket = None + + def create_socket(self, zmq_context, socket_type, port): + """ + Create a ZeroMQ socket. + + :param zmq_context: The ZeroMQ context to use. + :type zmq_context: zmq.Context + + :param socket_type: The type of socket to create. Use zmq constants, e.g. zmq.SUB or zmq.REP. + :type socket_type: int + + :param port: The port to use. + :type port: int + """ + self.socket = zmq_context.socket(socket_type) + self.socket.connect("tcp://localhost:{}".format(port)) + + def close(self): + """Close the ZeroMQ socket.""" + if not self.socket: return + self.socket.close() + self.socket = None diff --git a/src/robot_interface/main.py b/src/robot_interface/main.py new file mode 100644 index 0000000..a203357 --- /dev/null +++ b/src/robot_interface/main.py @@ -0,0 +1,61 @@ +import logging +import time + +import zmq + +from robot_interface.endpoints.main_receiver import MainReceiver +from robot_interface.state import state + + +def main_loop(context): + """ + Run the main loop, handling all incoming requests like pings, negotiation, actuation, etc. + + :param context: The ZeroMQ context to use. + :type context: zmq.Context + """ + # When creating sockets, remember to add them to the `sockets` list of the state to ensure they're deinitialized + main_receiver = MainReceiver(context) + state.sockets.append(main_receiver) + + # Sockets that can run on the main thread. These sockets' endpoints should not block for long (say 50 ms at most). + receivers = [main_receiver] + + poller = zmq.Poller() + for receiver in receivers: + poller.register(receiver.socket, zmq.POLLIN) + + while True: + if state.exit_event.is_set(): break + socks = dict(poller.poll(100)) + + for receiver in receivers: + if receiver.socket not in socks: continue + + start_time = time.time() + + message = receiver.socket.recv_json() + response = receiver.handle_message(message) + receiver.socket.send_json(response) + + time_spent_ms = (time.time() - start_time) * 1000 + if time_spent_ms > 50: + logging.warn("Endpoint \"%s\" took too long (%.2f ms) on the main thread.", receiver.name, time_spent_ms) + + +def main(): + context = zmq.Context() + + state.initialize() + + try: + main_loop(context) + except KeyboardInterrupt: + print("User interrupted.") + finally: + state.deinitialize() + context.term() + + +if __name__ == "__main__": + main() diff --git a/src/robot_interface/state.py b/src/robot_interface/state.py new file mode 100644 index 0000000..d10cf77 --- /dev/null +++ b/src/robot_interface/state.py @@ -0,0 +1,58 @@ +import logging +import signal +import threading + + +class State(object): + """ + Do not create an instance of this class directly: use the instance `state` below. This state must be initiated once, + probably when your program starts. + + This class is used to share state between threads. For example, when the program is quit, that all threads can + detect this via the `exit_event` property being set. + """ + def __init__(self): + self.is_initialized = False + self.exit_event = None + self.sockets = [] # type: List[SocketBase] + + def initialize(self): + if self.is_initialized: + logging.warn("Already initialized") + return + + self.exit_event = threading.Event() + def handle_exit(_, __): + logging.info("Exiting.") + self.exit_event.set() + signal.signal(signal.SIGINT, handle_exit) + signal.signal(signal.SIGTERM, handle_exit) + + self.is_initialized = True + + def deinitialize(self): + if not self.is_initialized: return + + for socket in self.sockets: + socket.close() + + self.is_initialized = False + + def __getattribute__(self, name): + # Enforce that the state is initialized before accessing any property (aside from the basic ones) + if name in ("initialize", "deinitialize", "is_initialized", "__dict__", "__class__"): + return object.__getattribute__(self, name) + + if not object.__getattribute__(self, "is_initialized"): + # Special case for the exit_event: if the event is set, return it without an error + if name == "exit_event": + exit_event = object.__getattribute__(self, "exit_event") + if exit_event and exit_event.is_set(): return exit_event + + raise RuntimeError("State must be initialized before accessing '%s'" % name) + + return object.__getattribute__(self, name) + + +# Must call `.initialize` before use +state = State()