Skip to content
Snippets Groups Projects
Commit d7f18ce0 authored by Laurent Frering's avatar Laurent Frering
Browse files

Initial Commit

parents
No related branches found
No related tags found
No related merge requests found
Showing
with 1153 additions and 0 deletions
### Project Specific
secrets/*
.gradle
bin
build
savestates
!savestates/create_savestate.sh
!savestates/load_savestate.sh
### VisualStudioCode template
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
.idea
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Linux template
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### Windows template
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
### macOS template
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$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
# 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
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.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/
### SublimeText template
# Cache files for Sublime Text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
# Workspace files are user-specific
*.sublime-workspace
# Project files should be checked into the repository, unless a significant
# proportion of contributors will probably not be using Sublime Text
# *.sublime-project
# SFTP configuration file
sftp-config.json
sftp-config-alt*.json
# Package control specific files
Package Control.last-run
Package Control.ca-list
Package Control.ca-bundle
Package Control.system-ca-bundle
Package Control.cache/
Package Control.ca-certs/
Package Control.merged-ca-bundle
Package Control.user-ca-bundle
oscrypto-ca-bundle.crt
bh_unicode_properties.cache
# Sublime-github package stores a github token in this file
# https://packagecontrol.io/packages/sublime-github
GitHub.sublime-settings
## protobuf
**/java_msgs/
**/python_msgs
\ No newline at end of file
LICENSE 0 → 100644
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
# Multi-Robot-System Stack
This Project provides a complete docker stack for controlling multi-robot systems via agent-based reasoning. It provides interfaces to adapt to external components (data storage, robots, etc.)
The interfaces to external components are:
- event\_external\_adapter to receive events triggering behaviors
- dispatcher\_data\_external\_adapter to communicate with the database to a) ground symbols into real data, and b) send robot states
- dispatcher\_robot\_external\_adapter to communicate with a given robotic system. This has to be instantiated once for each robot.
# Usage
- Make sure docker engine is running! <br>
- If you need to install docker engine, refer to https://docs.docker.com/engine/install.
- The dsrun.sh script provides a utility for cleanly starting and stopping the stack. Use it with ```./dsrun.sh default``` to test the default project.
# Default project
The default project highlights the basic functionalities of the stack. It implements the following behavior:
external events are predicate in the form _default(X)_ with X being an integer sent over MQTT on the _event/external\_default_ topic. The external event adapter forwards them to the reasoner, who selects the corresponding action _action1(robot1, X)_ to be performed. The Robot Communication Layer first gets corresponding data from the data layer (which simply returns X+1) and refines this action into the skill SkillDefault, which simply counts from X+1 to 10. Once the skill finishes, the action succeeds and this is propagated to the Reasoner which prints that the goal succeeded. Multiple skills can be started simultaneously, and the other event type _goal\_management(X)_ can be used to interrupt all actions that started with X. If an action is interrupted, the last counter value of its skill is recorded, and used as a starting point for next action with the same parameter.
To send a goal, use e.g. Mosquitto command line utilities:
```
sudo apt-get install mosquitto
sudo apt-get install mosquitto-clients
mosquitto_pub -m "default(3)" -t "event/external_default -q 2"
mosquitto_pub -m "default(1)" -t "event/external_default -q 2"
mosquitto_pub -m "goal_management(1)" -t "event/external_default -q 2"
mosquitto_pub -m "default(1)" -t "event/external_default -q 2"
```
The above commands would start a coount from 4 to 10
Then start a count from 2 to 10
Then interrupt the previous count if it was still running
Then resume it from where it left off
# License
This project is licensed under the **GNU Lesser General Public License (LGPL) v3.0** or later.
This means:
- You are free to use, modify, and distribute this software, provided that modifications to this project remain under the same LGPL license.
- If you incorporate this software into another project, you must ensure that users can replace or modify the LGPL-covered portions.
- You must provide access to the source code of any modifications to the LGPL-covered parts.
All components in the components/ folder contain their own `LICENSE` files, specifying that their contents are covered by the LGPL v3.0.
### **Third-Party Code Notice**
This project includes and modifies code from **Jason**, which is licensed under the **LGPL v3.0**.
- The original library can be found at: https://github.com/jason-lang/jason
- Modifications made in this project are also licensed under **LGPL v3.0** and can be found in the following file:
`components/reasoner/jason-main/jason-interpreter/src/main/java/jason/environment/EnvReasoner.java`
**Disclaimer:**
This software is provided **"as is"**, without any warranty of any kind, express or implied, including but not limited to the warranties of **merchantability, fitness for a particular purpose, and noninfringement**. In no event shall the authors be liable for any claim, damages, or other liability arising from the use of this software.
For full details, see the [LICENSE](LICENSE) file.
FROM ros:noetic-ros-core as basis_img
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && apt-get -y install curl python3-venv python3-pip
WORKDIR /usr/src
COPY requirements.txt .
RUN pip3 install -r requirements.txt
COPY . .
CMD ["/bin/sh", "-c", "/bin/sh /opt/ros/noetic/setup.sh;python3 -m data_layer 2>&1 | tee /usr/src/logs/robot_data_layer_$(date +%Y-%m-%d_%H-%M-%S.txt)"]
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
The Data Layer is similar to the EEA, as in it is a pretty freeform module that communicates with the rest of the system via MQTT, and to external modules via arbitrary protocols.
It is made to run on a docker container, using the provided Dockerfile. All the code is python-based, and requirements can be added in requirements.txt
The Docker image builds on a ROS image as that is what was needed for KISecAssist, but a standard Ubuntu image could be used there. There is a bit of work to separate projects a bit better that they currently are.
in \_\_main\_\_.py you will find the entrypoint. This sets the logger (the logging level can be configured in the config file), instantiates an MQTT client (with an arbitrary list of callback functions, left empty in main but that will be populated later), and instantiate the project-specific data layer by importing the module in projects/dl\_{project_name}.py
All the project-specific developments should be made in this file. see projects/dl\_default.py for a barebone example, and projects/dl\_ksa.py for a complex implementation.
The Data layer basically receives requests via MQTT, usually with an object\_id. It processes those requests, and responds with the object\_id accompanied with the processed data. The processing itself is arbitrary and can require communicating to external processes. The content of the message could be a string, or serialized data (e.g. via pickle for python), as long as the object\_id is part of the message.
import os
import importlib
from sys import stdout
from logging import getLogger, basicConfig, info, debug
from data_layer.util import ExitHandler
from data_layer.mqttClient import Client
from data_layer.configuration import config
basicConfig(stream=stdout, level=config.logging.level.upper(), format='[%(levelname).5s]: %(message)s')
getLogger().setLevel(config.logging.level.upper())
if __name__ == '__main__':
project_name = os.environ["PROJECT_NAME"]
info(f"Starting Data Layer for project {project_name}...")
callback_list = []
# Dynamic import of project-relevant DL class
module_dl_path = "data_layer.projects" + ".dl_" + project_name
print(f'Importing module from {module_dl_path}')
module_dl = importlib.import_module(module_dl_path)
mqttc = Client([])
data_layer = module_dl.DataLayer(mqttc)
mqttc.will_set("module_status/data_layer", "offline", 2, True)
mqttc.connect(host="localhost")
mqttc.publish("module_status/data_layer", payload="online", retain=True)
exit_handler = ExitHandler()
mqttc.loop_start()
exit_handler.wait()
mqttc.publish("module_status/data_layer", payload="offline", retain=True)
mqttc.loop_stop()
debug("Data Layer Stopped!")
logging:
level: debug
from logging import debug
from yaml import safe_load
from python_json_config import ConfigBuilder
from python_json_config.validators import network_validators
def _define_config():
# Log Level
log_levels = ['CRITICAL', 'FATAL', 'ERROR', 'WARN', 'WARNING', 'INFO', 'DEBUG']
log_level_error = f"Invalid logging level, must be one of {log_levels}!"
builder.add_required_field("logging.level")
builder.validate_field_type("logging.level", str)
builder.validate_field_value("logging.level", lambda v: (v.upper() in log_levels, log_level_error))
builder = ConfigBuilder()
_define_config()
builder.merge_with_env_variables("CONF")
with open('data_layer/config/default.yaml', mode='r') as f:
config = builder.parse_config(safe_load(f))
import paho.mqtt.client as mqtt
from logging import info, debug
class Client(mqtt.Client):
def __init__(self, callback_list) -> None:
super().__init__()
self.callback_list = callback_list
def on_connect(self, client, userdata, flags, rc):
print("rc: "+str(rc))
for callback_tuple in self.callback_list:
client.subscribe(callback_tuple[0])
client.message_callback_add(callback_tuple[0][0], callback_tuple[1])
def on_connect_fail(self, mqttc, obj):
print("Connect failed")
def on_message(client, userdata, msg):
debug("Recieved message without specific callback")
debug(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
from logging import info, debug, warning, error
import json
import base64
from copy import deepcopy
import threading
import time
import pickle
from logging import info, debug
class DataLayer:
def __init__(self, mqttc):
info("DataLayer Class instance initialization")
self.mqttc = mqttc
callback_tuple = (("datalayer/request", 2), self.requestCB)
self.mqttc.callback_list.append(callback_tuple)
callback_tuple2 = (("datalayer/request_2", 2), self.request2CB)
self.mqttc.callback_list.append(callback_tuple2)
info("DataLayer initialized")
def requestCB(self, client, obj, msg):
'''
Receives a request, processes it, and responds.
We assume that the request is a string, with an id and
an action separated by a semicolon.
The response is serialized via pickle.
'''
info("MESSAGE REQUEST: " + msg.topic + " " + str(msg.qos))
msgstr = msg.payload.decode()
tmp = msgstr.split(";")
action_type = tmp[0]
object_id = tmp[1]
# In this default example, the data is the id + 1
payload_raw = [object_id, action_type, int(object_id) + 1]
payload_serialized = pickle.dumps(payload_raw)
self.mqttc.publish("datalayer/answer", payload=payload_serialized, qos=2)
def request2CB(self, client, obj, msg):
'''
Receives a request, processes it, and responds.
We assume that the request is a string, with an id and
an action separated by a semicolon.
The response is a simple string.
'''
info("MESSAGE REQUEST: " + msg.topic + " " + str(msg.qos))
msgstr = msg.payload.decode()
tmp = msgstr.split(";")
action_type = tmp[0]
object_id = tmp[1]
payload = object_id + ";response"
self.mqttc.publish("datalayer/answer", payload=payload, qos=2)
from threading import Event
from signal import signal, SIGTERM, SIGINT
class ExitHandler:
def __init__(self):
signal(SIGTERM, self.graceful_exit)
signal(SIGINT, self.graceful_exit)
self.trigger = Event()
def graceful_exit(self, signum, frame):
self.trigger.set()
def wait(self):
self.trigger.wait()
attrs==23.1.0
jsonschema==4.19.1
msgpack==1.0.7
pyrsistent==0.19.3
python-json-config==1.2.3
PyYAML==6.0.1
SQLAlchemy==2.0.21
GeoAlchemy2==0.14.1
psycopg2-binary==2.9.9
paho-mqtt==1.6.1
inflection==0.5.1
requests
protobuf==3.20.0
pyproj
geojson
Dockerfile
\ No newline at end of file
FROM python:3.11-slim
WORKDIR /usr/src
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
#CMD [ "python", "-m", "event_external_adapter" ]
CMD ["/bin/sh", "-c", "python -m event_external_adapter 2>&1 | tee /usr/src/logs/event_external_adapter$(date +%Y-%m-%d_%H-%M-%S.txt)"]
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
The Event External Adapter (EEA) role's is to interface with external modules generating the events used by the rest of the pipeline.
It is made to work in a docker container, with the Dockerfile building the corresponding image and starting the component.
This component is structured as python package, so the entrypoint is event\_external\_adapter/__main__.py
requirements.txt holds the python package requirements (used when building the image), config/ holds the configuration files, and event\_external\_adapter/ holds the python package.
__main__.py set the logging, registers the project name, and import the project-specific module from the external_adapters/ folder.
For each new project, a new external adapter (named project\_name.py) has to be added in the external\_adapters/ folder. The default one that can be used for templating is default.py
The external adapter makes use of util.py to load the ExitHandler class. This is a simple utility leveraging the signal library to perform a graceful exit.
The external adapter also makes use of mqtt.py, which wraps the MQTT related behaviors for simpler use. Importantly, this included setting up a debugging MQTT subscriber at event/external_{project_name}. in callbacks_projects, the MQTT callback for this debug topic is implemented.
In general, the project-specific development is to be done in the external adapter file. Here, the program has to subscribe to whatever channel is sending the events (MQTT, REST, HTTP, filesystem, ...), and publish the corresponding event to the reasoner. The topic and qos for this are defined in the configuration file at the top level. See ksa.py for a complex example involving setting up a REST server.
The configuration file can be used to change the logging the level and MQTT configuration.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment